blob: 14f31004a8565d20578bab049ed0dc8453457618 [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>
Greg Clayton989816b2011-05-14 01:50:35 +000014#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000016#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000017#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000018
19// C++ Includes
20#include <algorithm>
21#include <map>
22
23// Other libraries and framework includes
24
25#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000026#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Core/ArchSpec.h"
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000030#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Core/InputReader.h"
32#include "lldb/Core/Module.h"
33#include "lldb/Core/PluginManager.h"
34#include "lldb/Core/State.h"
35#include "lldb/Core/StreamString.h"
36#include "lldb/Core/Timer.h"
37#include "lldb/Host/TimeValue.h"
38#include "lldb/Symbol/ObjectFile.h"
39#include "lldb/Target/DynamicLoader.h"
40#include "lldb/Target/Target.h"
41#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000042#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000043#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044
45// Project includes
46#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000047#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000048#include "GDBRemoteRegisterContext.h"
49#include "ProcessGDBRemote.h"
50#include "ProcessGDBRemoteLog.h"
51#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000052#include "StopInfoMachException.h"
53
Chris Lattner24943d22010-06-08 16:52:24 +000054
Chris Lattner24943d22010-06-08 16:52:24 +000055
56#define DEBUGSERVER_BASENAME "debugserver"
57using namespace lldb;
58using namespace lldb_private;
59
Jim Inghamf9600482011-03-29 21:45:47 +000060static bool rand_initialized = false;
61
Chris Lattner24943d22010-06-08 16:52:24 +000062static inline uint16_t
63get_random_port ()
64{
Jim Inghamf9600482011-03-29 21:45:47 +000065 if (!rand_initialized)
66 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000067 time_t seed = time(NULL);
68
Jim Inghamf9600482011-03-29 21:45:47 +000069 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000070 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000071 }
Stephen Wilson50daf772011-03-25 18:16:28 +000072 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000073}
74
75
76const char *
77ProcessGDBRemote::GetPluginNameStatic()
78{
Greg Claytonb1888f22011-03-19 01:12:21 +000079 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000080}
81
82const char *
83ProcessGDBRemote::GetPluginDescriptionStatic()
84{
85 return "GDB Remote protocol based debugging plug-in.";
86}
87
88void
89ProcessGDBRemote::Terminate()
90{
91 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
92}
93
94
95Process*
96ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
97{
98 return new ProcessGDBRemote (target, listener);
99}
100
101bool
102ProcessGDBRemote::CanDebug(Target &target)
103{
104 // For now we are just making sure the file exists for a given module
105 ModuleSP exe_module_sp(target.GetExecutableModule());
106 if (exe_module_sp.get())
107 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000108 // However, if there is no executable module, we return true since we might be preparing to attach.
109 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000110}
111
112//----------------------------------------------------------------------
113// ProcessGDBRemote constructor
114//----------------------------------------------------------------------
115ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
116 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000117 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000118 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000119 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000120 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000121 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000122 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000123 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000124 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
125 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000126 m_continue_c_tids (),
127 m_continue_C_tids (),
128 m_continue_s_tids (),
129 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000130 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000131 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000132 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000133 m_local_debugserver (true),
134 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000135{
Greg Claytonff39f742011-04-01 00:29:43 +0000136 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
137 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000138}
139
140//----------------------------------------------------------------------
141// Destructor
142//----------------------------------------------------------------------
143ProcessGDBRemote::~ProcessGDBRemote()
144{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000145 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000146 {
147 Host::ThreadCancel (m_debugserver_thread, NULL);
148 thread_result_t thread_result;
149 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
150 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
151 }
Chris Lattner24943d22010-06-08 16:52:24 +0000152 // m_mach_process.UnregisterNotificationCallbacks (this);
153 Clear();
154}
155
156//----------------------------------------------------------------------
157// PluginInterface
158//----------------------------------------------------------------------
159const char *
160ProcessGDBRemote::GetPluginName()
161{
162 return "Process debugging plug-in that uses the GDB remote protocol";
163}
164
165const char *
166ProcessGDBRemote::GetShortPluginName()
167{
168 return GetPluginNameStatic();
169}
170
171uint32_t
172ProcessGDBRemote::GetPluginVersion()
173{
174 return 1;
175}
176
177void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000178ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000179{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000180 if (!force && m_register_info.GetNumRegisters() > 0)
181 return;
182
183 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000184 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000185 uint32_t reg_offset = 0;
186 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000187 StringExtractorGDBRemote::ResponseType response_type;
188 for (response_type = StringExtractorGDBRemote::eResponse;
189 response_type == StringExtractorGDBRemote::eResponse;
190 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000191 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000192 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
193 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000194 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000195 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000196 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000197 response_type = response.GetResponseType();
198 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000199 {
200 std::string name;
201 std::string value;
202 ConstString reg_name;
203 ConstString alt_name;
204 ConstString set_name;
205 RegisterInfo reg_info = { NULL, // Name
206 NULL, // Alt name
207 0, // byte size
208 reg_offset, // offset
209 eEncodingUint, // encoding
210 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000211 {
212 LLDB_INVALID_REGNUM, // GCC reg num
213 LLDB_INVALID_REGNUM, // DWARF reg num
214 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000215 reg_num, // GDB reg num
216 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000217 }
218 };
219
220 while (response.GetNameColonValue(name, value))
221 {
222 if (name.compare("name") == 0)
223 {
224 reg_name.SetCString(value.c_str());
225 }
226 else if (name.compare("alt-name") == 0)
227 {
228 alt_name.SetCString(value.c_str());
229 }
230 else if (name.compare("bitsize") == 0)
231 {
232 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
233 }
234 else if (name.compare("offset") == 0)
235 {
236 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000237 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000238 {
239 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000240 }
241 }
242 else if (name.compare("encoding") == 0)
243 {
244 if (value.compare("uint") == 0)
245 reg_info.encoding = eEncodingUint;
246 else if (value.compare("sint") == 0)
247 reg_info.encoding = eEncodingSint;
248 else if (value.compare("ieee754") == 0)
249 reg_info.encoding = eEncodingIEEE754;
250 else if (value.compare("vector") == 0)
251 reg_info.encoding = eEncodingVector;
252 }
253 else if (name.compare("format") == 0)
254 {
255 if (value.compare("binary") == 0)
256 reg_info.format = eFormatBinary;
257 else if (value.compare("decimal") == 0)
258 reg_info.format = eFormatDecimal;
259 else if (value.compare("hex") == 0)
260 reg_info.format = eFormatHex;
261 else if (value.compare("float") == 0)
262 reg_info.format = eFormatFloat;
263 else if (value.compare("vector-sint8") == 0)
264 reg_info.format = eFormatVectorOfSInt8;
265 else if (value.compare("vector-uint8") == 0)
266 reg_info.format = eFormatVectorOfUInt8;
267 else if (value.compare("vector-sint16") == 0)
268 reg_info.format = eFormatVectorOfSInt16;
269 else if (value.compare("vector-uint16") == 0)
270 reg_info.format = eFormatVectorOfUInt16;
271 else if (value.compare("vector-sint32") == 0)
272 reg_info.format = eFormatVectorOfSInt32;
273 else if (value.compare("vector-uint32") == 0)
274 reg_info.format = eFormatVectorOfUInt32;
275 else if (value.compare("vector-float32") == 0)
276 reg_info.format = eFormatVectorOfFloat32;
277 else if (value.compare("vector-uint128") == 0)
278 reg_info.format = eFormatVectorOfUInt128;
279 }
280 else if (name.compare("set") == 0)
281 {
282 set_name.SetCString(value.c_str());
283 }
284 else if (name.compare("gcc") == 0)
285 {
286 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
287 }
288 else if (name.compare("dwarf") == 0)
289 {
290 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
291 }
292 else if (name.compare("generic") == 0)
293 {
294 if (value.compare("pc") == 0)
295 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
296 else if (value.compare("sp") == 0)
297 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
298 else if (value.compare("fp") == 0)
299 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
300 else if (value.compare("ra") == 0)
301 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
302 else if (value.compare("flags") == 0)
303 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
304 }
305 }
306
Jason Molenda53d96862010-06-11 23:44:18 +0000307 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000308 assert (reg_info.byte_size != 0);
309 reg_offset += reg_info.byte_size;
310 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
311 }
312 }
313 else
314 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000315 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000316 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000317 }
318 }
319
320 if (reg_num == 0)
321 {
322 // We didn't get anything. See if we are debugging ARM and fill with
323 // a hard coded register set until we can get an updated debugserver
324 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000325 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000326 m_register_info.HardcodeARMRegisters();
327 }
328 m_register_info.Finalize ();
329}
330
331Error
332ProcessGDBRemote::WillLaunch (Module* module)
333{
334 return WillLaunchOrAttach ();
335}
336
337Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000338ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000339{
340 return WillLaunchOrAttach ();
341}
342
343Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000344ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000345{
346 return WillLaunchOrAttach ();
347}
348
349Error
Greg Claytone71e2582011-02-04 01:58:07 +0000350ProcessGDBRemote::DoConnectRemote (const char *remote_url)
351{
352 Error error (WillLaunchOrAttach ());
353
354 if (error.Fail())
355 return error;
356
Greg Clayton180546b2011-04-30 01:09:13 +0000357 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000358
359 if (error.Fail())
360 return error;
361 StartAsyncThread ();
362
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000363 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000364 if (pid == LLDB_INVALID_PROCESS_ID)
365 {
366 // We don't have a valid process ID, so note that we are connected
367 // and could now request to launch or attach, or get remote process
368 // listings...
369 SetPrivateState (eStateConnected);
370 }
371 else
372 {
373 // We have a valid process
374 SetID (pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000375 UpdateThreadListIfNeeded ();
Greg Claytone71e2582011-02-04 01:58:07 +0000376 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000377 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000378 {
379 const StateType state = SetThreadStopInfo (response);
380 if (state == eStateStopped)
381 {
382 SetPrivateState (state);
383 }
384 else
385 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
386 }
387 else
388 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
389 }
390 return error;
391}
392
393Error
Chris Lattner24943d22010-06-08 16:52:24 +0000394ProcessGDBRemote::WillLaunchOrAttach ()
395{
396 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000397 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000398 return error;
399}
400
401//----------------------------------------------------------------------
402// Process Control
403//----------------------------------------------------------------------
404Error
405ProcessGDBRemote::DoLaunch
406(
407 Module* module,
408 char const *argv[],
409 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000410 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000411 const char *stdin_path,
412 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000413 const char *stderr_path,
414 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000415)
416{
Greg Clayton4b407112010-09-30 21:49:03 +0000417 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000418 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
419 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
420 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000421
422 ObjectFile * object_file = module->GetObjectFile();
423 if (object_file)
424 {
Chris Lattner24943d22010-06-08 16:52:24 +0000425 char host_port[128];
426 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000427 char connect_url[128];
428 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000429
Greg Claytona2f74232011-02-24 22:24:29 +0000430 // Make sure we aren't already connected?
431 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000432 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000433 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000434 if (error.Fail())
435 return error;
436
Greg Claytone71e2582011-02-04 01:58:07 +0000437 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000438 }
439
440 if (error.Success())
441 {
442 lldb_utility::PseudoTerminal pty;
443 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000444
445 // If the debugserver is local and we aren't disabling STDIO, lets use
446 // a pseudo terminal to instead of relying on the 'O' packets for stdio
447 // since 'O' packets can really slow down debugging if the inferior
448 // does a lot of output.
449 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000450 {
451 const char *slave_name = NULL;
452 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000453 {
Greg Claytona2f74232011-02-24 22:24:29 +0000454 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
455 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000456 }
Greg Claytona2f74232011-02-24 22:24:29 +0000457 if (stdin_path == NULL)
458 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000459
Greg Claytona2f74232011-02-24 22:24:29 +0000460 if (stdout_path == NULL)
461 stdout_path = slave_name;
462
463 if (stderr_path == NULL)
464 stderr_path = slave_name;
465 }
466
Greg Claytonafb81862011-03-02 21:34:46 +0000467 // Set STDIN to /dev/null if we want STDIO disabled or if either
468 // STDOUT or STDERR have been set to something and STDIN hasn't
469 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000470 stdin_path = "/dev/null";
471
Greg Claytonafb81862011-03-02 21:34:46 +0000472 // Set STDOUT to /dev/null if we want STDIO disabled or if either
473 // STDIN or STDERR have been set to something and STDOUT hasn't
474 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000475 stdout_path = "/dev/null";
476
Greg Claytonafb81862011-03-02 21:34:46 +0000477 // Set STDERR to /dev/null if we want STDIO disabled or if either
478 // STDIN or STDOUT have been set to something and STDERR hasn't
479 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000480 stderr_path = "/dev/null";
481
482 if (stdin_path)
483 m_gdb_comm.SetSTDIN (stdin_path);
484 if (stdout_path)
485 m_gdb_comm.SetSTDOUT (stdout_path);
486 if (stderr_path)
487 m_gdb_comm.SetSTDERR (stderr_path);
488
489 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
490
Greg Claytona4582402011-05-08 04:53:50 +0000491 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000492
493 if (working_dir && working_dir[0])
494 {
495 m_gdb_comm.SetWorkingDir (working_dir);
496 }
497
498 // Send the environment and the program + arguments after we connect
499 if (envp)
500 {
501 const char *env_entry;
502 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000503 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000504 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000505 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000506 }
Greg Claytona2f74232011-02-24 22:24:29 +0000507 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000508
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000509 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
510 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
511 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000512 if (arg_packet_err == 0)
513 {
514 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000515 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000516 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000517 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000518 }
519 else
520 {
Greg Claytona2f74232011-02-24 22:24:29 +0000521 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000522 }
Greg Claytona2f74232011-02-24 22:24:29 +0000523 }
524 else
525 {
526 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
527 }
Chris Lattner24943d22010-06-08 16:52:24 +0000528
Greg Claytona2f74232011-02-24 22:24:29 +0000529 if (GetID() == LLDB_INVALID_PROCESS_ID)
530 {
531 KillDebugserverProcess ();
532 return error;
533 }
534
535 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000536 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000537 {
538 SetPrivateState (SetThreadStopInfo (response));
539
540 if (!disable_stdio)
541 {
542 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
543 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
544 }
Chris Lattner24943d22010-06-08 16:52:24 +0000545 }
546 }
Chris Lattner24943d22010-06-08 16:52:24 +0000547 }
548 else
549 {
550 // Set our user ID to an invalid process ID.
551 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000552 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
553 module->GetFileSpec().GetFilename().AsCString(),
554 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000555 }
Chris Lattner24943d22010-06-08 16:52:24 +0000556 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000557
Chris Lattner24943d22010-06-08 16:52:24 +0000558}
559
560
561Error
Greg Claytone71e2582011-02-04 01:58:07 +0000562ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000563{
564 Error error;
565 // Sleep and wait a bit for debugserver to start to listen...
566 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
567 if (conn_ap.get())
568 {
Chris Lattner24943d22010-06-08 16:52:24 +0000569 const uint32_t max_retry_count = 50;
570 uint32_t retry_count = 0;
571 while (!m_gdb_comm.IsConnected())
572 {
Greg Claytone71e2582011-02-04 01:58:07 +0000573 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000574 {
575 m_gdb_comm.SetConnection (conn_ap.release());
576 break;
577 }
578 retry_count++;
579
580 if (retry_count >= max_retry_count)
581 break;
582
583 usleep (100000);
584 }
585 }
586
587 if (!m_gdb_comm.IsConnected())
588 {
589 if (error.Success())
590 error.SetErrorString("not connected to remote gdb server");
591 return error;
592 }
593
Greg Clayton24bc5d92011-03-30 18:16:51 +0000594 // We always seem to be able to open a connection to a local port
595 // so we need to make sure we can then send data to it. If we can't
596 // then we aren't actually connected to anything, so try and do the
597 // handshake with the remote GDB server and make sure that goes
598 // alright.
599 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000600 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000601 m_gdb_comm.Disconnect();
602 if (error.Success())
603 error.SetErrorString("not connected to remote gdb server");
604 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000605 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000606 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
607 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
608 this,
609 m_debugserver_pid,
610 false);
611 m_gdb_comm.ResetDiscoverableSettings();
612 m_gdb_comm.QueryNoAckModeSupported ();
613 m_gdb_comm.GetThreadSuffixSupported ();
614 m_gdb_comm.GetHostInfo ();
615 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000616 return error;
617}
618
619void
620ProcessGDBRemote::DidLaunchOrAttach ()
621{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000622 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
623 if (log)
624 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000625 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000626 {
627 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
628
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000629 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000630
Chris Lattner24943d22010-06-08 16:52:24 +0000631 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000632
Greg Claytoncb8977d2011-03-23 00:09:55 +0000633 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
634 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000635 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000636 ArchSpec &target_arch = GetTarget().GetArchitecture();
637
638 if (target_arch.IsValid())
639 {
640 // If the remote host is ARM and we have apple as the vendor, then
641 // ARM executables and shared libraries can have mixed ARM architectures.
642 // You can have an armv6 executable, and if the host is armv7, then the
643 // system will load the best possible architecture for all shared libraries
644 // it has, so we really need to take the remote host architecture as our
645 // defacto architecture in this case.
646
647 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
648 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
649 {
650 target_arch = gdb_remote_arch;
651 }
652 else
653 {
654 // Fill in what is missing in the triple
655 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
656 llvm::Triple &target_triple = target_arch.GetTriple();
657 if (target_triple.getVendor() == llvm::Triple::UnknownVendor)
658 target_triple.setVendor (remote_triple.getVendor());
659
660 if (target_triple.getOS() == llvm::Triple::UnknownOS)
661 target_triple.setOS (remote_triple.getOS());
662
663 if (target_triple.getEnvironment() == llvm::Triple::UnknownEnvironment)
664 target_triple.setEnvironment (remote_triple.getEnvironment());
665 }
666 }
667 else
668 {
669 // The target doesn't have a valid architecture yet, set it from
670 // the architecture we got from the remote GDB server
671 target_arch = gdb_remote_arch;
672 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000673 }
Chris Lattner24943d22010-06-08 16:52:24 +0000674 }
675}
676
677void
678ProcessGDBRemote::DidLaunch ()
679{
680 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000681}
682
683Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000684ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000685{
686 Error error;
687 // Clear out and clean up from any current state
688 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000689 if (attach_pid != LLDB_INVALID_PROCESS_ID)
690 {
Greg Claytona2f74232011-02-24 22:24:29 +0000691 // Make sure we aren't already connected?
692 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000693 {
Greg Claytona2f74232011-02-24 22:24:29 +0000694 char host_port[128];
695 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
696 char connect_url[128];
697 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000698
Greg Claytonb72d0f02011-04-12 05:54:46 +0000699 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000700
701 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000702 {
Greg Claytona2f74232011-02-24 22:24:29 +0000703 const char *error_string = error.AsCString();
704 if (error_string == NULL)
705 error_string = "unable to launch " DEBUGSERVER_BASENAME;
706
707 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000708 }
Greg Claytona2f74232011-02-24 22:24:29 +0000709 else
710 {
711 error = ConnectToDebugserver (connect_url);
712 }
713 }
714
715 if (error.Success())
716 {
717 char packet[64];
718 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
719
720 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000721 }
722 }
Chris Lattner24943d22010-06-08 16:52:24 +0000723 return error;
724}
725
726size_t
727ProcessGDBRemote::AttachInputReaderCallback
728(
729 void *baton,
730 InputReader *reader,
731 lldb::InputReaderAction notification,
732 const char *bytes,
733 size_t bytes_len
734)
735{
736 if (notification == eInputReaderGotToken)
737 {
738 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
739 if (gdb_process->m_waiting_for_attach)
740 gdb_process->m_waiting_for_attach = false;
741 reader->SetIsDone(true);
742 return 1;
743 }
744 return 0;
745}
746
747Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000748ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000749{
750 Error error;
751 // Clear out and clean up from any current state
752 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000753
Chris Lattner24943d22010-06-08 16:52:24 +0000754 if (process_name && process_name[0])
755 {
Greg Claytona2f74232011-02-24 22:24:29 +0000756 // Make sure we aren't already connected?
757 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000758 {
Greg Claytona2f74232011-02-24 22:24:29 +0000759 char host_port[128];
760 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
761 char connect_url[128];
762 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
763
Greg Claytonb72d0f02011-04-12 05:54:46 +0000764 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000765 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000766 {
Greg Claytona2f74232011-02-24 22:24:29 +0000767 const char *error_string = error.AsCString();
768 if (error_string == NULL)
769 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000770
Greg Claytona2f74232011-02-24 22:24:29 +0000771 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000772 }
Greg Claytona2f74232011-02-24 22:24:29 +0000773 else
774 {
775 error = ConnectToDebugserver (connect_url);
776 }
777 }
778
779 if (error.Success())
780 {
781 StreamString packet;
782
783 if (wait_for_launch)
784 packet.PutCString("vAttachWait");
785 else
786 packet.PutCString("vAttachName");
787 packet.PutChar(';');
788 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
789
790 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
791
Chris Lattner24943d22010-06-08 16:52:24 +0000792 }
793 }
Chris Lattner24943d22010-06-08 16:52:24 +0000794 return error;
795}
796
Chris Lattner24943d22010-06-08 16:52:24 +0000797
798void
799ProcessGDBRemote::DidAttach ()
800{
Greg Claytone71e2582011-02-04 01:58:07 +0000801 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000802}
803
804Error
805ProcessGDBRemote::WillResume ()
806{
Greg Claytonc1f45872011-02-12 06:28:37 +0000807 m_continue_c_tids.clear();
808 m_continue_C_tids.clear();
809 m_continue_s_tids.clear();
810 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000811 return Error();
812}
813
814Error
815ProcessGDBRemote::DoResume ()
816{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000817 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000818 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
819 if (log)
820 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000821
822 Listener listener ("gdb-remote.resume-packet-sent");
823 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
824 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000825 StreamString continue_packet;
826 bool continue_packet_error = false;
827 if (m_gdb_comm.HasAnyVContSupport ())
828 {
829 continue_packet.PutCString ("vCont");
830
831 if (!m_continue_c_tids.empty())
832 {
833 if (m_gdb_comm.GetVContSupported ('c'))
834 {
835 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)
836 continue_packet.Printf(";c:%4.4x", *t_pos);
837 }
838 else
839 continue_packet_error = true;
840 }
841
842 if (!continue_packet_error && !m_continue_C_tids.empty())
843 {
844 if (m_gdb_comm.GetVContSupported ('C'))
845 {
846 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)
847 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
848 }
849 else
850 continue_packet_error = true;
851 }
Greg Claytonb749a262010-12-03 06:02:24 +0000852
Greg Claytonc1f45872011-02-12 06:28:37 +0000853 if (!continue_packet_error && !m_continue_s_tids.empty())
854 {
855 if (m_gdb_comm.GetVContSupported ('s'))
856 {
857 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)
858 continue_packet.Printf(";s:%4.4x", *t_pos);
859 }
860 else
861 continue_packet_error = true;
862 }
863
864 if (!continue_packet_error && !m_continue_S_tids.empty())
865 {
866 if (m_gdb_comm.GetVContSupported ('S'))
867 {
868 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)
869 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
870 }
871 else
872 continue_packet_error = true;
873 }
874
875 if (continue_packet_error)
876 continue_packet.GetString().clear();
877 }
878 else
879 continue_packet_error = true;
880
881 if (continue_packet_error)
882 {
883 continue_packet_error = false;
884 // Either no vCont support, or we tried to use part of the vCont
885 // packet that wasn't supported by the remote GDB server.
886 // We need to try and make a simple packet that can do our continue
887 const size_t num_threads = GetThreadList().GetSize();
888 const size_t num_continue_c_tids = m_continue_c_tids.size();
889 const size_t num_continue_C_tids = m_continue_C_tids.size();
890 const size_t num_continue_s_tids = m_continue_s_tids.size();
891 const size_t num_continue_S_tids = m_continue_S_tids.size();
892 if (num_continue_c_tids > 0)
893 {
894 if (num_continue_c_tids == num_threads)
895 {
896 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000897 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000898 continue_packet.PutChar ('c');
899 }
900 else if (num_continue_c_tids == 1 &&
901 num_continue_C_tids == 0 &&
902 num_continue_s_tids == 0 &&
903 num_continue_S_tids == 0 )
904 {
905 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000906 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000907 continue_packet.PutChar ('c');
908 }
909 else
910 {
911 // We can't represent this continue packet....
912 continue_packet_error = true;
913 }
914 }
915
916 if (!continue_packet_error && num_continue_C_tids > 0)
917 {
918 if (num_continue_C_tids == num_threads)
919 {
920 const int continue_signo = m_continue_C_tids.front().second;
921 if (num_continue_C_tids > 1)
922 {
923 for (size_t i=1; i<num_threads; ++i)
924 {
925 if (m_continue_C_tids[i].second != continue_signo)
926 continue_packet_error = true;
927 }
928 }
929 if (!continue_packet_error)
930 {
931 // Add threads continuing with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000932 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000933 continue_packet.Printf("C%2.2x", continue_signo);
934 }
935 }
936 else if (num_continue_c_tids == 0 &&
937 num_continue_C_tids == 1 &&
938 num_continue_s_tids == 0 &&
939 num_continue_S_tids == 0 )
940 {
941 // Only one thread is continuing with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +0000942 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000943 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
944 }
945 else
946 {
947 // We can't represent this continue packet....
948 continue_packet_error = true;
949 }
950 }
951
952 if (!continue_packet_error && num_continue_s_tids > 0)
953 {
954 if (num_continue_s_tids == num_threads)
955 {
956 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000957 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000958 continue_packet.PutChar ('s');
959 }
960 else if (num_continue_c_tids == 0 &&
961 num_continue_C_tids == 0 &&
962 num_continue_s_tids == 1 &&
963 num_continue_S_tids == 0 )
964 {
965 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +0000966 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000967 continue_packet.PutChar ('s');
968 }
969 else
970 {
971 // We can't represent this continue packet....
972 continue_packet_error = true;
973 }
974 }
975
976 if (!continue_packet_error && num_continue_S_tids > 0)
977 {
978 if (num_continue_S_tids == num_threads)
979 {
980 const int step_signo = m_continue_S_tids.front().second;
981 // Are all threads trying to step with the same signal?
982 if (num_continue_S_tids > 1)
983 {
984 for (size_t i=1; i<num_threads; ++i)
985 {
986 if (m_continue_S_tids[i].second != step_signo)
987 continue_packet_error = true;
988 }
989 }
990 if (!continue_packet_error)
991 {
992 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000993 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000994 continue_packet.Printf("S%2.2x", step_signo);
995 }
996 }
997 else if (num_continue_c_tids == 0 &&
998 num_continue_C_tids == 0 &&
999 num_continue_s_tids == 0 &&
1000 num_continue_S_tids == 1 )
1001 {
1002 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001003 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001004 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1005 }
1006 else
1007 {
1008 // We can't represent this continue packet....
1009 continue_packet_error = true;
1010 }
1011 }
1012 }
1013
1014 if (continue_packet_error)
1015 {
1016 error.SetErrorString ("can't make continue packet for this resume");
1017 }
1018 else
1019 {
1020 EventSP event_sp;
1021 TimeValue timeout;
1022 timeout = TimeValue::Now();
1023 timeout.OffsetWithSeconds (5);
1024 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1025
1026 if (listener.WaitForEvent (&timeout, event_sp) == false)
1027 error.SetErrorString("Resume timed out.");
1028 }
Greg Claytonb749a262010-12-03 06:02:24 +00001029 }
1030
Jim Ingham3ae449a2010-11-17 02:32:00 +00001031 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001032}
1033
Chris Lattner24943d22010-06-08 16:52:24 +00001034uint32_t
1035ProcessGDBRemote::UpdateThreadListIfNeeded ()
1036{
1037 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001038 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001039 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001040 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1041
Greg Clayton5205f0b2010-09-03 17:10:42 +00001042 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001043 const uint32_t stop_id = GetStopID();
1044 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1045 {
1046 // Update the thread list's stop id immediately so we don't recurse into this function.
1047 ThreadList curr_thread_list (this);
1048 curr_thread_list.SetStopID(stop_id);
1049
1050 Error err;
1051 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001052 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, false);
Greg Clayton61d043b2011-03-22 04:00:09 +00001053 response.IsNormalResponse();
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001054 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001055 {
1056 char ch = response.GetChar();
1057 if (ch == 'l')
1058 break;
1059 if (ch == 'm')
1060 {
1061 do
1062 {
1063 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1064
1065 if (tid != LLDB_INVALID_THREAD_ID)
1066 {
1067 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001068 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001069 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1070 curr_thread_list.AddThread(thread_sp);
1071 }
1072
1073 ch = response.GetChar();
1074 } while (ch == ',');
1075 }
1076 }
1077
1078 m_thread_list = curr_thread_list;
1079
1080 SetThreadStopInfo (m_last_stop_packet);
1081 }
1082 return GetThreadList().GetSize(false);
1083}
1084
1085
1086StateType
1087ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1088{
1089 const char stop_type = stop_packet.GetChar();
1090 switch (stop_type)
1091 {
1092 case 'T':
1093 case 'S':
1094 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001095 if (GetStopID() == 0)
1096 {
1097 // Our first stop, make sure we have a process ID, and also make
1098 // sure we know about our registers
1099 if (GetID() == LLDB_INVALID_PROCESS_ID)
1100 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001101 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001102 if (pid != LLDB_INVALID_PROCESS_ID)
1103 SetID (pid);
1104 }
1105 BuildDynamicRegisterInfo (true);
1106 }
Chris Lattner24943d22010-06-08 16:52:24 +00001107 // Stop with signal and thread info
1108 const uint8_t signo = stop_packet.GetHexU8();
1109 std::string name;
1110 std::string value;
1111 std::string thread_name;
1112 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001113 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001114 uint32_t tid = LLDB_INVALID_THREAD_ID;
1115 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1116 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001117 ThreadSP thread_sp;
1118
Chris Lattner24943d22010-06-08 16:52:24 +00001119 while (stop_packet.GetNameColonValue(name, value))
1120 {
1121 if (name.compare("metype") == 0)
1122 {
1123 // exception type in big endian hex
1124 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1125 }
1126 else if (name.compare("mecount") == 0)
1127 {
1128 // exception count in big endian hex
1129 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1130 }
1131 else if (name.compare("medata") == 0)
1132 {
1133 // exception data in big endian hex
1134 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1135 }
1136 else if (name.compare("thread") == 0)
1137 {
1138 // thread in big endian hex
1139 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001140 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001141 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001142 if (!thread_sp)
1143 {
1144 // Create the thread if we need to
1145 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1146 m_thread_list.AddThread(thread_sp);
1147 }
Chris Lattner24943d22010-06-08 16:52:24 +00001148 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001149 else if (name.compare("hexname") == 0)
1150 {
1151 StringExtractor name_extractor;
1152 // Swap "value" over into "name_extractor"
1153 name_extractor.GetStringRef().swap(value);
1154 // Now convert the HEX bytes into a string value
1155 name_extractor.GetHexByteString (value);
1156 thread_name.swap (value);
1157 }
Chris Lattner24943d22010-06-08 16:52:24 +00001158 else if (name.compare("name") == 0)
1159 {
1160 thread_name.swap (value);
1161 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001162 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001163 {
1164 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1165 }
Greg Claytona875b642011-01-09 21:07:35 +00001166 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1167 {
1168 // We have a register number that contains an expedited
1169 // register value. Lets supply this register to our thread
1170 // so it won't have to go and read it.
1171 if (thread_sp)
1172 {
1173 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1174
1175 if (reg != UINT32_MAX)
1176 {
1177 StringExtractor reg_value_extractor;
1178 // Swap "value" over into "reg_value_extractor"
1179 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001180 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1181 {
1182 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1183 name.c_str(),
1184 reg,
1185 reg,
1186 reg_value_extractor.GetStringRef().c_str(),
1187 stop_packet.GetStringRef().c_str());
1188 }
Greg Claytona875b642011-01-09 21:07:35 +00001189 }
1190 }
1191 }
Chris Lattner24943d22010-06-08 16:52:24 +00001192 }
Chris Lattner24943d22010-06-08 16:52:24 +00001193
1194 if (thread_sp)
1195 {
1196 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1197
1198 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001199 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001200 if (exc_type != 0)
1201 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001202 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001203
1204 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1205 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001206 exc_data_size,
1207 exc_data_size >= 1 ? exc_data[0] : 0,
1208 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001209 }
1210 else if (signo)
1211 {
Greg Clayton643ee732010-08-04 01:40:35 +00001212 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001213 }
1214 else
1215 {
Greg Clayton643ee732010-08-04 01:40:35 +00001216 StopInfoSP invalid_stop_info_sp;
1217 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001218 }
1219 }
1220 return eStateStopped;
1221 }
1222 break;
1223
1224 case 'W':
1225 // process exited
1226 return eStateExited;
1227
1228 default:
1229 break;
1230 }
1231 return eStateInvalid;
1232}
1233
1234void
1235ProcessGDBRemote::RefreshStateAfterStop ()
1236{
Jim Ingham7508e732010-08-09 23:31:02 +00001237 // FIXME - add a variable to tell that we're in the middle of attaching if we
1238 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001239 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001240// if (!GetTarget().GetArchitecture().IsValid())
1241// {
1242// Module *exe_module = GetTarget().GetExecutableModule().get();
1243// if (exe_module)
1244// m_arch_spec = exe_module->GetArchitecture();
1245// }
1246
Chris Lattner24943d22010-06-08 16:52:24 +00001247 // Let all threads recover from stopping and do any clean up based
1248 // on the previous thread state (if any).
1249 m_thread_list.RefreshStateAfterStop();
1250
1251 // Discover new threads:
1252 UpdateThreadListIfNeeded ();
1253}
1254
1255Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001256ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001257{
1258 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001259
Greg Claytona4881d02011-01-22 07:12:45 +00001260 bool timed_out = false;
1261 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001262
1263 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001264 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001265 // We are being asked to halt during an attach. We need to just close
1266 // our file handle and debugserver will go away, and we can be done...
1267 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001268 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001269 else
1270 {
1271 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1272 {
1273 if (timed_out)
1274 error.SetErrorString("timed out sending interrupt packet");
1275 else
1276 error.SetErrorString("unknown error sending interrupt packet");
1277 }
1278 }
Chris Lattner24943d22010-06-08 16:52:24 +00001279 return error;
1280}
1281
1282Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001283ProcessGDBRemote::InterruptIfRunning
1284(
1285 bool discard_thread_plans,
1286 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001287 EventSP &stop_event_sp
1288)
Chris Lattner24943d22010-06-08 16:52:24 +00001289{
1290 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001291
Greg Clayton2860ba92011-01-23 19:58:49 +00001292 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1293
Greg Clayton68ca8232011-01-25 02:58:48 +00001294 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001295 const bool is_running = m_gdb_comm.IsRunning();
1296 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001297 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001298 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001299 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001300 is_running);
1301
Greg Clayton2860ba92011-01-23 19:58:49 +00001302 if (discard_thread_plans)
1303 {
1304 if (log)
1305 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1306 m_thread_list.DiscardThreadPlans();
1307 }
1308 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001309 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001310 if (catch_stop_event)
1311 {
1312 if (log)
1313 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1314 PausePrivateStateThread();
1315 paused_private_state_thread = true;
1316 }
1317
Greg Clayton4fb400f2010-09-27 21:07:38 +00001318 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001319 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001320 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001321
Greg Clayton72e1c782011-01-22 23:43:18 +00001322 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001323 {
1324 if (timed_out)
1325 error.SetErrorString("timed out sending interrupt packet");
1326 else
1327 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001328 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001329 ResumePrivateStateThread();
1330 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001331 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001332
Greg Clayton72e1c782011-01-22 23:43:18 +00001333 if (catch_stop_event)
1334 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001335 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001336 TimeValue timeout_time;
1337 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001338 timeout_time.OffsetWithSeconds(5);
1339 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001340
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001341 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001342 if (log)
1343 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001344
Greg Clayton2860ba92011-01-23 19:58:49 +00001345 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001346 error.SetErrorString("unable to verify target stopped");
1347 }
1348
Greg Clayton68ca8232011-01-25 02:58:48 +00001349 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001350 {
1351 if (log)
1352 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001353 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001354 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001355 }
Chris Lattner24943d22010-06-08 16:52:24 +00001356 return error;
1357}
1358
Greg Clayton4fb400f2010-09-27 21:07:38 +00001359Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001360ProcessGDBRemote::WillDetach ()
1361{
Greg Clayton2860ba92011-01-23 19:58:49 +00001362 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1363 if (log)
1364 log->Printf ("ProcessGDBRemote::WillDetach()");
1365
Greg Clayton72e1c782011-01-22 23:43:18 +00001366 bool discard_thread_plans = true;
1367 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001368 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001369 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001370}
1371
1372Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001373ProcessGDBRemote::DoDetach()
1374{
1375 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001376 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001377 if (log)
1378 log->Printf ("ProcessGDBRemote::DoDetach()");
1379
1380 DisableAllBreakpointSites ();
1381
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001382 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001383
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001384 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1385 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001386 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001387 if (response_size)
1388 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1389 else
1390 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001391 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001392 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001393 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001394
Greg Clayton4fb400f2010-09-27 21:07:38 +00001395 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001396 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001397
1398 SetPrivateState (eStateDetached);
1399 ResumePrivateStateThread();
1400
1401 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001402 return error;
1403}
Chris Lattner24943d22010-06-08 16:52:24 +00001404
1405Error
1406ProcessGDBRemote::DoDestroy ()
1407{
1408 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001409 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001410 if (log)
1411 log->Printf ("ProcessGDBRemote::DoDestroy()");
1412
1413 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001414 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001415 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001416 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001417 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001418 // We are being asked to halt during an attach. We need to just close
1419 // our file handle and debugserver will go away, and we can be done...
1420 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001421 }
1422 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001423 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001424
1425 StringExtractorGDBRemote response;
1426 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001427 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001428 {
1429 char packet_cmd = response.GetChar(0);
1430
1431 if (packet_cmd == 'W' || packet_cmd == 'X')
1432 {
1433 m_last_stop_packet = response;
1434 SetExitStatus(response.GetHexU8(), NULL);
1435 }
1436 }
1437 else
1438 {
1439 SetExitStatus(SIGABRT, NULL);
1440 //error.SetErrorString("kill packet failed");
1441 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001442 }
1443 }
Chris Lattner24943d22010-06-08 16:52:24 +00001444 StopAsyncThread ();
1445 m_gdb_comm.StopReadThread();
1446 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001447 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001448 return error;
1449}
1450
Chris Lattner24943d22010-06-08 16:52:24 +00001451//------------------------------------------------------------------
1452// Process Queries
1453//------------------------------------------------------------------
1454
1455bool
1456ProcessGDBRemote::IsAlive ()
1457{
Greg Clayton58e844b2010-12-08 05:08:21 +00001458 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001459}
1460
1461addr_t
1462ProcessGDBRemote::GetImageInfoAddress()
1463{
1464 if (!m_gdb_comm.IsRunning())
1465 {
1466 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001467 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001468 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001469 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001470 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1471 }
1472 }
1473 return LLDB_INVALID_ADDRESS;
1474}
1475
Chris Lattner24943d22010-06-08 16:52:24 +00001476//------------------------------------------------------------------
1477// Process Memory
1478//------------------------------------------------------------------
1479size_t
1480ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1481{
1482 if (size > m_max_memory_size)
1483 {
1484 // Keep memory read sizes down to a sane limit. This function will be
1485 // called multiple times in order to complete the task by
1486 // lldb_private::Process so it is ok to do this.
1487 size = m_max_memory_size;
1488 }
1489
1490 char packet[64];
1491 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1492 assert (packet_len + 1 < sizeof(packet));
1493 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001494 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001495 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001496 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001497 {
1498 error.Clear();
1499 return response.GetHexBytes(buf, size, '\xdd');
1500 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001501 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001502 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001503 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001504 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1505 else
1506 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1507 }
1508 else
1509 {
1510 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1511 }
1512 return 0;
1513}
1514
1515size_t
1516ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1517{
1518 StreamString packet;
1519 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001520 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001521 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001522 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001523 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001524 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001525 {
1526 error.Clear();
1527 return size;
1528 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001529 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001530 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001531 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001532 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1533 else
1534 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1535 }
1536 else
1537 {
1538 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1539 }
1540 return 0;
1541}
1542
1543lldb::addr_t
1544ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1545{
Greg Clayton989816b2011-05-14 01:50:35 +00001546 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1547
1548 LazyBool supported = m_gdb_comm.SupportsAllocateMemory();
1549 switch (supported)
1550 {
1551 case eLazyBoolCalculate:
1552 case eLazyBoolYes:
1553 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1554 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1555 return allocated_addr;
1556
1557 case eLazyBoolNo:
1558 // Call mmap() to create executable memory in the inferior..
1559 {
1560 Thread *thread = GetThreadList().GetSelectedThread().get();
1561 if (thread == NULL)
1562 thread = GetThreadList().GetThreadAtIndex(0).get();
1563
1564 const bool append = true;
1565 const bool include_symbols = true;
1566 SymbolContextList sc_list;
1567 const uint32_t count = m_target.GetImages().FindFunctions (ConstString ("mmap"),
1568 eFunctionNameTypeFull,
1569 include_symbols,
1570 append,
1571 sc_list);
1572 if (count > 0)
1573 {
1574 SymbolContext sc;
1575 if (sc_list.GetContextAtIndex(0, sc))
1576 {
1577 const uint32_t range_scope = eSymbolContextFunction | eSymbolContextSymbol;
1578 const bool use_inline_block_range = false;
1579 const bool stop_other_threads = true;
1580 const bool discard_on_error = true;
1581 const bool try_all_threads = true;
1582 const uint32_t single_thread_timeout_usec = 500000;
1583 addr_t arg1_addr = 0;
1584 addr_t arg2_len = size;
1585 addr_t arg3_prot = PROT_NONE;
1586 addr_t arg4_flags = MAP_ANON;
1587 addr_t arg5_fd = -1;
1588 addr_t arg6_offset = 0;
1589 if (permissions & lldb::ePermissionsReadable)
1590 arg3_prot |= PROT_READ;
1591 if (permissions & lldb::ePermissionsWritable)
1592 arg3_prot |= PROT_WRITE;
1593 if (permissions & lldb::ePermissionsExecutable)
1594 arg3_prot |= PROT_EXEC;
1595
1596 AddressRange mmap_range;
1597 if (sc.GetAddressRange(range_scope, 0, use_inline_block_range, mmap_range))
1598 {
1599 lldb::ThreadPlanSP call_plan_sp (new ThreadPlanCallFunction (*thread,
1600 mmap_range.GetBaseAddress(),
1601 stop_other_threads,
1602 discard_on_error,
1603 &arg1_addr,
1604 &arg2_len,
1605 &arg3_prot,
1606 &arg4_flags,
1607 &arg5_fd,
1608 &arg6_offset));
1609 if (call_plan_sp)
1610 {
1611 StreamFile error_strm;
1612 StackFrame *frame = thread->GetStackFrameAtIndex (0).get();
1613 if (frame)
1614 {
1615 ExecutionContext exe_ctx;
1616 frame->CalculateExecutionContext (exe_ctx);
1617 ExecutionResults results = RunThreadPlan (exe_ctx,
1618 call_plan_sp,
1619 stop_other_threads,
1620 try_all_threads,
1621 discard_on_error,
1622 single_thread_timeout_usec,
1623 error_strm);
1624 }
1625 }
1626 }
1627 }
1628 }
1629 }
1630 break;
1631 }
1632
Chris Lattner24943d22010-06-08 16:52:24 +00001633 if (allocated_addr == LLDB_INVALID_ADDRESS)
1634 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1635 else
1636 error.Clear();
1637 return allocated_addr;
1638}
1639
1640Error
1641ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1642{
1643 Error error;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001644 if (!m_gdb_comm.DeallocateMemory (addr))
Chris Lattner24943d22010-06-08 16:52:24 +00001645 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1646 return error;
1647}
1648
1649
1650//------------------------------------------------------------------
1651// Process STDIO
1652//------------------------------------------------------------------
1653
1654size_t
1655ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1656{
1657 Mutex::Locker locker(m_stdio_mutex);
1658 size_t bytes_available = m_stdout_data.size();
1659 if (bytes_available > 0)
1660 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001661 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1662 if (log)
1663 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001664 if (bytes_available > buf_size)
1665 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001666 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001667 m_stdout_data.erase(0, buf_size);
1668 bytes_available = buf_size;
1669 }
1670 else
1671 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001672 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001673 m_stdout_data.clear();
1674
1675 //ResetEventBits(eBroadcastBitSTDOUT);
1676 }
1677 }
1678 return bytes_available;
1679}
1680
1681size_t
1682ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1683{
1684 // Can we get STDERR through the remote protocol?
1685 return 0;
1686}
1687
1688size_t
1689ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1690{
1691 if (m_stdio_communication.IsConnected())
1692 {
1693 ConnectionStatus status;
1694 m_stdio_communication.Write(src, src_len, status, NULL);
1695 }
1696 return 0;
1697}
1698
1699Error
1700ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1701{
1702 Error error;
1703 assert (bp_site != NULL);
1704
Greg Claytone005f2c2010-11-06 01:53:30 +00001705 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001706 user_id_t site_id = bp_site->GetID();
1707 const addr_t addr = bp_site->GetLoadAddress();
1708 if (log)
1709 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1710
1711 if (bp_site->IsEnabled())
1712 {
1713 if (log)
1714 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1715 return error;
1716 }
1717 else
1718 {
1719 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1720
1721 if (bp_site->HardwarePreferred())
1722 {
1723 // Try and set hardware breakpoint, and if that fails, fall through
1724 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001725 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001726 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001727 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001728 {
1729 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001730 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001731 return error;
1732 }
Chris Lattner24943d22010-06-08 16:52:24 +00001733 }
1734 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001735
1736 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001737 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001738 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1739 {
1740 bp_site->SetEnabled(true);
1741 bp_site->SetType (BreakpointSite::eExternal);
1742 return error;
1743 }
Chris Lattner24943d22010-06-08 16:52:24 +00001744 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001745
1746 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001747 }
1748
1749 if (log)
1750 {
1751 const char *err_string = error.AsCString();
1752 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1753 bp_site->GetLoadAddress(),
1754 err_string ? err_string : "NULL");
1755 }
1756 // We shouldn't reach here on a successful breakpoint enable...
1757 if (error.Success())
1758 error.SetErrorToGenericError();
1759 return error;
1760}
1761
1762Error
1763ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1764{
1765 Error error;
1766 assert (bp_site != NULL);
1767 addr_t addr = bp_site->GetLoadAddress();
1768 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001769 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001770 if (log)
1771 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1772
1773 if (bp_site->IsEnabled())
1774 {
1775 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1776
Greg Claytonb72d0f02011-04-12 05:54:46 +00001777 BreakpointSite::Type bp_type = bp_site->GetType();
1778 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001779 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001780 case BreakpointSite::eSoftware:
1781 error = DisableSoftwareBreakpoint (bp_site);
1782 break;
1783
1784 case BreakpointSite::eHardware:
1785 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1786 error.SetErrorToGenericError();
1787 break;
1788
1789 case BreakpointSite::eExternal:
1790 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1791 error.SetErrorToGenericError();
1792 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001793 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001794 if (error.Success())
1795 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001796 }
1797 else
1798 {
1799 if (log)
1800 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1801 return error;
1802 }
1803
1804 if (error.Success())
1805 error.SetErrorToGenericError();
1806 return error;
1807}
1808
1809Error
1810ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1811{
1812 Error error;
1813 if (wp)
1814 {
1815 user_id_t watchID = wp->GetID();
1816 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001817 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001818 if (log)
1819 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1820 if (wp->IsEnabled())
1821 {
1822 if (log)
1823 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1824 return error;
1825 }
1826 else
1827 {
1828 // Pass down an appropriate z/Z packet...
1829 error.SetErrorString("watchpoints not supported");
1830 }
1831 }
1832 else
1833 {
1834 error.SetErrorString("Watchpoint location argument was NULL.");
1835 }
1836 if (error.Success())
1837 error.SetErrorToGenericError();
1838 return error;
1839}
1840
1841Error
1842ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1843{
1844 Error error;
1845 if (wp)
1846 {
1847 user_id_t watchID = wp->GetID();
1848
Greg Claytone005f2c2010-11-06 01:53:30 +00001849 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001850
1851 addr_t addr = wp->GetLoadAddress();
1852 if (log)
1853 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1854
1855 if (wp->IsHardware())
1856 {
1857 // Pass down an appropriate z/Z packet...
1858 error.SetErrorString("watchpoints not supported");
1859 }
1860 // TODO: clear software watchpoints if we implement them
1861 }
1862 else
1863 {
1864 error.SetErrorString("Watchpoint location argument was NULL.");
1865 }
1866 if (error.Success())
1867 error.SetErrorToGenericError();
1868 return error;
1869}
1870
1871void
1872ProcessGDBRemote::Clear()
1873{
1874 m_flags = 0;
1875 m_thread_list.Clear();
1876 {
1877 Mutex::Locker locker(m_stdio_mutex);
1878 m_stdout_data.clear();
1879 }
Chris Lattner24943d22010-06-08 16:52:24 +00001880}
1881
1882Error
1883ProcessGDBRemote::DoSignal (int signo)
1884{
1885 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001886 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001887 if (log)
1888 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1889
1890 if (!m_gdb_comm.SendAsyncSignal (signo))
1891 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1892 return error;
1893}
1894
Chris Lattner24943d22010-06-08 16:52:24 +00001895Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00001896ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner24943d22010-06-08 16:52:24 +00001897{
1898 Error error;
1899 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1900 {
1901 // If we locate debugserver, keep that located version around
1902 static FileSpec g_debugserver_file_spec;
1903
Greg Claytonb72d0f02011-04-12 05:54:46 +00001904 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00001905 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00001906 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00001907
1908 // Always check to see if we have an environment override for the path
1909 // to the debugserver to use and use it if we do.
1910 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1911 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001912 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001913 else
1914 debugserver_file_spec = g_debugserver_file_spec;
1915 bool debugserver_exists = debugserver_file_spec.Exists();
1916 if (!debugserver_exists)
1917 {
1918 // The debugserver binary is in the LLDB.framework/Resources
1919 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001920 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001921 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001922 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001923 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001924 if (debugserver_exists)
1925 {
1926 g_debugserver_file_spec = debugserver_file_spec;
1927 }
1928 else
1929 {
1930 g_debugserver_file_spec.Clear();
1931 debugserver_file_spec.Clear();
1932 }
Chris Lattner24943d22010-06-08 16:52:24 +00001933 }
1934 }
1935
1936 if (debugserver_exists)
1937 {
1938 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1939
1940 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001941
Greg Claytone005f2c2010-11-06 01:53:30 +00001942 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001943
Greg Claytonb72d0f02011-04-12 05:54:46 +00001944 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00001945 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001946
Chris Lattner24943d22010-06-08 16:52:24 +00001947 // Start args with "debugserver /file/path -r --"
1948 debugserver_args.AppendArgument(debugserver_path);
1949 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001950 // use native registers, not the GDB registers
1951 debugserver_args.AppendArgument("--native-regs");
1952 // make debugserver run in its own session so signals generated by
1953 // special terminal key sequences (^C) don't affect debugserver
1954 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001955
Chris Lattner24943d22010-06-08 16:52:24 +00001956 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1957 if (env_debugserver_log_file)
1958 {
1959 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1960 debugserver_args.AppendArgument(arg_cstr);
1961 }
1962
1963 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1964 if (env_debugserver_log_flags)
1965 {
1966 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1967 debugserver_args.AppendArgument(arg_cstr);
1968 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001969// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001970// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001971
Greg Claytonb72d0f02011-04-12 05:54:46 +00001972 // We currently send down all arguments, attach pids, or attach
1973 // process names in dedicated GDB server packets, so we don't need
1974 // to pass them as arguments. This is currently because of all the
1975 // things we need to setup prior to launching: the environment,
1976 // current working dir, file actions, etc.
1977#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00001978 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00001979 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00001980 {
Greg Claytona2f74232011-02-24 22:24:29 +00001981 // Terminate the debugserver args so we can now append the inferior args
1982 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00001983
Greg Claytona2f74232011-02-24 22:24:29 +00001984 for (int i = 0; inferior_argv[i] != NULL; ++i)
1985 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00001986 }
1987 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1988 {
1989 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1990 debugserver_args.AppendArgument (arg_cstr);
1991 }
1992 else if (attach_name && attach_name[0])
1993 {
1994 if (wait_for_launch)
1995 debugserver_args.AppendArgument ("--waitfor");
1996 else
1997 debugserver_args.AppendArgument ("--attach");
1998 debugserver_args.AppendArgument (attach_name);
1999 }
Chris Lattner24943d22010-06-08 16:52:24 +00002000#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002001
2002 ProcessLaunchInfo::FileAction file_action;
2003
2004 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2005 // to "/dev/null" if we run into any problems.
2006 file_action.Close (STDIN_FILENO);
2007 launch_info.AppendFileAction (file_action);
2008 file_action.Close (STDOUT_FILENO);
2009 launch_info.AppendFileAction (file_action);
2010 file_action.Close (STDERR_FILENO);
2011 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002012
2013 if (log)
2014 {
2015 StreamString strm;
2016 debugserver_args.Dump (&strm);
2017 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2018 }
2019
Greg Claytonb72d0f02011-04-12 05:54:46 +00002020 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002021
Greg Claytonb72d0f02011-04-12 05:54:46 +00002022 if (error.Success ())
2023 m_debugserver_pid = launch_info.GetProcessID();
2024 else
Chris Lattner24943d22010-06-08 16:52:24 +00002025 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2026
2027 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002028 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002029 }
2030 else
2031 {
2032 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2033 }
2034
2035 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2036 StartAsyncThread ();
2037 }
2038 return error;
2039}
2040
2041bool
2042ProcessGDBRemote::MonitorDebugserverProcess
2043(
2044 void *callback_baton,
2045 lldb::pid_t debugserver_pid,
2046 int signo, // Zero for no signal
2047 int exit_status // Exit value of process if signal is zero
2048)
2049{
2050 // We pass in the ProcessGDBRemote inferior process it and name it
2051 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2052 // pointer value itself, thus we need the double cast...
2053
2054 // "debugserver_pid" argument passed in is the process ID for
2055 // debugserver that we are tracking...
2056
Greg Clayton75ccf502010-08-21 02:22:51 +00002057 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002058
2059 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2060 if (log)
2061 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2062
Greg Clayton75ccf502010-08-21 02:22:51 +00002063 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002064 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002065 // Sleep for a half a second to make sure our inferior process has
2066 // time to set its exit status before we set it incorrectly when
2067 // both the debugserver and the inferior process shut down.
2068 usleep (500000);
2069 // If our process hasn't yet exited, debugserver might have died.
2070 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002071 const StateType state = process->GetState();
2072
2073 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2074 state != eStateInvalid &&
2075 state != eStateUnloaded &&
2076 state != eStateExited &&
2077 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002078 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002079 char error_str[1024];
2080 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002081 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002082 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2083 if (signal_cstr)
2084 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002085 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002086 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002087 }
2088 else
2089 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002090 ::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 +00002091 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002092
2093 process->SetExitStatus (-1, error_str);
2094 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002095 // Debugserver has exited we need to let our ProcessGDBRemote
2096 // know that it no longer has a debugserver instance
2097 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2098 // We are returning true to this function below, so we can
2099 // forget about the monitor handle.
2100 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002101 }
2102 return true;
2103}
2104
2105void
2106ProcessGDBRemote::KillDebugserverProcess ()
2107{
2108 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2109 {
2110 ::kill (m_debugserver_pid, SIGINT);
2111 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2112 }
2113}
2114
2115void
2116ProcessGDBRemote::Initialize()
2117{
2118 static bool g_initialized = false;
2119
2120 if (g_initialized == false)
2121 {
2122 g_initialized = true;
2123 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2124 GetPluginDescriptionStatic(),
2125 CreateInstance);
2126
2127 Log::Callbacks log_callbacks = {
2128 ProcessGDBRemoteLog::DisableLog,
2129 ProcessGDBRemoteLog::EnableLog,
2130 ProcessGDBRemoteLog::ListLogCategories
2131 };
2132
2133 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2134 }
2135}
2136
2137bool
Chris Lattner24943d22010-06-08 16:52:24 +00002138ProcessGDBRemote::StartAsyncThread ()
2139{
Greg Claytone005f2c2010-11-06 01:53:30 +00002140 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002141
2142 if (log)
2143 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2144
2145 // Create a thread that watches our internal state and controls which
2146 // events make it to clients (into the DCProcess event queue).
2147 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002148 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002149}
2150
2151void
2152ProcessGDBRemote::StopAsyncThread ()
2153{
Greg Claytone005f2c2010-11-06 01:53:30 +00002154 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002155
2156 if (log)
2157 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2158
2159 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2160
2161 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002162 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002163 {
2164 Host::ThreadJoin (m_async_thread, NULL, NULL);
2165 }
2166}
2167
2168
2169void *
2170ProcessGDBRemote::AsyncThread (void *arg)
2171{
2172 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2173
Greg Claytone005f2c2010-11-06 01:53:30 +00002174 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002175 if (log)
2176 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2177
2178 Listener listener ("ProcessGDBRemote::AsyncThread");
2179 EventSP event_sp;
2180 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2181 eBroadcastBitAsyncThreadShouldExit;
2182
2183 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2184 {
Greg Claytona2f74232011-02-24 22:24:29 +00002185 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2186
Chris Lattner24943d22010-06-08 16:52:24 +00002187 bool done = false;
2188 while (!done)
2189 {
2190 if (log)
2191 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2192 if (listener.WaitForEvent (NULL, event_sp))
2193 {
2194 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002195 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002196 {
Greg Claytona2f74232011-02-24 22:24:29 +00002197 if (log)
2198 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 +00002199
Greg Claytona2f74232011-02-24 22:24:29 +00002200 switch (event_type)
2201 {
2202 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002203 {
Greg Claytona2f74232011-02-24 22:24:29 +00002204 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002205
Greg Claytona2f74232011-02-24 22:24:29 +00002206 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002207 {
Greg Claytona2f74232011-02-24 22:24:29 +00002208 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2209 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2210 if (log)
2211 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002212
Greg Claytona2f74232011-02-24 22:24:29 +00002213 if (::strstr (continue_cstr, "vAttach") == NULL)
2214 process->SetPrivateState(eStateRunning);
2215 StringExtractorGDBRemote response;
2216 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002217
Greg Claytona2f74232011-02-24 22:24:29 +00002218 switch (stop_state)
2219 {
2220 case eStateStopped:
2221 case eStateCrashed:
2222 case eStateSuspended:
2223 process->m_last_stop_packet = response;
2224 process->m_last_stop_packet.SetFilePos (0);
2225 process->SetPrivateState (stop_state);
2226 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002227
Greg Claytona2f74232011-02-24 22:24:29 +00002228 case eStateExited:
2229 process->m_last_stop_packet = response;
2230 process->m_last_stop_packet.SetFilePos (0);
2231 response.SetFilePos(1);
2232 process->SetExitStatus(response.GetHexU8(), NULL);
2233 done = true;
2234 break;
2235
2236 case eStateInvalid:
2237 process->SetExitStatus(-1, "lost connection");
2238 break;
2239
2240 default:
2241 process->SetPrivateState (stop_state);
2242 break;
2243 }
Chris Lattner24943d22010-06-08 16:52:24 +00002244 }
2245 }
Greg Claytona2f74232011-02-24 22:24:29 +00002246 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002247
Greg Claytona2f74232011-02-24 22:24:29 +00002248 case eBroadcastBitAsyncThreadShouldExit:
2249 if (log)
2250 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2251 done = true;
2252 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002253
Greg Claytona2f74232011-02-24 22:24:29 +00002254 default:
2255 if (log)
2256 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2257 done = true;
2258 break;
2259 }
2260 }
2261 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2262 {
2263 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2264 {
2265 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002266 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002267 }
Chris Lattner24943d22010-06-08 16:52:24 +00002268 }
2269 }
2270 else
2271 {
2272 if (log)
2273 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2274 done = true;
2275 }
2276 }
2277 }
2278
2279 if (log)
2280 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2281
2282 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2283 return NULL;
2284}
2285
Chris Lattner24943d22010-06-08 16:52:24 +00002286const char *
2287ProcessGDBRemote::GetDispatchQueueNameForThread
2288(
2289 addr_t thread_dispatch_qaddr,
2290 std::string &dispatch_queue_name
2291)
2292{
2293 dispatch_queue_name.clear();
2294 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2295 {
2296 // Cache the dispatch_queue_offsets_addr value so we don't always have
2297 // to look it up
2298 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2299 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002300 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2301 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002302 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002303 if (module_sp)
2304 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2305
2306 if (dispatch_queue_offsets_symbol == NULL)
2307 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002308 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002309 if (module_sp)
2310 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2311 }
Chris Lattner24943d22010-06-08 16:52:24 +00002312 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002313 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002314
2315 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2316 return NULL;
2317 }
2318
2319 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002320 DataExtractor data (memory_buffer,
2321 sizeof(memory_buffer),
2322 m_target.GetArchitecture().GetByteOrder(),
2323 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002324
2325 // Excerpt from src/queue_private.h
2326 struct dispatch_queue_offsets_s
2327 {
2328 uint16_t dqo_version;
2329 uint16_t dqo_label;
2330 uint16_t dqo_label_size;
2331 } dispatch_queue_offsets;
2332
2333
2334 Error error;
2335 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2336 {
2337 uint32_t data_offset = 0;
2338 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2339 {
2340 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2341 {
2342 data_offset = 0;
2343 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2344 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2345 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2346 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2347 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2348 dispatch_queue_name.erase (bytes_read);
2349 }
2350 }
2351 }
2352 }
2353 if (dispatch_queue_name.empty())
2354 return NULL;
2355 return dispatch_queue_name.c_str();
2356}
2357
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002358//uint32_t
2359//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2360//{
2361// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2362// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2363// if (m_local_debugserver)
2364// {
2365// return Host::ListProcessesMatchingName (name, matches, pids);
2366// }
2367// else
2368// {
2369// // FIXME: Implement talking to the remote debugserver.
2370// return 0;
2371// }
2372//
2373//}
2374//
Jim Ingham55e01d82011-01-22 01:33:44 +00002375bool
2376ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2377 lldb_private::StoppointCallbackContext *context,
2378 lldb::user_id_t break_id,
2379 lldb::user_id_t break_loc_id)
2380{
2381 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2382 // run so I can stop it if that's what I want to do.
2383 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2384 if (log)
2385 log->Printf("Hit New Thread Notification breakpoint.");
2386 return false;
2387}
2388
2389
2390bool
2391ProcessGDBRemote::StartNoticingNewThreads()
2392{
2393 static const char *bp_names[] =
2394 {
2395 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002396 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002397 "_pthread_start",
2398 NULL
2399 };
2400
2401 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2402 size_t num_bps = m_thread_observation_bps.size();
2403 if (num_bps != 0)
2404 {
2405 for (int i = 0; i < num_bps; i++)
2406 {
2407 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2408 if (break_sp)
2409 {
2410 if (log)
2411 log->Printf("Enabled noticing new thread breakpoint.");
2412 break_sp->SetEnabled(true);
2413 }
2414 }
2415 }
2416 else
2417 {
2418 for (int i = 0; bp_names[i] != NULL; i++)
2419 {
2420 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2421 if (breakpoint)
2422 {
2423 if (log)
2424 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2425 m_thread_observation_bps.push_back(breakpoint->GetID());
2426 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2427 }
2428 else
2429 {
2430 if (log)
2431 log->Printf("Failed to create new thread notification breakpoint.");
2432 return false;
2433 }
2434 }
2435 }
2436
2437 return true;
2438}
2439
2440bool
2441ProcessGDBRemote::StopNoticingNewThreads()
2442{
Jim Inghamff276fe2011-02-08 05:19:01 +00002443 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2444 if (log)
2445 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002446 size_t num_bps = m_thread_observation_bps.size();
2447 if (num_bps != 0)
2448 {
2449 for (int i = 0; i < num_bps; i++)
2450 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002451
2452 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2453 if (break_sp)
2454 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002455 break_sp->SetEnabled(false);
2456 }
2457 }
2458 }
2459 return true;
2460}
2461
2462