blob: ec07fbee0729750351b75d00e834c3258463bac6 [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{
Greg Claytonff39f742011-04-01 00:29:43 +0000137 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
138 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000139}
140
141//----------------------------------------------------------------------
142// Destructor
143//----------------------------------------------------------------------
144ProcessGDBRemote::~ProcessGDBRemote()
145{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000146 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000147 {
148 Host::ThreadCancel (m_debugserver_thread, NULL);
149 thread_result_t thread_result;
150 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
151 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
152 }
Chris Lattner24943d22010-06-08 16:52:24 +0000153 // m_mach_process.UnregisterNotificationCallbacks (this);
154 Clear();
155}
156
157//----------------------------------------------------------------------
158// PluginInterface
159//----------------------------------------------------------------------
160const char *
161ProcessGDBRemote::GetPluginName()
162{
163 return "Process debugging plug-in that uses the GDB remote protocol";
164}
165
166const char *
167ProcessGDBRemote::GetShortPluginName()
168{
169 return GetPluginNameStatic();
170}
171
172uint32_t
173ProcessGDBRemote::GetPluginVersion()
174{
175 return 1;
176}
177
178void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000179ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000180{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000181 if (!force && m_register_info.GetNumRegisters() > 0)
182 return;
183
184 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000185 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000186 uint32_t reg_offset = 0;
187 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000188 StringExtractorGDBRemote::ResponseType response_type;
189 for (response_type = StringExtractorGDBRemote::eResponse;
190 response_type == StringExtractorGDBRemote::eResponse;
191 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000192 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000193 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
194 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000195 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000196 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000197 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000198 response_type = response.GetResponseType();
199 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000200 {
201 std::string name;
202 std::string value;
203 ConstString reg_name;
204 ConstString alt_name;
205 ConstString set_name;
206 RegisterInfo reg_info = { NULL, // Name
207 NULL, // Alt name
208 0, // byte size
209 reg_offset, // offset
210 eEncodingUint, // encoding
211 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000212 {
213 LLDB_INVALID_REGNUM, // GCC reg num
214 LLDB_INVALID_REGNUM, // DWARF reg num
215 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000216 reg_num, // GDB reg num
217 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000218 }
219 };
220
221 while (response.GetNameColonValue(name, value))
222 {
223 if (name.compare("name") == 0)
224 {
225 reg_name.SetCString(value.c_str());
226 }
227 else if (name.compare("alt-name") == 0)
228 {
229 alt_name.SetCString(value.c_str());
230 }
231 else if (name.compare("bitsize") == 0)
232 {
233 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
234 }
235 else if (name.compare("offset") == 0)
236 {
237 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000238 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000239 {
240 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000241 }
242 }
243 else if (name.compare("encoding") == 0)
244 {
245 if (value.compare("uint") == 0)
246 reg_info.encoding = eEncodingUint;
247 else if (value.compare("sint") == 0)
248 reg_info.encoding = eEncodingSint;
249 else if (value.compare("ieee754") == 0)
250 reg_info.encoding = eEncodingIEEE754;
251 else if (value.compare("vector") == 0)
252 reg_info.encoding = eEncodingVector;
253 }
254 else if (name.compare("format") == 0)
255 {
256 if (value.compare("binary") == 0)
257 reg_info.format = eFormatBinary;
258 else if (value.compare("decimal") == 0)
259 reg_info.format = eFormatDecimal;
260 else if (value.compare("hex") == 0)
261 reg_info.format = eFormatHex;
262 else if (value.compare("float") == 0)
263 reg_info.format = eFormatFloat;
264 else if (value.compare("vector-sint8") == 0)
265 reg_info.format = eFormatVectorOfSInt8;
266 else if (value.compare("vector-uint8") == 0)
267 reg_info.format = eFormatVectorOfUInt8;
268 else if (value.compare("vector-sint16") == 0)
269 reg_info.format = eFormatVectorOfSInt16;
270 else if (value.compare("vector-uint16") == 0)
271 reg_info.format = eFormatVectorOfUInt16;
272 else if (value.compare("vector-sint32") == 0)
273 reg_info.format = eFormatVectorOfSInt32;
274 else if (value.compare("vector-uint32") == 0)
275 reg_info.format = eFormatVectorOfUInt32;
276 else if (value.compare("vector-float32") == 0)
277 reg_info.format = eFormatVectorOfFloat32;
278 else if (value.compare("vector-uint128") == 0)
279 reg_info.format = eFormatVectorOfUInt128;
280 }
281 else if (name.compare("set") == 0)
282 {
283 set_name.SetCString(value.c_str());
284 }
285 else if (name.compare("gcc") == 0)
286 {
287 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
288 }
289 else if (name.compare("dwarf") == 0)
290 {
291 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
292 }
293 else if (name.compare("generic") == 0)
294 {
295 if (value.compare("pc") == 0)
296 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
297 else if (value.compare("sp") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
299 else if (value.compare("fp") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
301 else if (value.compare("ra") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
303 else if (value.compare("flags") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
305 }
306 }
307
Jason Molenda53d96862010-06-11 23:44:18 +0000308 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000309 assert (reg_info.byte_size != 0);
310 reg_offset += reg_info.byte_size;
311 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
312 }
313 }
314 else
315 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000316 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000317 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000318 }
319 }
320
321 if (reg_num == 0)
322 {
323 // We didn't get anything. See if we are debugging ARM and fill with
324 // a hard coded register set until we can get an updated debugserver
325 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000326 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000327 m_register_info.HardcodeARMRegisters();
328 }
329 m_register_info.Finalize ();
330}
331
332Error
333ProcessGDBRemote::WillLaunch (Module* module)
334{
335 return WillLaunchOrAttach ();
336}
337
338Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000339ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000340{
341 return WillLaunchOrAttach ();
342}
343
344Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000345ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000346{
347 return WillLaunchOrAttach ();
348}
349
350Error
Greg Claytone71e2582011-02-04 01:58:07 +0000351ProcessGDBRemote::DoConnectRemote (const char *remote_url)
352{
353 Error error (WillLaunchOrAttach ());
354
355 if (error.Fail())
356 return error;
357
358 if (strncmp (remote_url, "connect://", strlen ("connect://")) == 0)
359 {
360 error = ConnectToDebugserver (remote_url);
361 }
362 else
363 {
364 error.SetErrorStringWithFormat ("unsupported remote url: %s", remote_url);
365 }
366
367 if (error.Fail())
368 return error;
369 StartAsyncThread ();
370
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000371 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000372 if (pid == LLDB_INVALID_PROCESS_ID)
373 {
374 // We don't have a valid process ID, so note that we are connected
375 // and could now request to launch or attach, or get remote process
376 // listings...
377 SetPrivateState (eStateConnected);
378 }
379 else
380 {
381 // We have a valid process
382 SetID (pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000383 UpdateThreadListIfNeeded ();
Greg Claytone71e2582011-02-04 01:58:07 +0000384 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000385 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000386 {
387 const StateType state = SetThreadStopInfo (response);
388 if (state == eStateStopped)
389 {
390 SetPrivateState (state);
391 }
392 else
393 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
394 }
395 else
396 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
397 }
398 return error;
399}
400
401Error
Chris Lattner24943d22010-06-08 16:52:24 +0000402ProcessGDBRemote::WillLaunchOrAttach ()
403{
404 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000405 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000406 return error;
407}
408
409//----------------------------------------------------------------------
410// Process Control
411//----------------------------------------------------------------------
412Error
413ProcessGDBRemote::DoLaunch
414(
415 Module* module,
416 char const *argv[],
417 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000418 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000419 const char *stdin_path,
420 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000421 const char *stderr_path,
422 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000423)
424{
Greg Clayton4b407112010-09-30 21:49:03 +0000425 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000426 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
427 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
428 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000429
430 ObjectFile * object_file = module->GetObjectFile();
431 if (object_file)
432 {
433 ArchSpec inferior_arch(module->GetArchitecture());
434 char host_port[128];
435 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000436 char connect_url[128];
437 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000438
Greg Claytona2f74232011-02-24 22:24:29 +0000439 // Make sure we aren't already connected?
440 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000441 {
442 error = StartDebugserverProcess (host_port,
443 NULL,
444 NULL,
Chris Lattner24943d22010-06-08 16:52:24 +0000445 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000446 NULL,
447 false,
Chris Lattner24943d22010-06-08 16:52:24 +0000448 inferior_arch);
449 if (error.Fail())
450 return error;
451
Greg Claytone71e2582011-02-04 01:58:07 +0000452 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000453 }
454
455 if (error.Success())
456 {
457 lldb_utility::PseudoTerminal pty;
458 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000459
460 // If the debugserver is local and we aren't disabling STDIO, lets use
461 // a pseudo terminal to instead of relying on the 'O' packets for stdio
462 // since 'O' packets can really slow down debugging if the inferior
463 // does a lot of output.
464 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000465 {
466 const char *slave_name = NULL;
467 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000468 {
Greg Claytona2f74232011-02-24 22:24:29 +0000469 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
470 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000471 }
Greg Claytona2f74232011-02-24 22:24:29 +0000472 if (stdin_path == NULL)
473 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000474
Greg Claytona2f74232011-02-24 22:24:29 +0000475 if (stdout_path == NULL)
476 stdout_path = slave_name;
477
478 if (stderr_path == NULL)
479 stderr_path = slave_name;
480 }
481
Greg Claytonafb81862011-03-02 21:34:46 +0000482 // Set STDIN to /dev/null if we want STDIO disabled or if either
483 // STDOUT or STDERR have been set to something and STDIN hasn't
484 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000485 stdin_path = "/dev/null";
486
Greg Claytonafb81862011-03-02 21:34:46 +0000487 // Set STDOUT to /dev/null if we want STDIO disabled or if either
488 // STDIN or STDERR have been set to something and STDOUT hasn't
489 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000490 stdout_path = "/dev/null";
491
Greg Claytonafb81862011-03-02 21:34:46 +0000492 // Set STDERR to /dev/null if we want STDIO disabled or if either
493 // STDIN or STDOUT have been set to something and STDERR hasn't
494 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000495 stderr_path = "/dev/null";
496
497 if (stdin_path)
498 m_gdb_comm.SetSTDIN (stdin_path);
499 if (stdout_path)
500 m_gdb_comm.SetSTDOUT (stdout_path);
501 if (stderr_path)
502 m_gdb_comm.SetSTDERR (stderr_path);
503
504 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
505
506
507 if (working_dir && working_dir[0])
508 {
509 m_gdb_comm.SetWorkingDir (working_dir);
510 }
511
512 // Send the environment and the program + arguments after we connect
513 if (envp)
514 {
515 const char *env_entry;
516 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000517 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000518 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000519 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000520 }
Greg Claytona2f74232011-02-24 22:24:29 +0000521 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000522
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000523 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
524 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
525 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000526 if (arg_packet_err == 0)
527 {
528 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000529 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000530 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000531 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000532 }
533 else
534 {
Greg Claytona2f74232011-02-24 22:24:29 +0000535 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000536 }
Greg Claytona2f74232011-02-24 22:24:29 +0000537 }
538 else
539 {
540 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
541 }
Chris Lattner24943d22010-06-08 16:52:24 +0000542
Greg Claytona2f74232011-02-24 22:24:29 +0000543 if (GetID() == LLDB_INVALID_PROCESS_ID)
544 {
545 KillDebugserverProcess ();
546 return error;
547 }
548
549 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000550 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000551 {
552 SetPrivateState (SetThreadStopInfo (response));
553
554 if (!disable_stdio)
555 {
556 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
557 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
558 }
Chris Lattner24943d22010-06-08 16:52:24 +0000559 }
560 }
Chris Lattner24943d22010-06-08 16:52:24 +0000561 }
562 else
563 {
564 // Set our user ID to an invalid process ID.
565 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000566 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
567 module->GetFileSpec().GetFilename().AsCString(),
568 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000569 }
Chris Lattner24943d22010-06-08 16:52:24 +0000570 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000571
Chris Lattner24943d22010-06-08 16:52:24 +0000572}
573
574
575Error
Greg Claytone71e2582011-02-04 01:58:07 +0000576ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000577{
578 Error error;
579 // Sleep and wait a bit for debugserver to start to listen...
580 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
581 if (conn_ap.get())
582 {
Chris Lattner24943d22010-06-08 16:52:24 +0000583 const uint32_t max_retry_count = 50;
584 uint32_t retry_count = 0;
585 while (!m_gdb_comm.IsConnected())
586 {
Greg Claytone71e2582011-02-04 01:58:07 +0000587 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000588 {
589 m_gdb_comm.SetConnection (conn_ap.release());
590 break;
591 }
592 retry_count++;
593
594 if (retry_count >= max_retry_count)
595 break;
596
597 usleep (100000);
598 }
599 }
600
601 if (!m_gdb_comm.IsConnected())
602 {
603 if (error.Success())
604 error.SetErrorString("not connected to remote gdb server");
605 return error;
606 }
607
Greg Clayton24bc5d92011-03-30 18:16:51 +0000608 // We always seem to be able to open a connection to a local port
609 // so we need to make sure we can then send data to it. If we can't
610 // then we aren't actually connected to anything, so try and do the
611 // handshake with the remote GDB server and make sure that goes
612 // alright.
613 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000614 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000615 m_gdb_comm.Disconnect();
616 if (error.Success())
617 error.SetErrorString("not connected to remote gdb server");
618 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000619 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000620 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
621 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
622 this,
623 m_debugserver_pid,
624 false);
625 m_gdb_comm.ResetDiscoverableSettings();
626 m_gdb_comm.QueryNoAckModeSupported ();
627 m_gdb_comm.GetThreadSuffixSupported ();
628 m_gdb_comm.GetHostInfo ();
629 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000630 return error;
631}
632
633void
634ProcessGDBRemote::DidLaunchOrAttach ()
635{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000636 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
637 if (log)
638 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000639 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000640 {
641 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
642
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000643 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000644
Chris Lattner24943d22010-06-08 16:52:24 +0000645 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000646
Greg Claytoncb8977d2011-03-23 00:09:55 +0000647 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
648 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000649 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000650 ArchSpec &target_arch = GetTarget().GetArchitecture();
651
652 if (target_arch.IsValid())
653 {
654 // If the remote host is ARM and we have apple as the vendor, then
655 // ARM executables and shared libraries can have mixed ARM architectures.
656 // You can have an armv6 executable, and if the host is armv7, then the
657 // system will load the best possible architecture for all shared libraries
658 // it has, so we really need to take the remote host architecture as our
659 // defacto architecture in this case.
660
661 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
662 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
663 {
664 target_arch = gdb_remote_arch;
665 }
666 else
667 {
668 // Fill in what is missing in the triple
669 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
670 llvm::Triple &target_triple = target_arch.GetTriple();
671 if (target_triple.getVendor() == llvm::Triple::UnknownVendor)
672 target_triple.setVendor (remote_triple.getVendor());
673
674 if (target_triple.getOS() == llvm::Triple::UnknownOS)
675 target_triple.setOS (remote_triple.getOS());
676
677 if (target_triple.getEnvironment() == llvm::Triple::UnknownEnvironment)
678 target_triple.setEnvironment (remote_triple.getEnvironment());
679 }
680 }
681 else
682 {
683 // The target doesn't have a valid architecture yet, set it from
684 // the architecture we got from the remote GDB server
685 target_arch = gdb_remote_arch;
686 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000687 }
Chris Lattner24943d22010-06-08 16:52:24 +0000688 }
689}
690
691void
692ProcessGDBRemote::DidLaunch ()
693{
694 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000695}
696
697Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000698ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000699{
700 Error error;
701 // Clear out and clean up from any current state
702 Clear();
Greg Claytona2f74232011-02-24 22:24:29 +0000703 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000704
Chris Lattner24943d22010-06-08 16:52:24 +0000705 if (attach_pid != LLDB_INVALID_PROCESS_ID)
706 {
Greg Claytona2f74232011-02-24 22:24:29 +0000707 // Make sure we aren't already connected?
708 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000709 {
Greg Claytona2f74232011-02-24 22:24:29 +0000710 char host_port[128];
711 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
712 char connect_url[128];
713 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000714
Greg Claytona2f74232011-02-24 22:24:29 +0000715 error = StartDebugserverProcess (host_port, // debugserver_url
716 NULL, // inferior_argv
717 NULL, // inferior_envp
718 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
719 NULL, // Don't send any attach by process name option to debugserver
720 false, // Don't send any attach wait_for_launch flag as an option to debugserver
721 arch_spec);
722
723 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000724 {
Greg Claytona2f74232011-02-24 22:24:29 +0000725 const char *error_string = error.AsCString();
726 if (error_string == NULL)
727 error_string = "unable to launch " DEBUGSERVER_BASENAME;
728
729 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000730 }
Greg Claytona2f74232011-02-24 22:24:29 +0000731 else
732 {
733 error = ConnectToDebugserver (connect_url);
734 }
735 }
736
737 if (error.Success())
738 {
739 char packet[64];
740 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
741
742 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000743 }
744 }
Chris Lattner24943d22010-06-08 16:52:24 +0000745 return error;
746}
747
748size_t
749ProcessGDBRemote::AttachInputReaderCallback
750(
751 void *baton,
752 InputReader *reader,
753 lldb::InputReaderAction notification,
754 const char *bytes,
755 size_t bytes_len
756)
757{
758 if (notification == eInputReaderGotToken)
759 {
760 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
761 if (gdb_process->m_waiting_for_attach)
762 gdb_process->m_waiting_for_attach = false;
763 reader->SetIsDone(true);
764 return 1;
765 }
766 return 0;
767}
768
769Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000770ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000771{
772 Error error;
773 // Clear out and clean up from any current state
774 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000775
Chris Lattner24943d22010-06-08 16:52:24 +0000776 if (process_name && process_name[0])
777 {
Greg Claytona2f74232011-02-24 22:24:29 +0000778 // Make sure we aren't already connected?
779 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000780 {
Chris Lattner24943d22010-06-08 16:52:24 +0000781
Greg Claytona2f74232011-02-24 22:24:29 +0000782 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
783
784 char host_port[128];
785 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
786 char connect_url[128];
787 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
788
789 error = StartDebugserverProcess (host_port, // debugserver_url
790 NULL, // inferior_argv
791 NULL, // inferior_envp
792 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
793 NULL, // Don't send any attach by process name option to debugserver
794 false, // Don't send any attach wait_for_launch flag as an option to debugserver
795 arch_spec);
796 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000797 {
Greg Claytona2f74232011-02-24 22:24:29 +0000798 const char *error_string = error.AsCString();
799 if (error_string == NULL)
800 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000801
Greg Claytona2f74232011-02-24 22:24:29 +0000802 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000803 }
Greg Claytona2f74232011-02-24 22:24:29 +0000804 else
805 {
806 error = ConnectToDebugserver (connect_url);
807 }
808 }
809
810 if (error.Success())
811 {
812 StreamString packet;
813
814 if (wait_for_launch)
815 packet.PutCString("vAttachWait");
816 else
817 packet.PutCString("vAttachName");
818 packet.PutChar(';');
819 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
820
821 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
822
Chris Lattner24943d22010-06-08 16:52:24 +0000823 }
824 }
Chris Lattner24943d22010-06-08 16:52:24 +0000825 return error;
826}
827
Chris Lattner24943d22010-06-08 16:52:24 +0000828
829void
830ProcessGDBRemote::DidAttach ()
831{
Greg Claytone71e2582011-02-04 01:58:07 +0000832 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000833}
834
835Error
836ProcessGDBRemote::WillResume ()
837{
Greg Claytonc1f45872011-02-12 06:28:37 +0000838 m_continue_c_tids.clear();
839 m_continue_C_tids.clear();
840 m_continue_s_tids.clear();
841 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000842 return Error();
843}
844
845Error
846ProcessGDBRemote::DoResume ()
847{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000848 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000849 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
850 if (log)
851 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000852
853 Listener listener ("gdb-remote.resume-packet-sent");
854 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
855 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000856 StreamString continue_packet;
857 bool continue_packet_error = false;
858 if (m_gdb_comm.HasAnyVContSupport ())
859 {
860 continue_packet.PutCString ("vCont");
861
862 if (!m_continue_c_tids.empty())
863 {
864 if (m_gdb_comm.GetVContSupported ('c'))
865 {
866 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)
867 continue_packet.Printf(";c:%4.4x", *t_pos);
868 }
869 else
870 continue_packet_error = true;
871 }
872
873 if (!continue_packet_error && !m_continue_C_tids.empty())
874 {
875 if (m_gdb_comm.GetVContSupported ('C'))
876 {
877 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)
878 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
879 }
880 else
881 continue_packet_error = true;
882 }
Greg Claytonb749a262010-12-03 06:02:24 +0000883
Greg Claytonc1f45872011-02-12 06:28:37 +0000884 if (!continue_packet_error && !m_continue_s_tids.empty())
885 {
886 if (m_gdb_comm.GetVContSupported ('s'))
887 {
888 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)
889 continue_packet.Printf(";s:%4.4x", *t_pos);
890 }
891 else
892 continue_packet_error = true;
893 }
894
895 if (!continue_packet_error && !m_continue_S_tids.empty())
896 {
897 if (m_gdb_comm.GetVContSupported ('S'))
898 {
899 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)
900 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
901 }
902 else
903 continue_packet_error = true;
904 }
905
906 if (continue_packet_error)
907 continue_packet.GetString().clear();
908 }
909 else
910 continue_packet_error = true;
911
912 if (continue_packet_error)
913 {
914 continue_packet_error = false;
915 // Either no vCont support, or we tried to use part of the vCont
916 // packet that wasn't supported by the remote GDB server.
917 // We need to try and make a simple packet that can do our continue
918 const size_t num_threads = GetThreadList().GetSize();
919 const size_t num_continue_c_tids = m_continue_c_tids.size();
920 const size_t num_continue_C_tids = m_continue_C_tids.size();
921 const size_t num_continue_s_tids = m_continue_s_tids.size();
922 const size_t num_continue_S_tids = m_continue_S_tids.size();
923 if (num_continue_c_tids > 0)
924 {
925 if (num_continue_c_tids == num_threads)
926 {
927 // All threads are resuming...
928 SetCurrentGDBRemoteThreadForRun (-1);
929 continue_packet.PutChar ('c');
930 }
931 else if (num_continue_c_tids == 1 &&
932 num_continue_C_tids == 0 &&
933 num_continue_s_tids == 0 &&
934 num_continue_S_tids == 0 )
935 {
936 // Only one thread is continuing
937 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
938 continue_packet.PutChar ('c');
939 }
940 else
941 {
942 // We can't represent this continue packet....
943 continue_packet_error = true;
944 }
945 }
946
947 if (!continue_packet_error && num_continue_C_tids > 0)
948 {
949 if (num_continue_C_tids == num_threads)
950 {
951 const int continue_signo = m_continue_C_tids.front().second;
952 if (num_continue_C_tids > 1)
953 {
954 for (size_t i=1; i<num_threads; ++i)
955 {
956 if (m_continue_C_tids[i].second != continue_signo)
957 continue_packet_error = true;
958 }
959 }
960 if (!continue_packet_error)
961 {
962 // Add threads continuing with the same signo...
963 SetCurrentGDBRemoteThreadForRun (-1);
964 continue_packet.Printf("C%2.2x", continue_signo);
965 }
966 }
967 else if (num_continue_c_tids == 0 &&
968 num_continue_C_tids == 1 &&
969 num_continue_s_tids == 0 &&
970 num_continue_S_tids == 0 )
971 {
972 // Only one thread is continuing with signal
973 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
974 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
975 }
976 else
977 {
978 // We can't represent this continue packet....
979 continue_packet_error = true;
980 }
981 }
982
983 if (!continue_packet_error && num_continue_s_tids > 0)
984 {
985 if (num_continue_s_tids == num_threads)
986 {
987 // All threads are resuming...
988 SetCurrentGDBRemoteThreadForRun (-1);
989 continue_packet.PutChar ('s');
990 }
991 else if (num_continue_c_tids == 0 &&
992 num_continue_C_tids == 0 &&
993 num_continue_s_tids == 1 &&
994 num_continue_S_tids == 0 )
995 {
996 // Only one thread is stepping
997 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
998 continue_packet.PutChar ('s');
999 }
1000 else
1001 {
1002 // We can't represent this continue packet....
1003 continue_packet_error = true;
1004 }
1005 }
1006
1007 if (!continue_packet_error && num_continue_S_tids > 0)
1008 {
1009 if (num_continue_S_tids == num_threads)
1010 {
1011 const int step_signo = m_continue_S_tids.front().second;
1012 // Are all threads trying to step with the same signal?
1013 if (num_continue_S_tids > 1)
1014 {
1015 for (size_t i=1; i<num_threads; ++i)
1016 {
1017 if (m_continue_S_tids[i].second != step_signo)
1018 continue_packet_error = true;
1019 }
1020 }
1021 if (!continue_packet_error)
1022 {
1023 // Add threads stepping with the same signo...
1024 SetCurrentGDBRemoteThreadForRun (-1);
1025 continue_packet.Printf("S%2.2x", step_signo);
1026 }
1027 }
1028 else if (num_continue_c_tids == 0 &&
1029 num_continue_C_tids == 0 &&
1030 num_continue_s_tids == 0 &&
1031 num_continue_S_tids == 1 )
1032 {
1033 // Only one thread is stepping with signal
1034 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1035 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1036 }
1037 else
1038 {
1039 // We can't represent this continue packet....
1040 continue_packet_error = true;
1041 }
1042 }
1043 }
1044
1045 if (continue_packet_error)
1046 {
1047 error.SetErrorString ("can't make continue packet for this resume");
1048 }
1049 else
1050 {
1051 EventSP event_sp;
1052 TimeValue timeout;
1053 timeout = TimeValue::Now();
1054 timeout.OffsetWithSeconds (5);
1055 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1056
1057 if (listener.WaitForEvent (&timeout, event_sp) == false)
1058 error.SetErrorString("Resume timed out.");
1059 }
Greg Claytonb749a262010-12-03 06:02:24 +00001060 }
1061
Jim Ingham3ae449a2010-11-17 02:32:00 +00001062 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001063}
1064
Chris Lattner24943d22010-06-08 16:52:24 +00001065uint32_t
1066ProcessGDBRemote::UpdateThreadListIfNeeded ()
1067{
1068 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001069 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001070 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001071 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1072
Greg Clayton5205f0b2010-09-03 17:10:42 +00001073 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001074 const uint32_t stop_id = GetStopID();
1075 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1076 {
1077 // Update the thread list's stop id immediately so we don't recurse into this function.
1078 ThreadList curr_thread_list (this);
1079 curr_thread_list.SetStopID(stop_id);
1080
1081 Error err;
1082 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001083 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, false);
Greg Clayton61d043b2011-03-22 04:00:09 +00001084 response.IsNormalResponse();
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001085 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001086 {
1087 char ch = response.GetChar();
1088 if (ch == 'l')
1089 break;
1090 if (ch == 'm')
1091 {
1092 do
1093 {
1094 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1095
1096 if (tid != LLDB_INVALID_THREAD_ID)
1097 {
1098 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001099 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001100 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1101 curr_thread_list.AddThread(thread_sp);
1102 }
1103
1104 ch = response.GetChar();
1105 } while (ch == ',');
1106 }
1107 }
1108
1109 m_thread_list = curr_thread_list;
1110
1111 SetThreadStopInfo (m_last_stop_packet);
1112 }
1113 return GetThreadList().GetSize(false);
1114}
1115
1116
1117StateType
1118ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1119{
1120 const char stop_type = stop_packet.GetChar();
1121 switch (stop_type)
1122 {
1123 case 'T':
1124 case 'S':
1125 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001126 if (GetStopID() == 0)
1127 {
1128 // Our first stop, make sure we have a process ID, and also make
1129 // sure we know about our registers
1130 if (GetID() == LLDB_INVALID_PROCESS_ID)
1131 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001132 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001133 if (pid != LLDB_INVALID_PROCESS_ID)
1134 SetID (pid);
1135 }
1136 BuildDynamicRegisterInfo (true);
1137 }
Chris Lattner24943d22010-06-08 16:52:24 +00001138 // Stop with signal and thread info
1139 const uint8_t signo = stop_packet.GetHexU8();
1140 std::string name;
1141 std::string value;
1142 std::string thread_name;
1143 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001144 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001145 uint32_t tid = LLDB_INVALID_THREAD_ID;
1146 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1147 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001148 ThreadSP thread_sp;
1149
Chris Lattner24943d22010-06-08 16:52:24 +00001150 while (stop_packet.GetNameColonValue(name, value))
1151 {
1152 if (name.compare("metype") == 0)
1153 {
1154 // exception type in big endian hex
1155 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1156 }
1157 else if (name.compare("mecount") == 0)
1158 {
1159 // exception count in big endian hex
1160 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1161 }
1162 else if (name.compare("medata") == 0)
1163 {
1164 // exception data in big endian hex
1165 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1166 }
1167 else if (name.compare("thread") == 0)
1168 {
1169 // thread in big endian hex
1170 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001171 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001172 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001173 if (!thread_sp)
1174 {
1175 // Create the thread if we need to
1176 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1177 m_thread_list.AddThread(thread_sp);
1178 }
Chris Lattner24943d22010-06-08 16:52:24 +00001179 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001180 else if (name.compare("hexname") == 0)
1181 {
1182 StringExtractor name_extractor;
1183 // Swap "value" over into "name_extractor"
1184 name_extractor.GetStringRef().swap(value);
1185 // Now convert the HEX bytes into a string value
1186 name_extractor.GetHexByteString (value);
1187 thread_name.swap (value);
1188 }
Chris Lattner24943d22010-06-08 16:52:24 +00001189 else if (name.compare("name") == 0)
1190 {
1191 thread_name.swap (value);
1192 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001193 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001194 {
1195 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1196 }
Greg Claytona875b642011-01-09 21:07:35 +00001197 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1198 {
1199 // We have a register number that contains an expedited
1200 // register value. Lets supply this register to our thread
1201 // so it won't have to go and read it.
1202 if (thread_sp)
1203 {
1204 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1205
1206 if (reg != UINT32_MAX)
1207 {
1208 StringExtractor reg_value_extractor;
1209 // Swap "value" over into "reg_value_extractor"
1210 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001211 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1212 {
1213 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1214 name.c_str(),
1215 reg,
1216 reg,
1217 reg_value_extractor.GetStringRef().c_str(),
1218 stop_packet.GetStringRef().c_str());
1219 }
Greg Claytona875b642011-01-09 21:07:35 +00001220 }
1221 }
1222 }
Chris Lattner24943d22010-06-08 16:52:24 +00001223 }
Chris Lattner24943d22010-06-08 16:52:24 +00001224
1225 if (thread_sp)
1226 {
1227 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1228
1229 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001230 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001231 if (exc_type != 0)
1232 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001233 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001234
1235 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1236 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001237 exc_data_size,
1238 exc_data_size >= 1 ? exc_data[0] : 0,
1239 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001240 }
1241 else if (signo)
1242 {
Greg Clayton643ee732010-08-04 01:40:35 +00001243 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001244 }
1245 else
1246 {
Greg Clayton643ee732010-08-04 01:40:35 +00001247 StopInfoSP invalid_stop_info_sp;
1248 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001249 }
1250 }
1251 return eStateStopped;
1252 }
1253 break;
1254
1255 case 'W':
1256 // process exited
1257 return eStateExited;
1258
1259 default:
1260 break;
1261 }
1262 return eStateInvalid;
1263}
1264
1265void
1266ProcessGDBRemote::RefreshStateAfterStop ()
1267{
Jim Ingham7508e732010-08-09 23:31:02 +00001268 // FIXME - add a variable to tell that we're in the middle of attaching if we
1269 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001270 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001271// if (!GetTarget().GetArchitecture().IsValid())
1272// {
1273// Module *exe_module = GetTarget().GetExecutableModule().get();
1274// if (exe_module)
1275// m_arch_spec = exe_module->GetArchitecture();
1276// }
1277
Chris Lattner24943d22010-06-08 16:52:24 +00001278 // Let all threads recover from stopping and do any clean up based
1279 // on the previous thread state (if any).
1280 m_thread_list.RefreshStateAfterStop();
1281
1282 // Discover new threads:
1283 UpdateThreadListIfNeeded ();
1284}
1285
1286Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001287ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001288{
1289 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001290
Greg Claytona4881d02011-01-22 07:12:45 +00001291 bool timed_out = false;
1292 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001293
1294 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001295 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001296 // We are being asked to halt during an attach. We need to just close
1297 // our file handle and debugserver will go away, and we can be done...
1298 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001299 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001300 else
1301 {
1302 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1303 {
1304 if (timed_out)
1305 error.SetErrorString("timed out sending interrupt packet");
1306 else
1307 error.SetErrorString("unknown error sending interrupt packet");
1308 }
1309 }
Chris Lattner24943d22010-06-08 16:52:24 +00001310 return error;
1311}
1312
1313Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001314ProcessGDBRemote::InterruptIfRunning
1315(
1316 bool discard_thread_plans,
1317 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001318 EventSP &stop_event_sp
1319)
Chris Lattner24943d22010-06-08 16:52:24 +00001320{
1321 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001322
Greg Clayton2860ba92011-01-23 19:58:49 +00001323 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1324
Greg Clayton68ca8232011-01-25 02:58:48 +00001325 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001326 const bool is_running = m_gdb_comm.IsRunning();
1327 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001328 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001329 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001330 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001331 is_running);
1332
Greg Clayton2860ba92011-01-23 19:58:49 +00001333 if (discard_thread_plans)
1334 {
1335 if (log)
1336 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1337 m_thread_list.DiscardThreadPlans();
1338 }
1339 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001340 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001341 if (catch_stop_event)
1342 {
1343 if (log)
1344 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1345 PausePrivateStateThread();
1346 paused_private_state_thread = true;
1347 }
1348
Greg Clayton4fb400f2010-09-27 21:07:38 +00001349 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001350 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001351 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001352
Greg Clayton72e1c782011-01-22 23:43:18 +00001353 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001354 {
1355 if (timed_out)
1356 error.SetErrorString("timed out sending interrupt packet");
1357 else
1358 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001359 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001360 ResumePrivateStateThread();
1361 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001362 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001363
Greg Clayton72e1c782011-01-22 23:43:18 +00001364 if (catch_stop_event)
1365 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001366 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001367 TimeValue timeout_time;
1368 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001369 timeout_time.OffsetWithSeconds(5);
1370 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001371
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001372 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001373 if (log)
1374 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001375
Greg Clayton2860ba92011-01-23 19:58:49 +00001376 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001377 error.SetErrorString("unable to verify target stopped");
1378 }
1379
Greg Clayton68ca8232011-01-25 02:58:48 +00001380 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001381 {
1382 if (log)
1383 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001384 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001385 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001386 }
Chris Lattner24943d22010-06-08 16:52:24 +00001387 return error;
1388}
1389
Greg Clayton4fb400f2010-09-27 21:07:38 +00001390Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001391ProcessGDBRemote::WillDetach ()
1392{
Greg Clayton2860ba92011-01-23 19:58:49 +00001393 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1394 if (log)
1395 log->Printf ("ProcessGDBRemote::WillDetach()");
1396
Greg Clayton72e1c782011-01-22 23:43:18 +00001397 bool discard_thread_plans = true;
1398 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001399 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001400 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001401}
1402
1403Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001404ProcessGDBRemote::DoDetach()
1405{
1406 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001407 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001408 if (log)
1409 log->Printf ("ProcessGDBRemote::DoDetach()");
1410
1411 DisableAllBreakpointSites ();
1412
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001413 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001414
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001415 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1416 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001417 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001418 if (response_size)
1419 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1420 else
1421 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001422 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001423 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001424 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001425
Greg Clayton4fb400f2010-09-27 21:07:38 +00001426 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001427 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001428
1429 SetPrivateState (eStateDetached);
1430 ResumePrivateStateThread();
1431
1432 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001433 return error;
1434}
Chris Lattner24943d22010-06-08 16:52:24 +00001435
1436Error
1437ProcessGDBRemote::DoDestroy ()
1438{
1439 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001440 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001441 if (log)
1442 log->Printf ("ProcessGDBRemote::DoDestroy()");
1443
1444 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001445 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001446 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001447 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001448 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001449 // We are being asked to halt during an attach. We need to just close
1450 // our file handle and debugserver will go away, and we can be done...
1451 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001452 }
1453 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001454 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001455
1456 StringExtractorGDBRemote response;
1457 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001458 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001459 {
1460 char packet_cmd = response.GetChar(0);
1461
1462 if (packet_cmd == 'W' || packet_cmd == 'X')
1463 {
1464 m_last_stop_packet = response;
1465 SetExitStatus(response.GetHexU8(), NULL);
1466 }
1467 }
1468 else
1469 {
1470 SetExitStatus(SIGABRT, NULL);
1471 //error.SetErrorString("kill packet failed");
1472 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001473 }
1474 }
Chris Lattner24943d22010-06-08 16:52:24 +00001475 StopAsyncThread ();
1476 m_gdb_comm.StopReadThread();
1477 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001478 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001479 return error;
1480}
1481
Chris Lattner24943d22010-06-08 16:52:24 +00001482//------------------------------------------------------------------
1483// Process Queries
1484//------------------------------------------------------------------
1485
1486bool
1487ProcessGDBRemote::IsAlive ()
1488{
Greg Clayton58e844b2010-12-08 05:08:21 +00001489 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001490}
1491
1492addr_t
1493ProcessGDBRemote::GetImageInfoAddress()
1494{
1495 if (!m_gdb_comm.IsRunning())
1496 {
1497 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001498 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001499 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001500 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001501 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1502 }
1503 }
1504 return LLDB_INVALID_ADDRESS;
1505}
1506
Chris Lattner24943d22010-06-08 16:52:24 +00001507//------------------------------------------------------------------
1508// Process Memory
1509//------------------------------------------------------------------
1510size_t
1511ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1512{
1513 if (size > m_max_memory_size)
1514 {
1515 // Keep memory read sizes down to a sane limit. This function will be
1516 // called multiple times in order to complete the task by
1517 // lldb_private::Process so it is ok to do this.
1518 size = m_max_memory_size;
1519 }
1520
1521 char packet[64];
1522 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1523 assert (packet_len + 1 < sizeof(packet));
1524 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001525 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001526 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001527 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001528 {
1529 error.Clear();
1530 return response.GetHexBytes(buf, size, '\xdd');
1531 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001532 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001533 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001534 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001535 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1536 else
1537 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1538 }
1539 else
1540 {
1541 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1542 }
1543 return 0;
1544}
1545
1546size_t
1547ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1548{
1549 StreamString packet;
1550 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001551 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001552 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001553 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001554 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001555 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001556 {
1557 error.Clear();
1558 return size;
1559 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001560 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001561 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001562 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001563 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1564 else
1565 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1566 }
1567 else
1568 {
1569 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1570 }
1571 return 0;
1572}
1573
1574lldb::addr_t
1575ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1576{
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001577 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
Chris Lattner24943d22010-06-08 16:52:24 +00001578 if (allocated_addr == LLDB_INVALID_ADDRESS)
1579 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1580 else
1581 error.Clear();
1582 return allocated_addr;
1583}
1584
1585Error
1586ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1587{
1588 Error error;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001589 if (!m_gdb_comm.DeallocateMemory (addr))
Chris Lattner24943d22010-06-08 16:52:24 +00001590 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1591 return error;
1592}
1593
1594
1595//------------------------------------------------------------------
1596// Process STDIO
1597//------------------------------------------------------------------
1598
1599size_t
1600ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1601{
1602 Mutex::Locker locker(m_stdio_mutex);
1603 size_t bytes_available = m_stdout_data.size();
1604 if (bytes_available > 0)
1605 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001606 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1607 if (log)
1608 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001609 if (bytes_available > buf_size)
1610 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001611 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001612 m_stdout_data.erase(0, buf_size);
1613 bytes_available = buf_size;
1614 }
1615 else
1616 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001617 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001618 m_stdout_data.clear();
1619
1620 //ResetEventBits(eBroadcastBitSTDOUT);
1621 }
1622 }
1623 return bytes_available;
1624}
1625
1626size_t
1627ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1628{
1629 // Can we get STDERR through the remote protocol?
1630 return 0;
1631}
1632
1633size_t
1634ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1635{
1636 if (m_stdio_communication.IsConnected())
1637 {
1638 ConnectionStatus status;
1639 m_stdio_communication.Write(src, src_len, status, NULL);
1640 }
1641 return 0;
1642}
1643
1644Error
1645ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1646{
1647 Error error;
1648 assert (bp_site != NULL);
1649
Greg Claytone005f2c2010-11-06 01:53:30 +00001650 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001651 user_id_t site_id = bp_site->GetID();
1652 const addr_t addr = bp_site->GetLoadAddress();
1653 if (log)
1654 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1655
1656 if (bp_site->IsEnabled())
1657 {
1658 if (log)
1659 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1660 return error;
1661 }
1662 else
1663 {
1664 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1665
1666 if (bp_site->HardwarePreferred())
1667 {
1668 // Try and set hardware breakpoint, and if that fails, fall through
1669 // and set a software breakpoint?
1670 }
1671
1672 if (m_z0_supported)
1673 {
1674 char packet[64];
1675 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1676 assert (packet_len + 1 < sizeof(packet));
1677 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001678 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001679 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001680 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001681 {
1682 // Disable z packet support and try again
1683 m_z0_supported = 0;
1684 return EnableBreakpoint (bp_site);
1685 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001686 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001687 {
1688 bp_site->SetEnabled(true);
1689 bp_site->SetType (BreakpointSite::eExternal);
1690 return error;
1691 }
1692 else
1693 {
1694 uint8_t error_byte = response.GetError();
1695 if (error_byte)
1696 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1697 }
1698 }
1699 }
1700 else
1701 {
1702 return EnableSoftwareBreakpoint (bp_site);
1703 }
1704 }
1705
1706 if (log)
1707 {
1708 const char *err_string = error.AsCString();
1709 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1710 bp_site->GetLoadAddress(),
1711 err_string ? err_string : "NULL");
1712 }
1713 // We shouldn't reach here on a successful breakpoint enable...
1714 if (error.Success())
1715 error.SetErrorToGenericError();
1716 return error;
1717}
1718
1719Error
1720ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1721{
1722 Error error;
1723 assert (bp_site != NULL);
1724 addr_t addr = bp_site->GetLoadAddress();
1725 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001726 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001727 if (log)
1728 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1729
1730 if (bp_site->IsEnabled())
1731 {
1732 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1733
1734 if (bp_site->IsHardware())
1735 {
1736 // TODO: disable hardware breakpoint...
1737 }
1738 else
1739 {
1740 if (m_z0_supported)
1741 {
1742 char packet[64];
1743 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1744 assert (packet_len + 1 < sizeof(packet));
1745 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001746 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001747 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001748 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001749 {
1750 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1751 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001752 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001753 {
1754 if (log)
1755 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1756 bp_site->SetEnabled(false);
1757 return error;
1758 }
1759 else
1760 {
1761 uint8_t error_byte = response.GetError();
1762 if (error_byte)
1763 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1764 }
1765 }
1766 }
1767 else
1768 {
1769 return DisableSoftwareBreakpoint (bp_site);
1770 }
1771 }
1772 }
1773 else
1774 {
1775 if (log)
1776 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1777 return error;
1778 }
1779
1780 if (error.Success())
1781 error.SetErrorToGenericError();
1782 return error;
1783}
1784
1785Error
1786ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1787{
1788 Error error;
1789 if (wp)
1790 {
1791 user_id_t watchID = wp->GetID();
1792 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001793 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001794 if (log)
1795 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1796 if (wp->IsEnabled())
1797 {
1798 if (log)
1799 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1800 return error;
1801 }
1802 else
1803 {
1804 // Pass down an appropriate z/Z packet...
1805 error.SetErrorString("watchpoints not supported");
1806 }
1807 }
1808 else
1809 {
1810 error.SetErrorString("Watchpoint location argument was NULL.");
1811 }
1812 if (error.Success())
1813 error.SetErrorToGenericError();
1814 return error;
1815}
1816
1817Error
1818ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1819{
1820 Error error;
1821 if (wp)
1822 {
1823 user_id_t watchID = wp->GetID();
1824
Greg Claytone005f2c2010-11-06 01:53:30 +00001825 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001826
1827 addr_t addr = wp->GetLoadAddress();
1828 if (log)
1829 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1830
1831 if (wp->IsHardware())
1832 {
1833 // Pass down an appropriate z/Z packet...
1834 error.SetErrorString("watchpoints not supported");
1835 }
1836 // TODO: clear software watchpoints if we implement them
1837 }
1838 else
1839 {
1840 error.SetErrorString("Watchpoint location argument was NULL.");
1841 }
1842 if (error.Success())
1843 error.SetErrorToGenericError();
1844 return error;
1845}
1846
1847void
1848ProcessGDBRemote::Clear()
1849{
1850 m_flags = 0;
1851 m_thread_list.Clear();
1852 {
1853 Mutex::Locker locker(m_stdio_mutex);
1854 m_stdout_data.clear();
1855 }
Chris Lattner24943d22010-06-08 16:52:24 +00001856}
1857
1858Error
1859ProcessGDBRemote::DoSignal (int signo)
1860{
1861 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001862 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001863 if (log)
1864 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1865
1866 if (!m_gdb_comm.SendAsyncSignal (signo))
1867 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1868 return error;
1869}
1870
Chris Lattner24943d22010-06-08 16:52:24 +00001871Error
1872ProcessGDBRemote::StartDebugserverProcess
1873(
1874 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1875 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1876 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Clayton23cf0c72010-11-08 04:29:11 +00001877 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 +00001878 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1879 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Claytona2f74232011-02-24 22:24:29 +00001880 const ArchSpec& inferior_arch // The arch of the inferior that we will launch
Chris Lattner24943d22010-06-08 16:52:24 +00001881)
1882{
1883 Error error;
1884 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1885 {
1886 // If we locate debugserver, keep that located version around
1887 static FileSpec g_debugserver_file_spec;
1888
1889 FileSpec debugserver_file_spec;
1890 char debugserver_path[PATH_MAX];
1891
1892 // Always check to see if we have an environment override for the path
1893 // to the debugserver to use and use it if we do.
1894 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1895 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001896 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001897 else
1898 debugserver_file_spec = g_debugserver_file_spec;
1899 bool debugserver_exists = debugserver_file_spec.Exists();
1900 if (!debugserver_exists)
1901 {
1902 // The debugserver binary is in the LLDB.framework/Resources
1903 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001904 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001905 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001906 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001907 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001908 if (debugserver_exists)
1909 {
1910 g_debugserver_file_spec = debugserver_file_spec;
1911 }
1912 else
1913 {
1914 g_debugserver_file_spec.Clear();
1915 debugserver_file_spec.Clear();
1916 }
Chris Lattner24943d22010-06-08 16:52:24 +00001917 }
1918 }
1919
1920 if (debugserver_exists)
1921 {
1922 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1923
1924 m_stdio_communication.Clear();
1925 posix_spawnattr_t attr;
1926
Greg Claytone005f2c2010-11-06 01:53:30 +00001927 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001928
1929 Error local_err; // Errors that don't affect the spawning.
1930 if (log)
Greg Clayton940b1032011-02-23 00:35:02 +00001931 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )",
1932 __FUNCTION__,
1933 debugserver_path,
1934 inferior_argv,
1935 inferior_envp,
1936 inferior_arch.GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +00001937 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1938 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001939 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001940 if (error.Fail())
Greg Clayton940b1032011-02-23 00:35:02 +00001941 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001942
Chris Lattner24943d22010-06-08 16:52:24 +00001943 Args debugserver_args;
1944 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001945
Chris Lattner24943d22010-06-08 16:52:24 +00001946 // Start args with "debugserver /file/path -r --"
1947 debugserver_args.AppendArgument(debugserver_path);
1948 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001949 // use native registers, not the GDB registers
1950 debugserver_args.AppendArgument("--native-regs");
1951 // make debugserver run in its own session so signals generated by
1952 // special terminal key sequences (^C) don't affect debugserver
1953 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001954
Chris Lattner24943d22010-06-08 16:52:24 +00001955 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1956 if (env_debugserver_log_file)
1957 {
1958 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1959 debugserver_args.AppendArgument(arg_cstr);
1960 }
1961
1962 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1963 if (env_debugserver_log_flags)
1964 {
1965 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1966 debugserver_args.AppendArgument(arg_cstr);
1967 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001968// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001969// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001970
1971 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00001972 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00001973 {
Greg Claytona2f74232011-02-24 22:24:29 +00001974 // Terminate the debugserver args so we can now append the inferior args
1975 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00001976
Greg Claytona2f74232011-02-24 22:24:29 +00001977 for (int i = 0; inferior_argv[i] != NULL; ++i)
1978 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00001979 }
1980 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1981 {
1982 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1983 debugserver_args.AppendArgument (arg_cstr);
1984 }
1985 else if (attach_name && attach_name[0])
1986 {
1987 if (wait_for_launch)
1988 debugserver_args.AppendArgument ("--waitfor");
1989 else
1990 debugserver_args.AppendArgument ("--attach");
1991 debugserver_args.AppendArgument (attach_name);
1992 }
1993
1994 Error file_actions_err;
1995 posix_spawn_file_actions_t file_actions;
1996#if DONT_CLOSE_DEBUGSERVER_STDIO
1997 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1998#else
1999 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
2000 if (file_actions_err.Success())
2001 {
2002 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
2003 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
2004 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
2005 }
2006#endif
2007
2008 if (log)
2009 {
2010 StreamString strm;
2011 debugserver_args.Dump (&strm);
2012 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2013 }
2014
Greg Clayton72e1c782011-01-22 23:43:18 +00002015 error.SetError (::posix_spawnp (&m_debugserver_pid,
2016 debugserver_path,
2017 file_actions_err.Success() ? &file_actions : NULL,
2018 &attr,
2019 debugserver_args.GetArgumentVector(),
2020 (char * const*)inferior_envp),
2021 eErrorTypePOSIX);
2022
Greg Claytone9d0df42010-07-02 01:29:13 +00002023
2024 ::posix_spawnattr_destroy (&attr);
2025
Chris Lattner24943d22010-06-08 16:52:24 +00002026 if (file_actions_err.Success())
2027 ::posix_spawn_file_actions_destroy (&file_actions);
2028
2029 // We have seen some cases where posix_spawnp was returning a valid
2030 // looking pid even when an error was returned, so clear it out
2031 if (error.Fail())
2032 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2033
2034 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002035 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 +00002036
Chris Lattner24943d22010-06-08 16:52:24 +00002037 }
2038 else
2039 {
2040 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2041 }
2042
2043 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2044 StartAsyncThread ();
2045 }
2046 return error;
2047}
2048
2049bool
2050ProcessGDBRemote::MonitorDebugserverProcess
2051(
2052 void *callback_baton,
2053 lldb::pid_t debugserver_pid,
2054 int signo, // Zero for no signal
2055 int exit_status // Exit value of process if signal is zero
2056)
2057{
2058 // We pass in the ProcessGDBRemote inferior process it and name it
2059 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2060 // pointer value itself, thus we need the double cast...
2061
2062 // "debugserver_pid" argument passed in is the process ID for
2063 // debugserver that we are tracking...
2064
Greg Clayton75ccf502010-08-21 02:22:51 +00002065 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002066
2067 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2068 if (log)
2069 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2070
Greg Clayton75ccf502010-08-21 02:22:51 +00002071 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002072 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002073 // Sleep for a half a second to make sure our inferior process has
2074 // time to set its exit status before we set it incorrectly when
2075 // both the debugserver and the inferior process shut down.
2076 usleep (500000);
2077 // If our process hasn't yet exited, debugserver might have died.
2078 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002079 const StateType state = process->GetState();
2080
2081 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2082 state != eStateInvalid &&
2083 state != eStateUnloaded &&
2084 state != eStateExited &&
2085 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002086 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002087 char error_str[1024];
2088 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002089 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002090 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2091 if (signal_cstr)
2092 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002093 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002094 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002095 }
2096 else
2097 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002098 ::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 +00002099 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002100
2101 process->SetExitStatus (-1, error_str);
2102 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002103 // Debugserver has exited we need to let our ProcessGDBRemote
2104 // know that it no longer has a debugserver instance
2105 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2106 // We are returning true to this function below, so we can
2107 // forget about the monitor handle.
2108 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002109 }
2110 return true;
2111}
2112
2113void
2114ProcessGDBRemote::KillDebugserverProcess ()
2115{
2116 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2117 {
2118 ::kill (m_debugserver_pid, SIGINT);
2119 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2120 }
2121}
2122
2123void
2124ProcessGDBRemote::Initialize()
2125{
2126 static bool g_initialized = false;
2127
2128 if (g_initialized == false)
2129 {
2130 g_initialized = true;
2131 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2132 GetPluginDescriptionStatic(),
2133 CreateInstance);
2134
2135 Log::Callbacks log_callbacks = {
2136 ProcessGDBRemoteLog::DisableLog,
2137 ProcessGDBRemoteLog::EnableLog,
2138 ProcessGDBRemoteLog::ListLogCategories
2139 };
2140
2141 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2142 }
2143}
2144
2145bool
2146ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2147{
2148 if (m_curr_tid == tid)
2149 return true;
2150
2151 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002152 int packet_len;
2153 if (tid <= 0)
2154 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2155 else
2156 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002157 assert (packet_len + 1 < sizeof(packet));
2158 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002159 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002160 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002161 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002162 {
2163 m_curr_tid = tid;
2164 return true;
2165 }
2166 }
2167 return false;
2168}
2169
2170bool
2171ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2172{
2173 if (m_curr_tid_run == tid)
2174 return true;
2175
2176 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002177 int packet_len;
2178 if (tid <= 0)
2179 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2180 else
2181 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2182
Chris Lattner24943d22010-06-08 16:52:24 +00002183 assert (packet_len + 1 < sizeof(packet));
2184 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002185 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002186 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002187 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002188 {
2189 m_curr_tid_run = tid;
2190 return true;
2191 }
2192 }
2193 return false;
2194}
2195
2196void
2197ProcessGDBRemote::ResetGDBRemoteState ()
2198{
2199 // Reset and GDB remote state
2200 m_curr_tid = LLDB_INVALID_THREAD_ID;
2201 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2202 m_z0_supported = 1;
2203}
2204
2205
2206bool
2207ProcessGDBRemote::StartAsyncThread ()
2208{
2209 ResetGDBRemoteState ();
2210
Greg Claytone005f2c2010-11-06 01:53:30 +00002211 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002212
2213 if (log)
2214 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2215
2216 // Create a thread that watches our internal state and controls which
2217 // events make it to clients (into the DCProcess event queue).
2218 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002219 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002220}
2221
2222void
2223ProcessGDBRemote::StopAsyncThread ()
2224{
Greg Claytone005f2c2010-11-06 01:53:30 +00002225 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002226
2227 if (log)
2228 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2229
2230 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2231
2232 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002233 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002234 {
2235 Host::ThreadJoin (m_async_thread, NULL, NULL);
2236 }
2237}
2238
2239
2240void *
2241ProcessGDBRemote::AsyncThread (void *arg)
2242{
2243 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2244
Greg Claytone005f2c2010-11-06 01:53:30 +00002245 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002246 if (log)
2247 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2248
2249 Listener listener ("ProcessGDBRemote::AsyncThread");
2250 EventSP event_sp;
2251 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2252 eBroadcastBitAsyncThreadShouldExit;
2253
2254 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2255 {
Greg Claytona2f74232011-02-24 22:24:29 +00002256 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2257
Chris Lattner24943d22010-06-08 16:52:24 +00002258 bool done = false;
2259 while (!done)
2260 {
2261 if (log)
2262 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2263 if (listener.WaitForEvent (NULL, event_sp))
2264 {
2265 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002266 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002267 {
Greg Claytona2f74232011-02-24 22:24:29 +00002268 if (log)
2269 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 +00002270
Greg Claytona2f74232011-02-24 22:24:29 +00002271 switch (event_type)
2272 {
2273 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002274 {
Greg Claytona2f74232011-02-24 22:24:29 +00002275 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002276
Greg Claytona2f74232011-02-24 22:24:29 +00002277 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002278 {
Greg Claytona2f74232011-02-24 22:24:29 +00002279 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2280 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2281 if (log)
2282 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002283
Greg Claytona2f74232011-02-24 22:24:29 +00002284 if (::strstr (continue_cstr, "vAttach") == NULL)
2285 process->SetPrivateState(eStateRunning);
2286 StringExtractorGDBRemote response;
2287 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002288
Greg Claytona2f74232011-02-24 22:24:29 +00002289 switch (stop_state)
2290 {
2291 case eStateStopped:
2292 case eStateCrashed:
2293 case eStateSuspended:
2294 process->m_last_stop_packet = response;
2295 process->m_last_stop_packet.SetFilePos (0);
2296 process->SetPrivateState (stop_state);
2297 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002298
Greg Claytona2f74232011-02-24 22:24:29 +00002299 case eStateExited:
2300 process->m_last_stop_packet = response;
2301 process->m_last_stop_packet.SetFilePos (0);
2302 response.SetFilePos(1);
2303 process->SetExitStatus(response.GetHexU8(), NULL);
2304 done = true;
2305 break;
2306
2307 case eStateInvalid:
2308 process->SetExitStatus(-1, "lost connection");
2309 break;
2310
2311 default:
2312 process->SetPrivateState (stop_state);
2313 break;
2314 }
Chris Lattner24943d22010-06-08 16:52:24 +00002315 }
2316 }
Greg Claytona2f74232011-02-24 22:24:29 +00002317 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002318
Greg Claytona2f74232011-02-24 22:24:29 +00002319 case eBroadcastBitAsyncThreadShouldExit:
2320 if (log)
2321 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2322 done = true;
2323 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002324
Greg Claytona2f74232011-02-24 22:24:29 +00002325 default:
2326 if (log)
2327 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2328 done = true;
2329 break;
2330 }
2331 }
2332 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2333 {
2334 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2335 {
2336 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002337 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002338 }
Chris Lattner24943d22010-06-08 16:52:24 +00002339 }
2340 }
2341 else
2342 {
2343 if (log)
2344 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2345 done = true;
2346 }
2347 }
2348 }
2349
2350 if (log)
2351 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2352
2353 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2354 return NULL;
2355}
2356
Chris Lattner24943d22010-06-08 16:52:24 +00002357const char *
2358ProcessGDBRemote::GetDispatchQueueNameForThread
2359(
2360 addr_t thread_dispatch_qaddr,
2361 std::string &dispatch_queue_name
2362)
2363{
2364 dispatch_queue_name.clear();
2365 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2366 {
2367 // Cache the dispatch_queue_offsets_addr value so we don't always have
2368 // to look it up
2369 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2370 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002371 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2372 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002373 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
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
2377 if (dispatch_queue_offsets_symbol == NULL)
2378 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002379 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002380 if (module_sp)
2381 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2382 }
Chris Lattner24943d22010-06-08 16:52:24 +00002383 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002384 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002385
2386 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2387 return NULL;
2388 }
2389
2390 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002391 DataExtractor data (memory_buffer,
2392 sizeof(memory_buffer),
2393 m_target.GetArchitecture().GetByteOrder(),
2394 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002395
2396 // Excerpt from src/queue_private.h
2397 struct dispatch_queue_offsets_s
2398 {
2399 uint16_t dqo_version;
2400 uint16_t dqo_label;
2401 uint16_t dqo_label_size;
2402 } dispatch_queue_offsets;
2403
2404
2405 Error error;
2406 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2407 {
2408 uint32_t data_offset = 0;
2409 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2410 {
2411 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2412 {
2413 data_offset = 0;
2414 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2415 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2416 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2417 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2418 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2419 dispatch_queue_name.erase (bytes_read);
2420 }
2421 }
2422 }
2423 }
2424 if (dispatch_queue_name.empty())
2425 return NULL;
2426 return dispatch_queue_name.c_str();
2427}
2428
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002429//uint32_t
2430//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2431//{
2432// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2433// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2434// if (m_local_debugserver)
2435// {
2436// return Host::ListProcessesMatchingName (name, matches, pids);
2437// }
2438// else
2439// {
2440// // FIXME: Implement talking to the remote debugserver.
2441// return 0;
2442// }
2443//
2444//}
2445//
Jim Ingham55e01d82011-01-22 01:33:44 +00002446bool
2447ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2448 lldb_private::StoppointCallbackContext *context,
2449 lldb::user_id_t break_id,
2450 lldb::user_id_t break_loc_id)
2451{
2452 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2453 // run so I can stop it if that's what I want to do.
2454 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2455 if (log)
2456 log->Printf("Hit New Thread Notification breakpoint.");
2457 return false;
2458}
2459
2460
2461bool
2462ProcessGDBRemote::StartNoticingNewThreads()
2463{
2464 static const char *bp_names[] =
2465 {
2466 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002467 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002468 "_pthread_start",
2469 NULL
2470 };
2471
2472 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2473 size_t num_bps = m_thread_observation_bps.size();
2474 if (num_bps != 0)
2475 {
2476 for (int i = 0; i < num_bps; i++)
2477 {
2478 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2479 if (break_sp)
2480 {
2481 if (log)
2482 log->Printf("Enabled noticing new thread breakpoint.");
2483 break_sp->SetEnabled(true);
2484 }
2485 }
2486 }
2487 else
2488 {
2489 for (int i = 0; bp_names[i] != NULL; i++)
2490 {
2491 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2492 if (breakpoint)
2493 {
2494 if (log)
2495 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2496 m_thread_observation_bps.push_back(breakpoint->GetID());
2497 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2498 }
2499 else
2500 {
2501 if (log)
2502 log->Printf("Failed to create new thread notification breakpoint.");
2503 return false;
2504 }
2505 }
2506 }
2507
2508 return true;
2509}
2510
2511bool
2512ProcessGDBRemote::StopNoticingNewThreads()
2513{
Jim Inghamff276fe2011-02-08 05:19:01 +00002514 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2515 if (log)
2516 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002517 size_t num_bps = m_thread_observation_bps.size();
2518 if (num_bps != 0)
2519 {
2520 for (int i = 0; i < num_bps; i++)
2521 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002522
2523 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2524 if (break_sp)
2525 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002526 break_sp->SetEnabled(false);
2527 }
2528 }
2529 }
2530 return true;
2531}
2532
2533