blob: a2b17e568926dbbd1a9bd9d8411afdcf57baacce [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <sys/types.h>
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000016#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000017
18// C++ Includes
19#include <algorithm>
20#include <map>
21
22// Other libraries and framework includes
23
24#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000025#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000026#include "lldb/Core/ArchSpec.h"
27#include "lldb/Core/Debugger.h"
28#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000029#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/InputReader.h"
31#include "lldb/Core/Module.h"
32#include "lldb/Core/PluginManager.h"
33#include "lldb/Core/State.h"
34#include "lldb/Core/StreamString.h"
35#include "lldb/Core/Timer.h"
36#include "lldb/Host/TimeValue.h"
37#include "lldb/Symbol/ObjectFile.h"
38#include "lldb/Target/DynamicLoader.h"
39#include "lldb/Target/Target.h"
40#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000041#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042
43// Project includes
44#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000045#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046#include "GDBRemoteRegisterContext.h"
47#include "ProcessGDBRemote.h"
48#include "ProcessGDBRemoteLog.h"
49#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000050#include "StopInfoMachException.h"
51
Chris Lattner24943d22010-06-08 16:52:24 +000052
Chris Lattner24943d22010-06-08 16:52:24 +000053
54#define DEBUGSERVER_BASENAME "debugserver"
55using namespace lldb;
56using namespace lldb_private;
57
Jim Inghamf9600482011-03-29 21:45:47 +000058static bool rand_initialized = false;
59
Chris Lattner24943d22010-06-08 16:52:24 +000060static inline uint16_t
61get_random_port ()
62{
Jim Inghamf9600482011-03-29 21:45:47 +000063 if (!rand_initialized)
64 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000065 time_t seed = time(NULL);
66
Jim Inghamf9600482011-03-29 21:45:47 +000067 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000068 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000069 }
Stephen Wilson50daf772011-03-25 18:16:28 +000070 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000071}
72
73
74const char *
75ProcessGDBRemote::GetPluginNameStatic()
76{
Greg Claytonb1888f22011-03-19 01:12:21 +000077 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000078}
79
80const char *
81ProcessGDBRemote::GetPluginDescriptionStatic()
82{
83 return "GDB Remote protocol based debugging plug-in.";
84}
85
86void
87ProcessGDBRemote::Terminate()
88{
89 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
90}
91
92
93Process*
94ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
95{
96 return new ProcessGDBRemote (target, listener);
97}
98
99bool
100ProcessGDBRemote::CanDebug(Target &target)
101{
102 // For now we are just making sure the file exists for a given module
103 ModuleSP exe_module_sp(target.GetExecutableModule());
104 if (exe_module_sp.get())
105 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000106 // However, if there is no executable module, we return true since we might be preparing to attach.
107 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000108}
109
110//----------------------------------------------------------------------
111// ProcessGDBRemote constructor
112//----------------------------------------------------------------------
113ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
114 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000115 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000116 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000117 m_gdb_comm(),
118 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000119 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000120 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000121 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
123 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000124 m_curr_tid (LLDB_INVALID_THREAD_ID),
125 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000126 m_z0_supported (1),
Greg Claytonc1f45872011-02-12 06:28:37 +0000127 m_continue_c_tids (),
128 m_continue_C_tids (),
129 m_continue_s_tids (),
130 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000131 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000132 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000133 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000134 m_local_debugserver (true),
135 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000136{
137}
138
139//----------------------------------------------------------------------
140// Destructor
141//----------------------------------------------------------------------
142ProcessGDBRemote::~ProcessGDBRemote()
143{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000144 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000145 {
146 Host::ThreadCancel (m_debugserver_thread, NULL);
147 thread_result_t thread_result;
148 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
149 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
150 }
Chris Lattner24943d22010-06-08 16:52:24 +0000151 // m_mach_process.UnregisterNotificationCallbacks (this);
152 Clear();
153}
154
155//----------------------------------------------------------------------
156// PluginInterface
157//----------------------------------------------------------------------
158const char *
159ProcessGDBRemote::GetPluginName()
160{
161 return "Process debugging plug-in that uses the GDB remote protocol";
162}
163
164const char *
165ProcessGDBRemote::GetShortPluginName()
166{
167 return GetPluginNameStatic();
168}
169
170uint32_t
171ProcessGDBRemote::GetPluginVersion()
172{
173 return 1;
174}
175
176void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000177ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000178{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000179 if (!force && m_register_info.GetNumRegisters() > 0)
180 return;
181
182 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000183 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000184 uint32_t reg_offset = 0;
185 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000186 StringExtractorGDBRemote::ResponseType response_type;
187 for (response_type = StringExtractorGDBRemote::eResponse;
188 response_type == StringExtractorGDBRemote::eResponse;
189 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000190 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000191 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
192 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000193 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000194 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000195 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000196 response_type = response.GetResponseType();
197 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000198 {
199 std::string name;
200 std::string value;
201 ConstString reg_name;
202 ConstString alt_name;
203 ConstString set_name;
204 RegisterInfo reg_info = { NULL, // Name
205 NULL, // Alt name
206 0, // byte size
207 reg_offset, // offset
208 eEncodingUint, // encoding
209 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000210 {
211 LLDB_INVALID_REGNUM, // GCC reg num
212 LLDB_INVALID_REGNUM, // DWARF reg num
213 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000214 reg_num, // GDB reg num
215 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000216 }
217 };
218
219 while (response.GetNameColonValue(name, value))
220 {
221 if (name.compare("name") == 0)
222 {
223 reg_name.SetCString(value.c_str());
224 }
225 else if (name.compare("alt-name") == 0)
226 {
227 alt_name.SetCString(value.c_str());
228 }
229 else if (name.compare("bitsize") == 0)
230 {
231 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
232 }
233 else if (name.compare("offset") == 0)
234 {
235 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000236 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000237 {
238 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000239 }
240 }
241 else if (name.compare("encoding") == 0)
242 {
243 if (value.compare("uint") == 0)
244 reg_info.encoding = eEncodingUint;
245 else if (value.compare("sint") == 0)
246 reg_info.encoding = eEncodingSint;
247 else if (value.compare("ieee754") == 0)
248 reg_info.encoding = eEncodingIEEE754;
249 else if (value.compare("vector") == 0)
250 reg_info.encoding = eEncodingVector;
251 }
252 else if (name.compare("format") == 0)
253 {
254 if (value.compare("binary") == 0)
255 reg_info.format = eFormatBinary;
256 else if (value.compare("decimal") == 0)
257 reg_info.format = eFormatDecimal;
258 else if (value.compare("hex") == 0)
259 reg_info.format = eFormatHex;
260 else if (value.compare("float") == 0)
261 reg_info.format = eFormatFloat;
262 else if (value.compare("vector-sint8") == 0)
263 reg_info.format = eFormatVectorOfSInt8;
264 else if (value.compare("vector-uint8") == 0)
265 reg_info.format = eFormatVectorOfUInt8;
266 else if (value.compare("vector-sint16") == 0)
267 reg_info.format = eFormatVectorOfSInt16;
268 else if (value.compare("vector-uint16") == 0)
269 reg_info.format = eFormatVectorOfUInt16;
270 else if (value.compare("vector-sint32") == 0)
271 reg_info.format = eFormatVectorOfSInt32;
272 else if (value.compare("vector-uint32") == 0)
273 reg_info.format = eFormatVectorOfUInt32;
274 else if (value.compare("vector-float32") == 0)
275 reg_info.format = eFormatVectorOfFloat32;
276 else if (value.compare("vector-uint128") == 0)
277 reg_info.format = eFormatVectorOfUInt128;
278 }
279 else if (name.compare("set") == 0)
280 {
281 set_name.SetCString(value.c_str());
282 }
283 else if (name.compare("gcc") == 0)
284 {
285 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
286 }
287 else if (name.compare("dwarf") == 0)
288 {
289 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
290 }
291 else if (name.compare("generic") == 0)
292 {
293 if (value.compare("pc") == 0)
294 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
295 else if (value.compare("sp") == 0)
296 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
297 else if (value.compare("fp") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
299 else if (value.compare("ra") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
301 else if (value.compare("flags") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
303 }
304 }
305
Jason Molenda53d96862010-06-11 23:44:18 +0000306 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000307 assert (reg_info.byte_size != 0);
308 reg_offset += reg_info.byte_size;
309 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
310 }
311 }
312 else
313 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000314 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000315 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000316 }
317 }
318
319 if (reg_num == 0)
320 {
321 // We didn't get anything. See if we are debugging ARM and fill with
322 // a hard coded register set until we can get an updated debugserver
323 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000324 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000325 m_register_info.HardcodeARMRegisters();
326 }
327 m_register_info.Finalize ();
328}
329
330Error
331ProcessGDBRemote::WillLaunch (Module* module)
332{
333 return WillLaunchOrAttach ();
334}
335
336Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000337ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000338{
339 return WillLaunchOrAttach ();
340}
341
342Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000343ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000344{
345 return WillLaunchOrAttach ();
346}
347
348Error
Greg Claytone71e2582011-02-04 01:58:07 +0000349ProcessGDBRemote::DoConnectRemote (const char *remote_url)
350{
351 Error error (WillLaunchOrAttach ());
352
353 if (error.Fail())
354 return error;
355
356 if (strncmp (remote_url, "connect://", strlen ("connect://")) == 0)
357 {
358 error = ConnectToDebugserver (remote_url);
359 }
360 else
361 {
362 error.SetErrorStringWithFormat ("unsupported remote url: %s", remote_url);
363 }
364
365 if (error.Fail())
366 return error;
367 StartAsyncThread ();
368
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000369 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000370 if (pid == LLDB_INVALID_PROCESS_ID)
371 {
372 // We don't have a valid process ID, so note that we are connected
373 // and could now request to launch or attach, or get remote process
374 // listings...
375 SetPrivateState (eStateConnected);
376 }
377 else
378 {
379 // We have a valid process
380 SetID (pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000381 UpdateThreadListIfNeeded ();
Greg Claytone71e2582011-02-04 01:58:07 +0000382 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000383 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000384 {
385 const StateType state = SetThreadStopInfo (response);
386 if (state == eStateStopped)
387 {
388 SetPrivateState (state);
389 }
390 else
391 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
392 }
393 else
394 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
395 }
396 return error;
397}
398
399Error
Chris Lattner24943d22010-06-08 16:52:24 +0000400ProcessGDBRemote::WillLaunchOrAttach ()
401{
402 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000403 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000404 return error;
405}
406
407//----------------------------------------------------------------------
408// Process Control
409//----------------------------------------------------------------------
410Error
411ProcessGDBRemote::DoLaunch
412(
413 Module* module,
414 char const *argv[],
415 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000416 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000417 const char *stdin_path,
418 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000419 const char *stderr_path,
420 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000421)
422{
Greg Clayton4b407112010-09-30 21:49:03 +0000423 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000424 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
425 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
426 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000427
428 ObjectFile * object_file = module->GetObjectFile();
429 if (object_file)
430 {
431 ArchSpec inferior_arch(module->GetArchitecture());
432 char host_port[128];
433 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000434 char connect_url[128];
435 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000436
Greg Claytona2f74232011-02-24 22:24:29 +0000437 // Make sure we aren't already connected?
438 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000439 {
440 error = StartDebugserverProcess (host_port,
441 NULL,
442 NULL,
Chris Lattner24943d22010-06-08 16:52:24 +0000443 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000444 NULL,
445 false,
Chris Lattner24943d22010-06-08 16:52:24 +0000446 inferior_arch);
447 if (error.Fail())
448 return error;
449
Greg Claytone71e2582011-02-04 01:58:07 +0000450 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000451 }
452
453 if (error.Success())
454 {
455 lldb_utility::PseudoTerminal pty;
456 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000457
458 // If the debugserver is local and we aren't disabling STDIO, lets use
459 // a pseudo terminal to instead of relying on the 'O' packets for stdio
460 // since 'O' packets can really slow down debugging if the inferior
461 // does a lot of output.
462 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000463 {
464 const char *slave_name = NULL;
465 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000466 {
Greg Claytona2f74232011-02-24 22:24:29 +0000467 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
468 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000469 }
Greg Claytona2f74232011-02-24 22:24:29 +0000470 if (stdin_path == NULL)
471 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000472
Greg Claytona2f74232011-02-24 22:24:29 +0000473 if (stdout_path == NULL)
474 stdout_path = slave_name;
475
476 if (stderr_path == NULL)
477 stderr_path = slave_name;
478 }
479
Greg Claytonafb81862011-03-02 21:34:46 +0000480 // Set STDIN to /dev/null if we want STDIO disabled or if either
481 // STDOUT or STDERR have been set to something and STDIN hasn't
482 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000483 stdin_path = "/dev/null";
484
Greg Claytonafb81862011-03-02 21:34:46 +0000485 // Set STDOUT to /dev/null if we want STDIO disabled or if either
486 // STDIN or STDERR have been set to something and STDOUT hasn't
487 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000488 stdout_path = "/dev/null";
489
Greg Claytonafb81862011-03-02 21:34:46 +0000490 // Set STDERR to /dev/null if we want STDIO disabled or if either
491 // STDIN or STDOUT have been set to something and STDERR hasn't
492 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000493 stderr_path = "/dev/null";
494
495 if (stdin_path)
496 m_gdb_comm.SetSTDIN (stdin_path);
497 if (stdout_path)
498 m_gdb_comm.SetSTDOUT (stdout_path);
499 if (stderr_path)
500 m_gdb_comm.SetSTDERR (stderr_path);
501
502 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
503
504
505 if (working_dir && working_dir[0])
506 {
507 m_gdb_comm.SetWorkingDir (working_dir);
508 }
509
510 // Send the environment and the program + arguments after we connect
511 if (envp)
512 {
513 const char *env_entry;
514 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000515 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000516 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000517 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000518 }
Greg Claytona2f74232011-02-24 22:24:29 +0000519 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000520
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000521 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
522 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
523 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000524 if (arg_packet_err == 0)
525 {
526 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000527 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000528 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000529 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000530 }
531 else
532 {
Greg Claytona2f74232011-02-24 22:24:29 +0000533 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000534 }
Greg Claytona2f74232011-02-24 22:24:29 +0000535 }
536 else
537 {
538 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
539 }
Chris Lattner24943d22010-06-08 16:52:24 +0000540
Greg Claytona2f74232011-02-24 22:24:29 +0000541 if (GetID() == LLDB_INVALID_PROCESS_ID)
542 {
543 KillDebugserverProcess ();
544 return error;
545 }
546
547 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000548 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000549 {
550 SetPrivateState (SetThreadStopInfo (response));
551
552 if (!disable_stdio)
553 {
554 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
555 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
556 }
Chris Lattner24943d22010-06-08 16:52:24 +0000557 }
558 }
Chris Lattner24943d22010-06-08 16:52:24 +0000559 }
560 else
561 {
562 // Set our user ID to an invalid process ID.
563 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000564 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
565 module->GetFileSpec().GetFilename().AsCString(),
566 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000567 }
Chris Lattner24943d22010-06-08 16:52:24 +0000568 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000569
Chris Lattner24943d22010-06-08 16:52:24 +0000570}
571
572
573Error
Greg Claytone71e2582011-02-04 01:58:07 +0000574ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000575{
576 Error error;
577 // Sleep and wait a bit for debugserver to start to listen...
578 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
579 if (conn_ap.get())
580 {
Chris Lattner24943d22010-06-08 16:52:24 +0000581 const uint32_t max_retry_count = 50;
582 uint32_t retry_count = 0;
583 while (!m_gdb_comm.IsConnected())
584 {
Greg Claytone71e2582011-02-04 01:58:07 +0000585 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000586 {
587 m_gdb_comm.SetConnection (conn_ap.release());
588 break;
589 }
590 retry_count++;
591
592 if (retry_count >= max_retry_count)
593 break;
594
595 usleep (100000);
596 }
597 }
598
599 if (!m_gdb_comm.IsConnected())
600 {
601 if (error.Success())
602 error.SetErrorString("not connected to remote gdb server");
603 return error;
604 }
605
Greg Clayton24bc5d92011-03-30 18:16:51 +0000606 // We always seem to be able to open a connection to a local port
607 // so we need to make sure we can then send data to it. If we can't
608 // then we aren't actually connected to anything, so try and do the
609 // handshake with the remote GDB server and make sure that goes
610 // alright.
611 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000612 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000613 m_gdb_comm.Disconnect();
614 if (error.Success())
615 error.SetErrorString("not connected to remote gdb server");
616 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000617 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000618 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
619 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
620 this,
621 m_debugserver_pid,
622 false);
623 m_gdb_comm.ResetDiscoverableSettings();
624 m_gdb_comm.QueryNoAckModeSupported ();
625 m_gdb_comm.GetThreadSuffixSupported ();
626 m_gdb_comm.GetHostInfo ();
627 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000628 return error;
629}
630
631void
632ProcessGDBRemote::DidLaunchOrAttach ()
633{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000634 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
635 if (log)
636 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000637 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000638 {
639 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
640
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000641 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000642
Chris Lattner24943d22010-06-08 16:52:24 +0000643 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000644
Greg Claytoncb8977d2011-03-23 00:09:55 +0000645 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
646 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000647 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000648 ArchSpec &target_arch = GetTarget().GetArchitecture();
649
650 if (target_arch.IsValid())
651 {
652 // If the remote host is ARM and we have apple as the vendor, then
653 // ARM executables and shared libraries can have mixed ARM architectures.
654 // You can have an armv6 executable, and if the host is armv7, then the
655 // system will load the best possible architecture for all shared libraries
656 // it has, so we really need to take the remote host architecture as our
657 // defacto architecture in this case.
658
659 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
660 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
661 {
662 target_arch = gdb_remote_arch;
663 }
664 else
665 {
666 // Fill in what is missing in the triple
667 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
668 llvm::Triple &target_triple = target_arch.GetTriple();
669 if (target_triple.getVendor() == llvm::Triple::UnknownVendor)
670 target_triple.setVendor (remote_triple.getVendor());
671
672 if (target_triple.getOS() == llvm::Triple::UnknownOS)
673 target_triple.setOS (remote_triple.getOS());
674
675 if (target_triple.getEnvironment() == llvm::Triple::UnknownEnvironment)
676 target_triple.setEnvironment (remote_triple.getEnvironment());
677 }
678 }
679 else
680 {
681 // The target doesn't have a valid architecture yet, set it from
682 // the architecture we got from the remote GDB server
683 target_arch = gdb_remote_arch;
684 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000685 }
Chris Lattner24943d22010-06-08 16:52:24 +0000686 }
687}
688
689void
690ProcessGDBRemote::DidLaunch ()
691{
692 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000693}
694
695Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000696ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000697{
698 Error error;
699 // Clear out and clean up from any current state
700 Clear();
Greg Claytona2f74232011-02-24 22:24:29 +0000701 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000702
Chris Lattner24943d22010-06-08 16:52:24 +0000703 if (attach_pid != LLDB_INVALID_PROCESS_ID)
704 {
Greg Claytona2f74232011-02-24 22:24:29 +0000705 // Make sure we aren't already connected?
706 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000707 {
Greg Claytona2f74232011-02-24 22:24:29 +0000708 char host_port[128];
709 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
710 char connect_url[128];
711 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000712
Greg Claytona2f74232011-02-24 22:24:29 +0000713 error = StartDebugserverProcess (host_port, // debugserver_url
714 NULL, // inferior_argv
715 NULL, // inferior_envp
716 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
717 NULL, // Don't send any attach by process name option to debugserver
718 false, // Don't send any attach wait_for_launch flag as an option to debugserver
719 arch_spec);
720
721 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000722 {
Greg Claytona2f74232011-02-24 22:24:29 +0000723 const char *error_string = error.AsCString();
724 if (error_string == NULL)
725 error_string = "unable to launch " DEBUGSERVER_BASENAME;
726
727 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000728 }
Greg Claytona2f74232011-02-24 22:24:29 +0000729 else
730 {
731 error = ConnectToDebugserver (connect_url);
732 }
733 }
734
735 if (error.Success())
736 {
737 char packet[64];
738 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
739
740 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000741 }
742 }
Chris Lattner24943d22010-06-08 16:52:24 +0000743 return error;
744}
745
746size_t
747ProcessGDBRemote::AttachInputReaderCallback
748(
749 void *baton,
750 InputReader *reader,
751 lldb::InputReaderAction notification,
752 const char *bytes,
753 size_t bytes_len
754)
755{
756 if (notification == eInputReaderGotToken)
757 {
758 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
759 if (gdb_process->m_waiting_for_attach)
760 gdb_process->m_waiting_for_attach = false;
761 reader->SetIsDone(true);
762 return 1;
763 }
764 return 0;
765}
766
767Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000768ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000769{
770 Error error;
771 // Clear out and clean up from any current state
772 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000773
Chris Lattner24943d22010-06-08 16:52:24 +0000774 if (process_name && process_name[0])
775 {
Greg Claytona2f74232011-02-24 22:24:29 +0000776 // Make sure we aren't already connected?
777 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000778 {
Chris Lattner24943d22010-06-08 16:52:24 +0000779
Greg Claytona2f74232011-02-24 22:24:29 +0000780 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
781
782 char host_port[128];
783 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
784 char connect_url[128];
785 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
786
787 error = StartDebugserverProcess (host_port, // debugserver_url
788 NULL, // inferior_argv
789 NULL, // inferior_envp
790 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
791 NULL, // Don't send any attach by process name option to debugserver
792 false, // Don't send any attach wait_for_launch flag as an option to debugserver
793 arch_spec);
794 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000795 {
Greg Claytona2f74232011-02-24 22:24:29 +0000796 const char *error_string = error.AsCString();
797 if (error_string == NULL)
798 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000799
Greg Claytona2f74232011-02-24 22:24:29 +0000800 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000801 }
Greg Claytona2f74232011-02-24 22:24:29 +0000802 else
803 {
804 error = ConnectToDebugserver (connect_url);
805 }
806 }
807
808 if (error.Success())
809 {
810 StreamString packet;
811
812 if (wait_for_launch)
813 packet.PutCString("vAttachWait");
814 else
815 packet.PutCString("vAttachName");
816 packet.PutChar(';');
817 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
818
819 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
820
Chris Lattner24943d22010-06-08 16:52:24 +0000821 }
822 }
Chris Lattner24943d22010-06-08 16:52:24 +0000823 return error;
824}
825
Chris Lattner24943d22010-06-08 16:52:24 +0000826
827void
828ProcessGDBRemote::DidAttach ()
829{
Greg Claytone71e2582011-02-04 01:58:07 +0000830 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000831}
832
833Error
834ProcessGDBRemote::WillResume ()
835{
Greg Claytonc1f45872011-02-12 06:28:37 +0000836 m_continue_c_tids.clear();
837 m_continue_C_tids.clear();
838 m_continue_s_tids.clear();
839 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000840 return Error();
841}
842
843Error
844ProcessGDBRemote::DoResume ()
845{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000846 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000847 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
848 if (log)
849 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000850
851 Listener listener ("gdb-remote.resume-packet-sent");
852 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
853 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000854 StreamString continue_packet;
855 bool continue_packet_error = false;
856 if (m_gdb_comm.HasAnyVContSupport ())
857 {
858 continue_packet.PutCString ("vCont");
859
860 if (!m_continue_c_tids.empty())
861 {
862 if (m_gdb_comm.GetVContSupported ('c'))
863 {
864 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)
865 continue_packet.Printf(";c:%4.4x", *t_pos);
866 }
867 else
868 continue_packet_error = true;
869 }
870
871 if (!continue_packet_error && !m_continue_C_tids.empty())
872 {
873 if (m_gdb_comm.GetVContSupported ('C'))
874 {
875 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)
876 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
877 }
878 else
879 continue_packet_error = true;
880 }
Greg Claytonb749a262010-12-03 06:02:24 +0000881
Greg Claytonc1f45872011-02-12 06:28:37 +0000882 if (!continue_packet_error && !m_continue_s_tids.empty())
883 {
884 if (m_gdb_comm.GetVContSupported ('s'))
885 {
886 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)
887 continue_packet.Printf(";s:%4.4x", *t_pos);
888 }
889 else
890 continue_packet_error = true;
891 }
892
893 if (!continue_packet_error && !m_continue_S_tids.empty())
894 {
895 if (m_gdb_comm.GetVContSupported ('S'))
896 {
897 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)
898 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
899 }
900 else
901 continue_packet_error = true;
902 }
903
904 if (continue_packet_error)
905 continue_packet.GetString().clear();
906 }
907 else
908 continue_packet_error = true;
909
910 if (continue_packet_error)
911 {
912 continue_packet_error = false;
913 // Either no vCont support, or we tried to use part of the vCont
914 // packet that wasn't supported by the remote GDB server.
915 // We need to try and make a simple packet that can do our continue
916 const size_t num_threads = GetThreadList().GetSize();
917 const size_t num_continue_c_tids = m_continue_c_tids.size();
918 const size_t num_continue_C_tids = m_continue_C_tids.size();
919 const size_t num_continue_s_tids = m_continue_s_tids.size();
920 const size_t num_continue_S_tids = m_continue_S_tids.size();
921 if (num_continue_c_tids > 0)
922 {
923 if (num_continue_c_tids == num_threads)
924 {
925 // All threads are resuming...
926 SetCurrentGDBRemoteThreadForRun (-1);
927 continue_packet.PutChar ('c');
928 }
929 else if (num_continue_c_tids == 1 &&
930 num_continue_C_tids == 0 &&
931 num_continue_s_tids == 0 &&
932 num_continue_S_tids == 0 )
933 {
934 // Only one thread is continuing
935 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
936 continue_packet.PutChar ('c');
937 }
938 else
939 {
940 // We can't represent this continue packet....
941 continue_packet_error = true;
942 }
943 }
944
945 if (!continue_packet_error && num_continue_C_tids > 0)
946 {
947 if (num_continue_C_tids == num_threads)
948 {
949 const int continue_signo = m_continue_C_tids.front().second;
950 if (num_continue_C_tids > 1)
951 {
952 for (size_t i=1; i<num_threads; ++i)
953 {
954 if (m_continue_C_tids[i].second != continue_signo)
955 continue_packet_error = true;
956 }
957 }
958 if (!continue_packet_error)
959 {
960 // Add threads continuing with the same signo...
961 SetCurrentGDBRemoteThreadForRun (-1);
962 continue_packet.Printf("C%2.2x", continue_signo);
963 }
964 }
965 else if (num_continue_c_tids == 0 &&
966 num_continue_C_tids == 1 &&
967 num_continue_s_tids == 0 &&
968 num_continue_S_tids == 0 )
969 {
970 // Only one thread is continuing with signal
971 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
972 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
973 }
974 else
975 {
976 // We can't represent this continue packet....
977 continue_packet_error = true;
978 }
979 }
980
981 if (!continue_packet_error && num_continue_s_tids > 0)
982 {
983 if (num_continue_s_tids == num_threads)
984 {
985 // All threads are resuming...
986 SetCurrentGDBRemoteThreadForRun (-1);
987 continue_packet.PutChar ('s');
988 }
989 else if (num_continue_c_tids == 0 &&
990 num_continue_C_tids == 0 &&
991 num_continue_s_tids == 1 &&
992 num_continue_S_tids == 0 )
993 {
994 // Only one thread is stepping
995 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
996 continue_packet.PutChar ('s');
997 }
998 else
999 {
1000 // We can't represent this continue packet....
1001 continue_packet_error = true;
1002 }
1003 }
1004
1005 if (!continue_packet_error && num_continue_S_tids > 0)
1006 {
1007 if (num_continue_S_tids == num_threads)
1008 {
1009 const int step_signo = m_continue_S_tids.front().second;
1010 // Are all threads trying to step with the same signal?
1011 if (num_continue_S_tids > 1)
1012 {
1013 for (size_t i=1; i<num_threads; ++i)
1014 {
1015 if (m_continue_S_tids[i].second != step_signo)
1016 continue_packet_error = true;
1017 }
1018 }
1019 if (!continue_packet_error)
1020 {
1021 // Add threads stepping with the same signo...
1022 SetCurrentGDBRemoteThreadForRun (-1);
1023 continue_packet.Printf("S%2.2x", step_signo);
1024 }
1025 }
1026 else if (num_continue_c_tids == 0 &&
1027 num_continue_C_tids == 0 &&
1028 num_continue_s_tids == 0 &&
1029 num_continue_S_tids == 1 )
1030 {
1031 // Only one thread is stepping with signal
1032 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1033 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1034 }
1035 else
1036 {
1037 // We can't represent this continue packet....
1038 continue_packet_error = true;
1039 }
1040 }
1041 }
1042
1043 if (continue_packet_error)
1044 {
1045 error.SetErrorString ("can't make continue packet for this resume");
1046 }
1047 else
1048 {
1049 EventSP event_sp;
1050 TimeValue timeout;
1051 timeout = TimeValue::Now();
1052 timeout.OffsetWithSeconds (5);
1053 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1054
1055 if (listener.WaitForEvent (&timeout, event_sp) == false)
1056 error.SetErrorString("Resume timed out.");
1057 }
Greg Claytonb749a262010-12-03 06:02:24 +00001058 }
1059
Jim Ingham3ae449a2010-11-17 02:32:00 +00001060 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001061}
1062
Chris Lattner24943d22010-06-08 16:52:24 +00001063uint32_t
1064ProcessGDBRemote::UpdateThreadListIfNeeded ()
1065{
1066 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001067 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001068 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001069 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1070
Greg Clayton5205f0b2010-09-03 17:10:42 +00001071 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001072 const uint32_t stop_id = GetStopID();
1073 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1074 {
1075 // Update the thread list's stop id immediately so we don't recurse into this function.
1076 ThreadList curr_thread_list (this);
1077 curr_thread_list.SetStopID(stop_id);
1078
1079 Error err;
1080 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001081 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, false);
Greg Clayton61d043b2011-03-22 04:00:09 +00001082 response.IsNormalResponse();
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001083 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001084 {
1085 char ch = response.GetChar();
1086 if (ch == 'l')
1087 break;
1088 if (ch == 'm')
1089 {
1090 do
1091 {
1092 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1093
1094 if (tid != LLDB_INVALID_THREAD_ID)
1095 {
1096 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001097 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001098 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1099 curr_thread_list.AddThread(thread_sp);
1100 }
1101
1102 ch = response.GetChar();
1103 } while (ch == ',');
1104 }
1105 }
1106
1107 m_thread_list = curr_thread_list;
1108
1109 SetThreadStopInfo (m_last_stop_packet);
1110 }
1111 return GetThreadList().GetSize(false);
1112}
1113
1114
1115StateType
1116ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1117{
1118 const char stop_type = stop_packet.GetChar();
1119 switch (stop_type)
1120 {
1121 case 'T':
1122 case 'S':
1123 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001124 if (GetStopID() == 0)
1125 {
1126 // Our first stop, make sure we have a process ID, and also make
1127 // sure we know about our registers
1128 if (GetID() == LLDB_INVALID_PROCESS_ID)
1129 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001130 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001131 if (pid != LLDB_INVALID_PROCESS_ID)
1132 SetID (pid);
1133 }
1134 BuildDynamicRegisterInfo (true);
1135 }
Chris Lattner24943d22010-06-08 16:52:24 +00001136 // Stop with signal and thread info
1137 const uint8_t signo = stop_packet.GetHexU8();
1138 std::string name;
1139 std::string value;
1140 std::string thread_name;
1141 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001142 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001143 uint32_t tid = LLDB_INVALID_THREAD_ID;
1144 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1145 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001146 ThreadSP thread_sp;
1147
Chris Lattner24943d22010-06-08 16:52:24 +00001148 while (stop_packet.GetNameColonValue(name, value))
1149 {
1150 if (name.compare("metype") == 0)
1151 {
1152 // exception type in big endian hex
1153 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1154 }
1155 else if (name.compare("mecount") == 0)
1156 {
1157 // exception count in big endian hex
1158 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1159 }
1160 else if (name.compare("medata") == 0)
1161 {
1162 // exception data in big endian hex
1163 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1164 }
1165 else if (name.compare("thread") == 0)
1166 {
1167 // thread in big endian hex
1168 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001169 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001170 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001171 if (!thread_sp)
1172 {
1173 // Create the thread if we need to
1174 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1175 m_thread_list.AddThread(thread_sp);
1176 }
Chris Lattner24943d22010-06-08 16:52:24 +00001177 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001178 else if (name.compare("hexname") == 0)
1179 {
1180 StringExtractor name_extractor;
1181 // Swap "value" over into "name_extractor"
1182 name_extractor.GetStringRef().swap(value);
1183 // Now convert the HEX bytes into a string value
1184 name_extractor.GetHexByteString (value);
1185 thread_name.swap (value);
1186 }
Chris Lattner24943d22010-06-08 16:52:24 +00001187 else if (name.compare("name") == 0)
1188 {
1189 thread_name.swap (value);
1190 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001191 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001192 {
1193 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1194 }
Greg Claytona875b642011-01-09 21:07:35 +00001195 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1196 {
1197 // We have a register number that contains an expedited
1198 // register value. Lets supply this register to our thread
1199 // so it won't have to go and read it.
1200 if (thread_sp)
1201 {
1202 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1203
1204 if (reg != UINT32_MAX)
1205 {
1206 StringExtractor reg_value_extractor;
1207 // Swap "value" over into "reg_value_extractor"
1208 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001209 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1210 {
1211 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1212 name.c_str(),
1213 reg,
1214 reg,
1215 reg_value_extractor.GetStringRef().c_str(),
1216 stop_packet.GetStringRef().c_str());
1217 }
Greg Claytona875b642011-01-09 21:07:35 +00001218 }
1219 }
1220 }
Chris Lattner24943d22010-06-08 16:52:24 +00001221 }
Chris Lattner24943d22010-06-08 16:52:24 +00001222
1223 if (thread_sp)
1224 {
1225 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1226
1227 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001228 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001229 if (exc_type != 0)
1230 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001231 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001232
1233 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1234 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001235 exc_data_size,
1236 exc_data_size >= 1 ? exc_data[0] : 0,
1237 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001238 }
1239 else if (signo)
1240 {
Greg Clayton643ee732010-08-04 01:40:35 +00001241 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001242 }
1243 else
1244 {
Greg Clayton643ee732010-08-04 01:40:35 +00001245 StopInfoSP invalid_stop_info_sp;
1246 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001247 }
1248 }
1249 return eStateStopped;
1250 }
1251 break;
1252
1253 case 'W':
1254 // process exited
1255 return eStateExited;
1256
1257 default:
1258 break;
1259 }
1260 return eStateInvalid;
1261}
1262
1263void
1264ProcessGDBRemote::RefreshStateAfterStop ()
1265{
Jim Ingham7508e732010-08-09 23:31:02 +00001266 // FIXME - add a variable to tell that we're in the middle of attaching if we
1267 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001268 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001269// if (!GetTarget().GetArchitecture().IsValid())
1270// {
1271// Module *exe_module = GetTarget().GetExecutableModule().get();
1272// if (exe_module)
1273// m_arch_spec = exe_module->GetArchitecture();
1274// }
1275
Chris Lattner24943d22010-06-08 16:52:24 +00001276 // Let all threads recover from stopping and do any clean up based
1277 // on the previous thread state (if any).
1278 m_thread_list.RefreshStateAfterStop();
1279
1280 // Discover new threads:
1281 UpdateThreadListIfNeeded ();
1282}
1283
1284Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001285ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001286{
1287 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001288
Greg Claytona4881d02011-01-22 07:12:45 +00001289 bool timed_out = false;
1290 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001291
1292 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001293 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001294 // We are being asked to halt during an attach. We need to just close
1295 // our file handle and debugserver will go away, and we can be done...
1296 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001297 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001298 else
1299 {
1300 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1301 {
1302 if (timed_out)
1303 error.SetErrorString("timed out sending interrupt packet");
1304 else
1305 error.SetErrorString("unknown error sending interrupt packet");
1306 }
1307 }
Chris Lattner24943d22010-06-08 16:52:24 +00001308 return error;
1309}
1310
1311Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001312ProcessGDBRemote::InterruptIfRunning
1313(
1314 bool discard_thread_plans,
1315 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001316 EventSP &stop_event_sp
1317)
Chris Lattner24943d22010-06-08 16:52:24 +00001318{
1319 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001320
Greg Clayton2860ba92011-01-23 19:58:49 +00001321 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1322
Greg Clayton68ca8232011-01-25 02:58:48 +00001323 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001324 const bool is_running = m_gdb_comm.IsRunning();
1325 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001326 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001327 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001328 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001329 is_running);
1330
Greg Clayton2860ba92011-01-23 19:58:49 +00001331 if (discard_thread_plans)
1332 {
1333 if (log)
1334 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1335 m_thread_list.DiscardThreadPlans();
1336 }
1337 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001338 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001339 if (catch_stop_event)
1340 {
1341 if (log)
1342 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1343 PausePrivateStateThread();
1344 paused_private_state_thread = true;
1345 }
1346
Greg Clayton4fb400f2010-09-27 21:07:38 +00001347 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001348 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001349 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001350
Greg Clayton72e1c782011-01-22 23:43:18 +00001351 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001352 {
1353 if (timed_out)
1354 error.SetErrorString("timed out sending interrupt packet");
1355 else
1356 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001357 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001358 ResumePrivateStateThread();
1359 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001360 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001361
Greg Clayton72e1c782011-01-22 23:43:18 +00001362 if (catch_stop_event)
1363 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001364 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001365 TimeValue timeout_time;
1366 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001367 timeout_time.OffsetWithSeconds(5);
1368 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001369
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001370 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001371 if (log)
1372 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001373
Greg Clayton2860ba92011-01-23 19:58:49 +00001374 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001375 error.SetErrorString("unable to verify target stopped");
1376 }
1377
Greg Clayton68ca8232011-01-25 02:58:48 +00001378 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001379 {
1380 if (log)
1381 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001382 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001383 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001384 }
Chris Lattner24943d22010-06-08 16:52:24 +00001385 return error;
1386}
1387
Greg Clayton4fb400f2010-09-27 21:07:38 +00001388Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001389ProcessGDBRemote::WillDetach ()
1390{
Greg Clayton2860ba92011-01-23 19:58:49 +00001391 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1392 if (log)
1393 log->Printf ("ProcessGDBRemote::WillDetach()");
1394
Greg Clayton72e1c782011-01-22 23:43:18 +00001395 bool discard_thread_plans = true;
1396 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001397 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001398 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001399}
1400
1401Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001402ProcessGDBRemote::DoDetach()
1403{
1404 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001405 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001406 if (log)
1407 log->Printf ("ProcessGDBRemote::DoDetach()");
1408
1409 DisableAllBreakpointSites ();
1410
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001411 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001412
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001413 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1414 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001415 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001416 if (response_size)
1417 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1418 else
1419 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001420 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001421 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001422 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001423
Greg Clayton4fb400f2010-09-27 21:07:38 +00001424 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001425 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001426
1427 SetPrivateState (eStateDetached);
1428 ResumePrivateStateThread();
1429
1430 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001431 return error;
1432}
Chris Lattner24943d22010-06-08 16:52:24 +00001433
1434Error
1435ProcessGDBRemote::DoDestroy ()
1436{
1437 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001438 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001439 if (log)
1440 log->Printf ("ProcessGDBRemote::DoDestroy()");
1441
1442 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001443 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001444 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001445 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001446 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001447 // We are being asked to halt during an attach. We need to just close
1448 // our file handle and debugserver will go away, and we can be done...
1449 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001450 }
1451 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001452 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001453
1454 StringExtractorGDBRemote response;
1455 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001456 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001457 {
1458 char packet_cmd = response.GetChar(0);
1459
1460 if (packet_cmd == 'W' || packet_cmd == 'X')
1461 {
1462 m_last_stop_packet = response;
1463 SetExitStatus(response.GetHexU8(), NULL);
1464 }
1465 }
1466 else
1467 {
1468 SetExitStatus(SIGABRT, NULL);
1469 //error.SetErrorString("kill packet failed");
1470 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001471 }
1472 }
Chris Lattner24943d22010-06-08 16:52:24 +00001473 StopAsyncThread ();
1474 m_gdb_comm.StopReadThread();
1475 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001476 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001477 return error;
1478}
1479
Chris Lattner24943d22010-06-08 16:52:24 +00001480//------------------------------------------------------------------
1481// Process Queries
1482//------------------------------------------------------------------
1483
1484bool
1485ProcessGDBRemote::IsAlive ()
1486{
Greg Clayton58e844b2010-12-08 05:08:21 +00001487 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001488}
1489
1490addr_t
1491ProcessGDBRemote::GetImageInfoAddress()
1492{
1493 if (!m_gdb_comm.IsRunning())
1494 {
1495 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001496 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001497 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001498 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001499 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1500 }
1501 }
1502 return LLDB_INVALID_ADDRESS;
1503}
1504
Chris Lattner24943d22010-06-08 16:52:24 +00001505//------------------------------------------------------------------
1506// Process Memory
1507//------------------------------------------------------------------
1508size_t
1509ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1510{
1511 if (size > m_max_memory_size)
1512 {
1513 // Keep memory read sizes down to a sane limit. This function will be
1514 // called multiple times in order to complete the task by
1515 // lldb_private::Process so it is ok to do this.
1516 size = m_max_memory_size;
1517 }
1518
1519 char packet[64];
1520 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1521 assert (packet_len + 1 < sizeof(packet));
1522 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001523 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001524 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001525 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001526 {
1527 error.Clear();
1528 return response.GetHexBytes(buf, size, '\xdd');
1529 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001530 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001531 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001532 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001533 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1534 else
1535 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1536 }
1537 else
1538 {
1539 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1540 }
1541 return 0;
1542}
1543
1544size_t
1545ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1546{
1547 StreamString packet;
1548 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001549 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001550 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001551 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001552 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001553 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001554 {
1555 error.Clear();
1556 return size;
1557 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001558 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001559 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001560 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001561 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1562 else
1563 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1564 }
1565 else
1566 {
1567 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1568 }
1569 return 0;
1570}
1571
1572lldb::addr_t
1573ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1574{
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001575 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
Chris Lattner24943d22010-06-08 16:52:24 +00001576 if (allocated_addr == LLDB_INVALID_ADDRESS)
1577 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1578 else
1579 error.Clear();
1580 return allocated_addr;
1581}
1582
1583Error
1584ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1585{
1586 Error error;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001587 if (!m_gdb_comm.DeallocateMemory (addr))
Chris Lattner24943d22010-06-08 16:52:24 +00001588 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1589 return error;
1590}
1591
1592
1593//------------------------------------------------------------------
1594// Process STDIO
1595//------------------------------------------------------------------
1596
1597size_t
1598ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1599{
1600 Mutex::Locker locker(m_stdio_mutex);
1601 size_t bytes_available = m_stdout_data.size();
1602 if (bytes_available > 0)
1603 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001604 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1605 if (log)
1606 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001607 if (bytes_available > buf_size)
1608 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001609 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001610 m_stdout_data.erase(0, buf_size);
1611 bytes_available = buf_size;
1612 }
1613 else
1614 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001615 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001616 m_stdout_data.clear();
1617
1618 //ResetEventBits(eBroadcastBitSTDOUT);
1619 }
1620 }
1621 return bytes_available;
1622}
1623
1624size_t
1625ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1626{
1627 // Can we get STDERR through the remote protocol?
1628 return 0;
1629}
1630
1631size_t
1632ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1633{
1634 if (m_stdio_communication.IsConnected())
1635 {
1636 ConnectionStatus status;
1637 m_stdio_communication.Write(src, src_len, status, NULL);
1638 }
1639 return 0;
1640}
1641
1642Error
1643ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1644{
1645 Error error;
1646 assert (bp_site != NULL);
1647
Greg Claytone005f2c2010-11-06 01:53:30 +00001648 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001649 user_id_t site_id = bp_site->GetID();
1650 const addr_t addr = bp_site->GetLoadAddress();
1651 if (log)
1652 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1653
1654 if (bp_site->IsEnabled())
1655 {
1656 if (log)
1657 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1658 return error;
1659 }
1660 else
1661 {
1662 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1663
1664 if (bp_site->HardwarePreferred())
1665 {
1666 // Try and set hardware breakpoint, and if that fails, fall through
1667 // and set a software breakpoint?
1668 }
1669
1670 if (m_z0_supported)
1671 {
1672 char packet[64];
1673 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1674 assert (packet_len + 1 < sizeof(packet));
1675 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001676 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001677 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001678 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001679 {
1680 // Disable z packet support and try again
1681 m_z0_supported = 0;
1682 return EnableBreakpoint (bp_site);
1683 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001684 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001685 {
1686 bp_site->SetEnabled(true);
1687 bp_site->SetType (BreakpointSite::eExternal);
1688 return error;
1689 }
1690 else
1691 {
1692 uint8_t error_byte = response.GetError();
1693 if (error_byte)
1694 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1695 }
1696 }
1697 }
1698 else
1699 {
1700 return EnableSoftwareBreakpoint (bp_site);
1701 }
1702 }
1703
1704 if (log)
1705 {
1706 const char *err_string = error.AsCString();
1707 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1708 bp_site->GetLoadAddress(),
1709 err_string ? err_string : "NULL");
1710 }
1711 // We shouldn't reach here on a successful breakpoint enable...
1712 if (error.Success())
1713 error.SetErrorToGenericError();
1714 return error;
1715}
1716
1717Error
1718ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1719{
1720 Error error;
1721 assert (bp_site != NULL);
1722 addr_t addr = bp_site->GetLoadAddress();
1723 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001724 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001725 if (log)
1726 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1727
1728 if (bp_site->IsEnabled())
1729 {
1730 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1731
1732 if (bp_site->IsHardware())
1733 {
1734 // TODO: disable hardware breakpoint...
1735 }
1736 else
1737 {
1738 if (m_z0_supported)
1739 {
1740 char packet[64];
1741 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1742 assert (packet_len + 1 < sizeof(packet));
1743 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001744 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001745 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001746 if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001747 {
1748 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1749 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001750 else if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001751 {
1752 if (log)
1753 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1754 bp_site->SetEnabled(false);
1755 return error;
1756 }
1757 else
1758 {
1759 uint8_t error_byte = response.GetError();
1760 if (error_byte)
1761 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1762 }
1763 }
1764 }
1765 else
1766 {
1767 return DisableSoftwareBreakpoint (bp_site);
1768 }
1769 }
1770 }
1771 else
1772 {
1773 if (log)
1774 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1775 return error;
1776 }
1777
1778 if (error.Success())
1779 error.SetErrorToGenericError();
1780 return error;
1781}
1782
1783Error
1784ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1785{
1786 Error error;
1787 if (wp)
1788 {
1789 user_id_t watchID = wp->GetID();
1790 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001791 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001792 if (log)
1793 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1794 if (wp->IsEnabled())
1795 {
1796 if (log)
1797 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1798 return error;
1799 }
1800 else
1801 {
1802 // Pass down an appropriate z/Z packet...
1803 error.SetErrorString("watchpoints not supported");
1804 }
1805 }
1806 else
1807 {
1808 error.SetErrorString("Watchpoint location argument was NULL.");
1809 }
1810 if (error.Success())
1811 error.SetErrorToGenericError();
1812 return error;
1813}
1814
1815Error
1816ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1817{
1818 Error error;
1819 if (wp)
1820 {
1821 user_id_t watchID = wp->GetID();
1822
Greg Claytone005f2c2010-11-06 01:53:30 +00001823 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001824
1825 addr_t addr = wp->GetLoadAddress();
1826 if (log)
1827 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1828
1829 if (wp->IsHardware())
1830 {
1831 // Pass down an appropriate z/Z packet...
1832 error.SetErrorString("watchpoints not supported");
1833 }
1834 // TODO: clear software watchpoints if we implement them
1835 }
1836 else
1837 {
1838 error.SetErrorString("Watchpoint location argument was NULL.");
1839 }
1840 if (error.Success())
1841 error.SetErrorToGenericError();
1842 return error;
1843}
1844
1845void
1846ProcessGDBRemote::Clear()
1847{
1848 m_flags = 0;
1849 m_thread_list.Clear();
1850 {
1851 Mutex::Locker locker(m_stdio_mutex);
1852 m_stdout_data.clear();
1853 }
Chris Lattner24943d22010-06-08 16:52:24 +00001854}
1855
1856Error
1857ProcessGDBRemote::DoSignal (int signo)
1858{
1859 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001860 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001861 if (log)
1862 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1863
1864 if (!m_gdb_comm.SendAsyncSignal (signo))
1865 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1866 return error;
1867}
1868
Chris Lattner24943d22010-06-08 16:52:24 +00001869Error
1870ProcessGDBRemote::StartDebugserverProcess
1871(
1872 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1873 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1874 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Clayton23cf0c72010-11-08 04:29:11 +00001875 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 +00001876 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1877 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Claytona2f74232011-02-24 22:24:29 +00001878 const ArchSpec& inferior_arch // The arch of the inferior that we will launch
Chris Lattner24943d22010-06-08 16:52:24 +00001879)
1880{
1881 Error error;
1882 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1883 {
1884 // If we locate debugserver, keep that located version around
1885 static FileSpec g_debugserver_file_spec;
1886
1887 FileSpec debugserver_file_spec;
1888 char debugserver_path[PATH_MAX];
1889
1890 // Always check to see if we have an environment override for the path
1891 // to the debugserver to use and use it if we do.
1892 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1893 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001894 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001895 else
1896 debugserver_file_spec = g_debugserver_file_spec;
1897 bool debugserver_exists = debugserver_file_spec.Exists();
1898 if (!debugserver_exists)
1899 {
1900 // The debugserver binary is in the LLDB.framework/Resources
1901 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001902 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001903 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001904 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001905 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001906 if (debugserver_exists)
1907 {
1908 g_debugserver_file_spec = debugserver_file_spec;
1909 }
1910 else
1911 {
1912 g_debugserver_file_spec.Clear();
1913 debugserver_file_spec.Clear();
1914 }
Chris Lattner24943d22010-06-08 16:52:24 +00001915 }
1916 }
1917
1918 if (debugserver_exists)
1919 {
1920 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1921
1922 m_stdio_communication.Clear();
1923 posix_spawnattr_t attr;
1924
Greg Claytone005f2c2010-11-06 01:53:30 +00001925 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001926
1927 Error local_err; // Errors that don't affect the spawning.
1928 if (log)
Greg Clayton940b1032011-02-23 00:35:02 +00001929 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )",
1930 __FUNCTION__,
1931 debugserver_path,
1932 inferior_argv,
1933 inferior_envp,
1934 inferior_arch.GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +00001935 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1936 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001937 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001938 if (error.Fail())
Greg Clayton940b1032011-02-23 00:35:02 +00001939 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001940
Chris Lattner24943d22010-06-08 16:52:24 +00001941 Args debugserver_args;
1942 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001943
Chris Lattner24943d22010-06-08 16:52:24 +00001944 // Start args with "debugserver /file/path -r --"
1945 debugserver_args.AppendArgument(debugserver_path);
1946 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001947 // use native registers, not the GDB registers
1948 debugserver_args.AppendArgument("--native-regs");
1949 // make debugserver run in its own session so signals generated by
1950 // special terminal key sequences (^C) don't affect debugserver
1951 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001952
Chris Lattner24943d22010-06-08 16:52:24 +00001953 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1954 if (env_debugserver_log_file)
1955 {
1956 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1957 debugserver_args.AppendArgument(arg_cstr);
1958 }
1959
1960 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1961 if (env_debugserver_log_flags)
1962 {
1963 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1964 debugserver_args.AppendArgument(arg_cstr);
1965 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001966// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001967// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001968
1969 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00001970 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00001971 {
Greg Claytona2f74232011-02-24 22:24:29 +00001972 // Terminate the debugserver args so we can now append the inferior args
1973 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00001974
Greg Claytona2f74232011-02-24 22:24:29 +00001975 for (int i = 0; inferior_argv[i] != NULL; ++i)
1976 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00001977 }
1978 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1979 {
1980 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1981 debugserver_args.AppendArgument (arg_cstr);
1982 }
1983 else if (attach_name && attach_name[0])
1984 {
1985 if (wait_for_launch)
1986 debugserver_args.AppendArgument ("--waitfor");
1987 else
1988 debugserver_args.AppendArgument ("--attach");
1989 debugserver_args.AppendArgument (attach_name);
1990 }
1991
1992 Error file_actions_err;
1993 posix_spawn_file_actions_t file_actions;
1994#if DONT_CLOSE_DEBUGSERVER_STDIO
1995 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1996#else
1997 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1998 if (file_actions_err.Success())
1999 {
2000 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
2001 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
2002 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
2003 }
2004#endif
2005
2006 if (log)
2007 {
2008 StreamString strm;
2009 debugserver_args.Dump (&strm);
2010 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2011 }
2012
Greg Clayton72e1c782011-01-22 23:43:18 +00002013 error.SetError (::posix_spawnp (&m_debugserver_pid,
2014 debugserver_path,
2015 file_actions_err.Success() ? &file_actions : NULL,
2016 &attr,
2017 debugserver_args.GetArgumentVector(),
2018 (char * const*)inferior_envp),
2019 eErrorTypePOSIX);
2020
Greg Claytone9d0df42010-07-02 01:29:13 +00002021
2022 ::posix_spawnattr_destroy (&attr);
2023
Chris Lattner24943d22010-06-08 16:52:24 +00002024 if (file_actions_err.Success())
2025 ::posix_spawn_file_actions_destroy (&file_actions);
2026
2027 // We have seen some cases where posix_spawnp was returning a valid
2028 // looking pid even when an error was returned, so clear it out
2029 if (error.Fail())
2030 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2031
2032 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002033 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 +00002034
Chris Lattner24943d22010-06-08 16:52:24 +00002035 }
2036 else
2037 {
2038 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2039 }
2040
2041 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2042 StartAsyncThread ();
2043 }
2044 return error;
2045}
2046
2047bool
2048ProcessGDBRemote::MonitorDebugserverProcess
2049(
2050 void *callback_baton,
2051 lldb::pid_t debugserver_pid,
2052 int signo, // Zero for no signal
2053 int exit_status // Exit value of process if signal is zero
2054)
2055{
2056 // We pass in the ProcessGDBRemote inferior process it and name it
2057 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2058 // pointer value itself, thus we need the double cast...
2059
2060 // "debugserver_pid" argument passed in is the process ID for
2061 // debugserver that we are tracking...
2062
Greg Clayton75ccf502010-08-21 02:22:51 +00002063 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002064
2065 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2066 if (log)
2067 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2068
Greg Clayton75ccf502010-08-21 02:22:51 +00002069 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002070 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002071 // Sleep for a half a second to make sure our inferior process has
2072 // time to set its exit status before we set it incorrectly when
2073 // both the debugserver and the inferior process shut down.
2074 usleep (500000);
2075 // If our process hasn't yet exited, debugserver might have died.
2076 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002077 const StateType state = process->GetState();
2078
2079 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2080 state != eStateInvalid &&
2081 state != eStateUnloaded &&
2082 state != eStateExited &&
2083 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002084 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002085 char error_str[1024];
2086 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002087 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002088 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2089 if (signal_cstr)
2090 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002091 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002092 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002093 }
2094 else
2095 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002096 ::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 +00002097 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002098
2099 process->SetExitStatus (-1, error_str);
2100 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002101 // Debugserver has exited we need to let our ProcessGDBRemote
2102 // know that it no longer has a debugserver instance
2103 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2104 // We are returning true to this function below, so we can
2105 // forget about the monitor handle.
2106 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002107 }
2108 return true;
2109}
2110
2111void
2112ProcessGDBRemote::KillDebugserverProcess ()
2113{
2114 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2115 {
2116 ::kill (m_debugserver_pid, SIGINT);
2117 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2118 }
2119}
2120
2121void
2122ProcessGDBRemote::Initialize()
2123{
2124 static bool g_initialized = false;
2125
2126 if (g_initialized == false)
2127 {
2128 g_initialized = true;
2129 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2130 GetPluginDescriptionStatic(),
2131 CreateInstance);
2132
2133 Log::Callbacks log_callbacks = {
2134 ProcessGDBRemoteLog::DisableLog,
2135 ProcessGDBRemoteLog::EnableLog,
2136 ProcessGDBRemoteLog::ListLogCategories
2137 };
2138
2139 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2140 }
2141}
2142
2143bool
2144ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2145{
2146 if (m_curr_tid == tid)
2147 return true;
2148
2149 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002150 int packet_len;
2151 if (tid <= 0)
2152 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2153 else
2154 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002155 assert (packet_len + 1 < sizeof(packet));
2156 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002157 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002158 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002159 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002160 {
2161 m_curr_tid = tid;
2162 return true;
2163 }
2164 }
2165 return false;
2166}
2167
2168bool
2169ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2170{
2171 if (m_curr_tid_run == tid)
2172 return true;
2173
2174 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002175 int packet_len;
2176 if (tid <= 0)
2177 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2178 else
2179 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2180
Chris Lattner24943d22010-06-08 16:52:24 +00002181 assert (packet_len + 1 < sizeof(packet));
2182 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002183 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002184 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002185 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002186 {
2187 m_curr_tid_run = tid;
2188 return true;
2189 }
2190 }
2191 return false;
2192}
2193
2194void
2195ProcessGDBRemote::ResetGDBRemoteState ()
2196{
2197 // Reset and GDB remote state
2198 m_curr_tid = LLDB_INVALID_THREAD_ID;
2199 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2200 m_z0_supported = 1;
2201}
2202
2203
2204bool
2205ProcessGDBRemote::StartAsyncThread ()
2206{
2207 ResetGDBRemoteState ();
2208
Greg Claytone005f2c2010-11-06 01:53:30 +00002209 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002210
2211 if (log)
2212 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2213
2214 // Create a thread that watches our internal state and controls which
2215 // events make it to clients (into the DCProcess event queue).
2216 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002217 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002218}
2219
2220void
2221ProcessGDBRemote::StopAsyncThread ()
2222{
Greg Claytone005f2c2010-11-06 01:53:30 +00002223 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002224
2225 if (log)
2226 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2227
2228 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2229
2230 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002231 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002232 {
2233 Host::ThreadJoin (m_async_thread, NULL, NULL);
2234 }
2235}
2236
2237
2238void *
2239ProcessGDBRemote::AsyncThread (void *arg)
2240{
2241 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2242
Greg Claytone005f2c2010-11-06 01:53:30 +00002243 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002244 if (log)
2245 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2246
2247 Listener listener ("ProcessGDBRemote::AsyncThread");
2248 EventSP event_sp;
2249 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2250 eBroadcastBitAsyncThreadShouldExit;
2251
2252 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2253 {
Greg Claytona2f74232011-02-24 22:24:29 +00002254 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2255
Chris Lattner24943d22010-06-08 16:52:24 +00002256 bool done = false;
2257 while (!done)
2258 {
2259 if (log)
2260 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2261 if (listener.WaitForEvent (NULL, event_sp))
2262 {
2263 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002264 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002265 {
Greg Claytona2f74232011-02-24 22:24:29 +00002266 if (log)
2267 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 +00002268
Greg Claytona2f74232011-02-24 22:24:29 +00002269 switch (event_type)
2270 {
2271 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002272 {
Greg Claytona2f74232011-02-24 22:24:29 +00002273 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002274
Greg Claytona2f74232011-02-24 22:24:29 +00002275 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002276 {
Greg Claytona2f74232011-02-24 22:24:29 +00002277 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2278 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2279 if (log)
2280 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002281
Greg Claytona2f74232011-02-24 22:24:29 +00002282 if (::strstr (continue_cstr, "vAttach") == NULL)
2283 process->SetPrivateState(eStateRunning);
2284 StringExtractorGDBRemote response;
2285 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002286
Greg Claytona2f74232011-02-24 22:24:29 +00002287 switch (stop_state)
2288 {
2289 case eStateStopped:
2290 case eStateCrashed:
2291 case eStateSuspended:
2292 process->m_last_stop_packet = response;
2293 process->m_last_stop_packet.SetFilePos (0);
2294 process->SetPrivateState (stop_state);
2295 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002296
Greg Claytona2f74232011-02-24 22:24:29 +00002297 case eStateExited:
2298 process->m_last_stop_packet = response;
2299 process->m_last_stop_packet.SetFilePos (0);
2300 response.SetFilePos(1);
2301 process->SetExitStatus(response.GetHexU8(), NULL);
2302 done = true;
2303 break;
2304
2305 case eStateInvalid:
2306 process->SetExitStatus(-1, "lost connection");
2307 break;
2308
2309 default:
2310 process->SetPrivateState (stop_state);
2311 break;
2312 }
Chris Lattner24943d22010-06-08 16:52:24 +00002313 }
2314 }
Greg Claytona2f74232011-02-24 22:24:29 +00002315 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002316
Greg Claytona2f74232011-02-24 22:24:29 +00002317 case eBroadcastBitAsyncThreadShouldExit:
2318 if (log)
2319 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2320 done = true;
2321 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002322
Greg Claytona2f74232011-02-24 22:24:29 +00002323 default:
2324 if (log)
2325 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2326 done = true;
2327 break;
2328 }
2329 }
2330 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2331 {
2332 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2333 {
2334 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002335 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002336 }
Chris Lattner24943d22010-06-08 16:52:24 +00002337 }
2338 }
2339 else
2340 {
2341 if (log)
2342 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2343 done = true;
2344 }
2345 }
2346 }
2347
2348 if (log)
2349 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2350
2351 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2352 return NULL;
2353}
2354
Chris Lattner24943d22010-06-08 16:52:24 +00002355const char *
2356ProcessGDBRemote::GetDispatchQueueNameForThread
2357(
2358 addr_t thread_dispatch_qaddr,
2359 std::string &dispatch_queue_name
2360)
2361{
2362 dispatch_queue_name.clear();
2363 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2364 {
2365 // Cache the dispatch_queue_offsets_addr value so we don't always have
2366 // to look it up
2367 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2368 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002369 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2370 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002371 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002372 if (module_sp)
2373 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2374
2375 if (dispatch_queue_offsets_symbol == NULL)
2376 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002377 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002378 if (module_sp)
2379 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2380 }
Chris Lattner24943d22010-06-08 16:52:24 +00002381 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002382 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002383
2384 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2385 return NULL;
2386 }
2387
2388 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002389 DataExtractor data (memory_buffer,
2390 sizeof(memory_buffer),
2391 m_target.GetArchitecture().GetByteOrder(),
2392 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002393
2394 // Excerpt from src/queue_private.h
2395 struct dispatch_queue_offsets_s
2396 {
2397 uint16_t dqo_version;
2398 uint16_t dqo_label;
2399 uint16_t dqo_label_size;
2400 } dispatch_queue_offsets;
2401
2402
2403 Error error;
2404 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2405 {
2406 uint32_t data_offset = 0;
2407 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2408 {
2409 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2410 {
2411 data_offset = 0;
2412 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2413 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2414 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2415 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2416 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2417 dispatch_queue_name.erase (bytes_read);
2418 }
2419 }
2420 }
2421 }
2422 if (dispatch_queue_name.empty())
2423 return NULL;
2424 return dispatch_queue_name.c_str();
2425}
2426
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002427//uint32_t
2428//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2429//{
2430// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2431// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2432// if (m_local_debugserver)
2433// {
2434// return Host::ListProcessesMatchingName (name, matches, pids);
2435// }
2436// else
2437// {
2438// // FIXME: Implement talking to the remote debugserver.
2439// return 0;
2440// }
2441//
2442//}
2443//
Jim Ingham55e01d82011-01-22 01:33:44 +00002444bool
2445ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2446 lldb_private::StoppointCallbackContext *context,
2447 lldb::user_id_t break_id,
2448 lldb::user_id_t break_loc_id)
2449{
2450 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2451 // run so I can stop it if that's what I want to do.
2452 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2453 if (log)
2454 log->Printf("Hit New Thread Notification breakpoint.");
2455 return false;
2456}
2457
2458
2459bool
2460ProcessGDBRemote::StartNoticingNewThreads()
2461{
2462 static const char *bp_names[] =
2463 {
2464 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002465 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002466 "_pthread_start",
2467 NULL
2468 };
2469
2470 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2471 size_t num_bps = m_thread_observation_bps.size();
2472 if (num_bps != 0)
2473 {
2474 for (int i = 0; i < num_bps; i++)
2475 {
2476 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2477 if (break_sp)
2478 {
2479 if (log)
2480 log->Printf("Enabled noticing new thread breakpoint.");
2481 break_sp->SetEnabled(true);
2482 }
2483 }
2484 }
2485 else
2486 {
2487 for (int i = 0; bp_names[i] != NULL; i++)
2488 {
2489 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2490 if (breakpoint)
2491 {
2492 if (log)
2493 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2494 m_thread_observation_bps.push_back(breakpoint->GetID());
2495 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2496 }
2497 else
2498 {
2499 if (log)
2500 log->Printf("Failed to create new thread notification breakpoint.");
2501 return false;
2502 }
2503 }
2504 }
2505
2506 return true;
2507}
2508
2509bool
2510ProcessGDBRemote::StopNoticingNewThreads()
2511{
Jim Inghamff276fe2011-02-08 05:19:01 +00002512 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2513 if (log)
2514 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002515 size_t num_bps = m_thread_observation_bps.size();
2516 if (num_bps != 0)
2517 {
2518 for (int i = 0; i < num_bps; i++)
2519 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002520
2521 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2522 if (break_sp)
2523 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002524 break_sp->SetEnabled(false);
2525 }
2526 }
2527 }
2528 return true;
2529}
2530
2531