blob: 172a1cf0f774b860d2af586aff4890414da9d5ce [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"
Greg Clayton2f085c62011-05-15 01:25:55 +000037#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Host/TimeValue.h"
39#include "lldb/Symbol/ObjectFile.h"
40#include "lldb/Target/DynamicLoader.h"
41#include "lldb/Target/Target.h"
42#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000043#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000044#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045
46// Project includes
47#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000048#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "GDBRemoteRegisterContext.h"
50#include "ProcessGDBRemote.h"
51#include "ProcessGDBRemoteLog.h"
52#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000053#include "StopInfoMachException.h"
54
Chris Lattner24943d22010-06-08 16:52:24 +000055
Chris Lattner24943d22010-06-08 16:52:24 +000056
57#define DEBUGSERVER_BASENAME "debugserver"
58using namespace lldb;
59using namespace lldb_private;
60
Jim Inghamf9600482011-03-29 21:45:47 +000061static bool rand_initialized = false;
62
Chris Lattner24943d22010-06-08 16:52:24 +000063static inline uint16_t
64get_random_port ()
65{
Jim Inghamf9600482011-03-29 21:45:47 +000066 if (!rand_initialized)
67 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000068 time_t seed = time(NULL);
69
Jim Inghamf9600482011-03-29 21:45:47 +000070 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000071 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000072 }
Stephen Wilson50daf772011-03-25 18:16:28 +000073 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000074}
75
76
77const char *
78ProcessGDBRemote::GetPluginNameStatic()
79{
Greg Claytonb1888f22011-03-19 01:12:21 +000080 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000081}
82
83const char *
84ProcessGDBRemote::GetPluginDescriptionStatic()
85{
86 return "GDB Remote protocol based debugging plug-in.";
87}
88
89void
90ProcessGDBRemote::Terminate()
91{
92 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
93}
94
95
96Process*
97ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
98{
99 return new ProcessGDBRemote (target, listener);
100}
101
102bool
103ProcessGDBRemote::CanDebug(Target &target)
104{
105 // For now we are just making sure the file exists for a given module
106 ModuleSP exe_module_sp(target.GetExecutableModule());
107 if (exe_module_sp.get())
108 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000109 // However, if there is no executable module, we return true since we might be preparing to attach.
110 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000111}
112
113//----------------------------------------------------------------------
114// ProcessGDBRemote constructor
115//----------------------------------------------------------------------
116ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
117 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000118 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000119 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000120 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000121 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000122 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000123 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000124 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000125 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
126 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000127 m_continue_c_tids (),
128 m_continue_C_tids (),
129 m_continue_s_tids (),
130 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000131 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000132 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000133 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000134 m_local_debugserver (true),
135 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000136{
Greg Claytonff39f742011-04-01 00:29:43 +0000137 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
138 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000139}
140
141//----------------------------------------------------------------------
142// Destructor
143//----------------------------------------------------------------------
144ProcessGDBRemote::~ProcessGDBRemote()
145{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000146 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000147 {
148 Host::ThreadCancel (m_debugserver_thread, NULL);
149 thread_result_t thread_result;
150 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
151 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
152 }
Chris Lattner24943d22010-06-08 16:52:24 +0000153 // m_mach_process.UnregisterNotificationCallbacks (this);
154 Clear();
155}
156
157//----------------------------------------------------------------------
158// PluginInterface
159//----------------------------------------------------------------------
160const char *
161ProcessGDBRemote::GetPluginName()
162{
163 return "Process debugging plug-in that uses the GDB remote protocol";
164}
165
166const char *
167ProcessGDBRemote::GetShortPluginName()
168{
169 return GetPluginNameStatic();
170}
171
172uint32_t
173ProcessGDBRemote::GetPluginVersion()
174{
175 return 1;
176}
177
178void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000179ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000180{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000181 if (!force && m_register_info.GetNumRegisters() > 0)
182 return;
183
184 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000185 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000186 uint32_t reg_offset = 0;
187 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000188 StringExtractorGDBRemote::ResponseType response_type;
189 for (response_type = StringExtractorGDBRemote::eResponse;
190 response_type == StringExtractorGDBRemote::eResponse;
191 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000192 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000193 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
194 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000195 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000196 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000197 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000198 response_type = response.GetResponseType();
199 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000200 {
201 std::string name;
202 std::string value;
203 ConstString reg_name;
204 ConstString alt_name;
205 ConstString set_name;
206 RegisterInfo reg_info = { NULL, // Name
207 NULL, // Alt name
208 0, // byte size
209 reg_offset, // offset
210 eEncodingUint, // encoding
211 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000212 {
213 LLDB_INVALID_REGNUM, // GCC reg num
214 LLDB_INVALID_REGNUM, // DWARF reg num
215 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000216 reg_num, // GDB reg num
217 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000218 }
219 };
220
221 while (response.GetNameColonValue(name, value))
222 {
223 if (name.compare("name") == 0)
224 {
225 reg_name.SetCString(value.c_str());
226 }
227 else if (name.compare("alt-name") == 0)
228 {
229 alt_name.SetCString(value.c_str());
230 }
231 else if (name.compare("bitsize") == 0)
232 {
233 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
234 }
235 else if (name.compare("offset") == 0)
236 {
237 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000238 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000239 {
240 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000241 }
242 }
243 else if (name.compare("encoding") == 0)
244 {
245 if (value.compare("uint") == 0)
246 reg_info.encoding = eEncodingUint;
247 else if (value.compare("sint") == 0)
248 reg_info.encoding = eEncodingSint;
249 else if (value.compare("ieee754") == 0)
250 reg_info.encoding = eEncodingIEEE754;
251 else if (value.compare("vector") == 0)
252 reg_info.encoding = eEncodingVector;
253 }
254 else if (name.compare("format") == 0)
255 {
256 if (value.compare("binary") == 0)
257 reg_info.format = eFormatBinary;
258 else if (value.compare("decimal") == 0)
259 reg_info.format = eFormatDecimal;
260 else if (value.compare("hex") == 0)
261 reg_info.format = eFormatHex;
262 else if (value.compare("float") == 0)
263 reg_info.format = eFormatFloat;
264 else if (value.compare("vector-sint8") == 0)
265 reg_info.format = eFormatVectorOfSInt8;
266 else if (value.compare("vector-uint8") == 0)
267 reg_info.format = eFormatVectorOfUInt8;
268 else if (value.compare("vector-sint16") == 0)
269 reg_info.format = eFormatVectorOfSInt16;
270 else if (value.compare("vector-uint16") == 0)
271 reg_info.format = eFormatVectorOfUInt16;
272 else if (value.compare("vector-sint32") == 0)
273 reg_info.format = eFormatVectorOfSInt32;
274 else if (value.compare("vector-uint32") == 0)
275 reg_info.format = eFormatVectorOfUInt32;
276 else if (value.compare("vector-float32") == 0)
277 reg_info.format = eFormatVectorOfFloat32;
278 else if (value.compare("vector-uint128") == 0)
279 reg_info.format = eFormatVectorOfUInt128;
280 }
281 else if (name.compare("set") == 0)
282 {
283 set_name.SetCString(value.c_str());
284 }
285 else if (name.compare("gcc") == 0)
286 {
287 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
288 }
289 else if (name.compare("dwarf") == 0)
290 {
291 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
292 }
293 else if (name.compare("generic") == 0)
294 {
295 if (value.compare("pc") == 0)
296 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
297 else if (value.compare("sp") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
299 else if (value.compare("fp") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
301 else if (value.compare("ra") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
303 else if (value.compare("flags") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
305 }
306 }
307
Jason Molenda53d96862010-06-11 23:44:18 +0000308 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000309 assert (reg_info.byte_size != 0);
310 reg_offset += reg_info.byte_size;
311 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
312 }
313 }
314 else
315 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000316 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000317 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000318 }
319 }
320
321 if (reg_num == 0)
322 {
323 // We didn't get anything. See if we are debugging ARM and fill with
324 // a hard coded register set until we can get an updated debugserver
325 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000326 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000327 m_register_info.HardcodeARMRegisters();
328 }
329 m_register_info.Finalize ();
330}
331
332Error
333ProcessGDBRemote::WillLaunch (Module* module)
334{
335 return WillLaunchOrAttach ();
336}
337
338Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000339ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000340{
341 return WillLaunchOrAttach ();
342}
343
344Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000345ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000346{
347 return WillLaunchOrAttach ();
348}
349
350Error
Greg Claytone71e2582011-02-04 01:58:07 +0000351ProcessGDBRemote::DoConnectRemote (const char *remote_url)
352{
353 Error error (WillLaunchOrAttach ());
354
355 if (error.Fail())
356 return error;
357
Greg Clayton180546b2011-04-30 01:09:13 +0000358 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000359
360 if (error.Fail())
361 return error;
362 StartAsyncThread ();
363
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000364 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000365 if (pid == LLDB_INVALID_PROCESS_ID)
366 {
367 // We don't have a valid process ID, so note that we are connected
368 // and could now request to launch or attach, or get remote process
369 // listings...
370 SetPrivateState (eStateConnected);
371 }
372 else
373 {
374 // We have a valid process
375 SetID (pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000376 UpdateThreadListIfNeeded ();
Greg Claytone71e2582011-02-04 01:58:07 +0000377 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000378 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000379 {
380 const StateType state = SetThreadStopInfo (response);
381 if (state == eStateStopped)
382 {
383 SetPrivateState (state);
384 }
385 else
386 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
387 }
388 else
389 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
390 }
391 return error;
392}
393
394Error
Chris Lattner24943d22010-06-08 16:52:24 +0000395ProcessGDBRemote::WillLaunchOrAttach ()
396{
397 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000398 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000399 return error;
400}
401
402//----------------------------------------------------------------------
403// Process Control
404//----------------------------------------------------------------------
405Error
406ProcessGDBRemote::DoLaunch
407(
408 Module* module,
409 char const *argv[],
410 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000411 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000412 const char *stdin_path,
413 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000414 const char *stderr_path,
415 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000416)
417{
Greg Clayton4b407112010-09-30 21:49:03 +0000418 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000419 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
420 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
421 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000422
423 ObjectFile * object_file = module->GetObjectFile();
424 if (object_file)
425 {
Chris Lattner24943d22010-06-08 16:52:24 +0000426 char host_port[128];
427 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000428 char connect_url[128];
429 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000430
Greg Claytona2f74232011-02-24 22:24:29 +0000431 // Make sure we aren't already connected?
432 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000433 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000434 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000435 if (error.Fail())
436 return error;
437
Greg Claytone71e2582011-02-04 01:58:07 +0000438 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000439 }
440
441 if (error.Success())
442 {
443 lldb_utility::PseudoTerminal pty;
444 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000445
446 // If the debugserver is local and we aren't disabling STDIO, lets use
447 // a pseudo terminal to instead of relying on the 'O' packets for stdio
448 // since 'O' packets can really slow down debugging if the inferior
449 // does a lot of output.
450 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000451 {
452 const char *slave_name = NULL;
453 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000454 {
Greg Claytona2f74232011-02-24 22:24:29 +0000455 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
456 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000457 }
Greg Claytona2f74232011-02-24 22:24:29 +0000458 if (stdin_path == NULL)
459 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000460
Greg Claytona2f74232011-02-24 22:24:29 +0000461 if (stdout_path == NULL)
462 stdout_path = slave_name;
463
464 if (stderr_path == NULL)
465 stderr_path = slave_name;
466 }
467
Greg Claytonafb81862011-03-02 21:34:46 +0000468 // Set STDIN to /dev/null if we want STDIO disabled or if either
469 // STDOUT or STDERR have been set to something and STDIN hasn't
470 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000471 stdin_path = "/dev/null";
472
Greg Claytonafb81862011-03-02 21:34:46 +0000473 // Set STDOUT to /dev/null if we want STDIO disabled or if either
474 // STDIN or STDERR have been set to something and STDOUT hasn't
475 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000476 stdout_path = "/dev/null";
477
Greg Claytonafb81862011-03-02 21:34:46 +0000478 // Set STDERR to /dev/null if we want STDIO disabled or if either
479 // STDIN or STDOUT have been set to something and STDERR hasn't
480 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000481 stderr_path = "/dev/null";
482
483 if (stdin_path)
484 m_gdb_comm.SetSTDIN (stdin_path);
485 if (stdout_path)
486 m_gdb_comm.SetSTDOUT (stdout_path);
487 if (stderr_path)
488 m_gdb_comm.SetSTDERR (stderr_path);
489
490 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
491
Greg Claytona4582402011-05-08 04:53:50 +0000492 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000493
494 if (working_dir && working_dir[0])
495 {
496 m_gdb_comm.SetWorkingDir (working_dir);
497 }
498
499 // Send the environment and the program + arguments after we connect
500 if (envp)
501 {
502 const char *env_entry;
503 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000504 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000505 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000506 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000507 }
Greg Claytona2f74232011-02-24 22:24:29 +0000508 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000509
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000510 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
511 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
512 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000513 if (arg_packet_err == 0)
514 {
515 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000516 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000517 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000518 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000519 }
520 else
521 {
Greg Claytona2f74232011-02-24 22:24:29 +0000522 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000523 }
Greg Claytona2f74232011-02-24 22:24:29 +0000524 }
525 else
526 {
527 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
528 }
Chris Lattner24943d22010-06-08 16:52:24 +0000529
Greg Claytona2f74232011-02-24 22:24:29 +0000530 if (GetID() == LLDB_INVALID_PROCESS_ID)
531 {
532 KillDebugserverProcess ();
533 return error;
534 }
535
536 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000537 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000538 {
539 SetPrivateState (SetThreadStopInfo (response));
540
541 if (!disable_stdio)
542 {
543 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
544 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
545 }
Chris Lattner24943d22010-06-08 16:52:24 +0000546 }
547 }
Chris Lattner24943d22010-06-08 16:52:24 +0000548 }
549 else
550 {
551 // Set our user ID to an invalid process ID.
552 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000553 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
554 module->GetFileSpec().GetFilename().AsCString(),
555 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000556 }
Chris Lattner24943d22010-06-08 16:52:24 +0000557 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000558
Chris Lattner24943d22010-06-08 16:52:24 +0000559}
560
561
562Error
Greg Claytone71e2582011-02-04 01:58:07 +0000563ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000564{
565 Error error;
566 // Sleep and wait a bit for debugserver to start to listen...
567 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
568 if (conn_ap.get())
569 {
Chris Lattner24943d22010-06-08 16:52:24 +0000570 const uint32_t max_retry_count = 50;
571 uint32_t retry_count = 0;
572 while (!m_gdb_comm.IsConnected())
573 {
Greg Claytone71e2582011-02-04 01:58:07 +0000574 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000575 {
576 m_gdb_comm.SetConnection (conn_ap.release());
577 break;
578 }
579 retry_count++;
580
581 if (retry_count >= max_retry_count)
582 break;
583
584 usleep (100000);
585 }
586 }
587
588 if (!m_gdb_comm.IsConnected())
589 {
590 if (error.Success())
591 error.SetErrorString("not connected to remote gdb server");
592 return error;
593 }
594
Greg Clayton24bc5d92011-03-30 18:16:51 +0000595 // We always seem to be able to open a connection to a local port
596 // so we need to make sure we can then send data to it. If we can't
597 // then we aren't actually connected to anything, so try and do the
598 // handshake with the remote GDB server and make sure that goes
599 // alright.
600 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000601 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000602 m_gdb_comm.Disconnect();
603 if (error.Success())
604 error.SetErrorString("not connected to remote gdb server");
605 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000606 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000607 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
608 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
609 this,
610 m_debugserver_pid,
611 false);
612 m_gdb_comm.ResetDiscoverableSettings();
613 m_gdb_comm.QueryNoAckModeSupported ();
614 m_gdb_comm.GetThreadSuffixSupported ();
615 m_gdb_comm.GetHostInfo ();
616 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000617 return error;
618}
619
620void
621ProcessGDBRemote::DidLaunchOrAttach ()
622{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000623 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
624 if (log)
625 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000626 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000627 {
628 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
629
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000630 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000631
Chris Lattner24943d22010-06-08 16:52:24 +0000632 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000633
Greg Claytoncb8977d2011-03-23 00:09:55 +0000634 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
635 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000636 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000637 ArchSpec &target_arch = GetTarget().GetArchitecture();
638
639 if (target_arch.IsValid())
640 {
641 // If the remote host is ARM and we have apple as the vendor, then
642 // ARM executables and shared libraries can have mixed ARM architectures.
643 // You can have an armv6 executable, and if the host is armv7, then the
644 // system will load the best possible architecture for all shared libraries
645 // it has, so we really need to take the remote host architecture as our
646 // defacto architecture in this case.
647
648 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
649 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
650 {
651 target_arch = gdb_remote_arch;
652 }
653 else
654 {
655 // Fill in what is missing in the triple
656 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
657 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000658 if (target_triple.getVendorName().size() == 0)
659 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000660 target_triple.setVendor (remote_triple.getVendor());
661
Greg Clayton2f085c62011-05-15 01:25:55 +0000662 if (target_triple.getOSName().size() == 0)
663 {
664 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000665
Greg Clayton2f085c62011-05-15 01:25:55 +0000666 if (target_triple.getEnvironmentName().size() == 0)
667 target_triple.setEnvironment (remote_triple.getEnvironment());
668 }
669 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000670 }
671 }
672 else
673 {
674 // The target doesn't have a valid architecture yet, set it from
675 // the architecture we got from the remote GDB server
676 target_arch = gdb_remote_arch;
677 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000678 }
Chris Lattner24943d22010-06-08 16:52:24 +0000679 }
680}
681
682void
683ProcessGDBRemote::DidLaunch ()
684{
685 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000686}
687
688Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000689ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000690{
691 Error error;
692 // Clear out and clean up from any current state
693 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000694 if (attach_pid != LLDB_INVALID_PROCESS_ID)
695 {
Greg Claytona2f74232011-02-24 22:24:29 +0000696 // Make sure we aren't already connected?
697 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000698 {
Greg Claytona2f74232011-02-24 22:24:29 +0000699 char host_port[128];
700 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
701 char connect_url[128];
702 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000703
Greg Claytonb72d0f02011-04-12 05:54:46 +0000704 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000705
706 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000707 {
Greg Claytona2f74232011-02-24 22:24:29 +0000708 const char *error_string = error.AsCString();
709 if (error_string == NULL)
710 error_string = "unable to launch " DEBUGSERVER_BASENAME;
711
712 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000713 }
Greg Claytona2f74232011-02-24 22:24:29 +0000714 else
715 {
716 error = ConnectToDebugserver (connect_url);
717 }
718 }
719
720 if (error.Success())
721 {
722 char packet[64];
723 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
724
725 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000726 }
727 }
Chris Lattner24943d22010-06-08 16:52:24 +0000728 return error;
729}
730
731size_t
732ProcessGDBRemote::AttachInputReaderCallback
733(
734 void *baton,
735 InputReader *reader,
736 lldb::InputReaderAction notification,
737 const char *bytes,
738 size_t bytes_len
739)
740{
741 if (notification == eInputReaderGotToken)
742 {
743 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
744 if (gdb_process->m_waiting_for_attach)
745 gdb_process->m_waiting_for_attach = false;
746 reader->SetIsDone(true);
747 return 1;
748 }
749 return 0;
750}
751
752Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000753ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000754{
755 Error error;
756 // Clear out and clean up from any current state
757 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000758
Chris Lattner24943d22010-06-08 16:52:24 +0000759 if (process_name && process_name[0])
760 {
Greg Claytona2f74232011-02-24 22:24:29 +0000761 // Make sure we aren't already connected?
762 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000763 {
Greg Claytona2f74232011-02-24 22:24:29 +0000764 char host_port[128];
765 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
766 char connect_url[128];
767 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
768
Greg Claytonb72d0f02011-04-12 05:54:46 +0000769 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000770 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000771 {
Greg Claytona2f74232011-02-24 22:24:29 +0000772 const char *error_string = error.AsCString();
773 if (error_string == NULL)
774 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000775
Greg Claytona2f74232011-02-24 22:24:29 +0000776 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000777 }
Greg Claytona2f74232011-02-24 22:24:29 +0000778 else
779 {
780 error = ConnectToDebugserver (connect_url);
781 }
782 }
783
784 if (error.Success())
785 {
786 StreamString packet;
787
788 if (wait_for_launch)
789 packet.PutCString("vAttachWait");
790 else
791 packet.PutCString("vAttachName");
792 packet.PutChar(';');
793 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
794
795 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
796
Chris Lattner24943d22010-06-08 16:52:24 +0000797 }
798 }
Chris Lattner24943d22010-06-08 16:52:24 +0000799 return error;
800}
801
Chris Lattner24943d22010-06-08 16:52:24 +0000802
803void
804ProcessGDBRemote::DidAttach ()
805{
Greg Claytone71e2582011-02-04 01:58:07 +0000806 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000807}
808
809Error
810ProcessGDBRemote::WillResume ()
811{
Greg Claytonc1f45872011-02-12 06:28:37 +0000812 m_continue_c_tids.clear();
813 m_continue_C_tids.clear();
814 m_continue_s_tids.clear();
815 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000816 return Error();
817}
818
819Error
820ProcessGDBRemote::DoResume ()
821{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000822 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000823 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
824 if (log)
825 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000826
827 Listener listener ("gdb-remote.resume-packet-sent");
828 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
829 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000830 StreamString continue_packet;
831 bool continue_packet_error = false;
832 if (m_gdb_comm.HasAnyVContSupport ())
833 {
834 continue_packet.PutCString ("vCont");
835
836 if (!m_continue_c_tids.empty())
837 {
838 if (m_gdb_comm.GetVContSupported ('c'))
839 {
840 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)
841 continue_packet.Printf(";c:%4.4x", *t_pos);
842 }
843 else
844 continue_packet_error = true;
845 }
846
847 if (!continue_packet_error && !m_continue_C_tids.empty())
848 {
849 if (m_gdb_comm.GetVContSupported ('C'))
850 {
851 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)
852 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
853 }
854 else
855 continue_packet_error = true;
856 }
Greg Claytonb749a262010-12-03 06:02:24 +0000857
Greg Claytonc1f45872011-02-12 06:28:37 +0000858 if (!continue_packet_error && !m_continue_s_tids.empty())
859 {
860 if (m_gdb_comm.GetVContSupported ('s'))
861 {
862 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)
863 continue_packet.Printf(";s:%4.4x", *t_pos);
864 }
865 else
866 continue_packet_error = true;
867 }
868
869 if (!continue_packet_error && !m_continue_S_tids.empty())
870 {
871 if (m_gdb_comm.GetVContSupported ('S'))
872 {
873 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)
874 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
875 }
876 else
877 continue_packet_error = true;
878 }
879
880 if (continue_packet_error)
881 continue_packet.GetString().clear();
882 }
883 else
884 continue_packet_error = true;
885
886 if (continue_packet_error)
887 {
888 continue_packet_error = false;
889 // Either no vCont support, or we tried to use part of the vCont
890 // packet that wasn't supported by the remote GDB server.
891 // We need to try and make a simple packet that can do our continue
892 const size_t num_threads = GetThreadList().GetSize();
893 const size_t num_continue_c_tids = m_continue_c_tids.size();
894 const size_t num_continue_C_tids = m_continue_C_tids.size();
895 const size_t num_continue_s_tids = m_continue_s_tids.size();
896 const size_t num_continue_S_tids = m_continue_S_tids.size();
897 if (num_continue_c_tids > 0)
898 {
899 if (num_continue_c_tids == num_threads)
900 {
901 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000902 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000903 continue_packet.PutChar ('c');
904 }
905 else if (num_continue_c_tids == 1 &&
906 num_continue_C_tids == 0 &&
907 num_continue_s_tids == 0 &&
908 num_continue_S_tids == 0 )
909 {
910 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000911 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000912 continue_packet.PutChar ('c');
913 }
914 else
915 {
916 // We can't represent this continue packet....
917 continue_packet_error = true;
918 }
919 }
920
921 if (!continue_packet_error && num_continue_C_tids > 0)
922 {
923 if (num_continue_C_tids == num_threads)
924 {
925 const int continue_signo = m_continue_C_tids.front().second;
926 if (num_continue_C_tids > 1)
927 {
928 for (size_t i=1; i<num_threads; ++i)
929 {
930 if (m_continue_C_tids[i].second != continue_signo)
931 continue_packet_error = true;
932 }
933 }
934 if (!continue_packet_error)
935 {
936 // Add threads continuing with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000937 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000938 continue_packet.Printf("C%2.2x", continue_signo);
939 }
940 }
941 else if (num_continue_c_tids == 0 &&
942 num_continue_C_tids == 1 &&
943 num_continue_s_tids == 0 &&
944 num_continue_S_tids == 0 )
945 {
946 // Only one thread is continuing with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +0000947 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000948 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
949 }
950 else
951 {
952 // We can't represent this continue packet....
953 continue_packet_error = true;
954 }
955 }
956
957 if (!continue_packet_error && num_continue_s_tids > 0)
958 {
959 if (num_continue_s_tids == num_threads)
960 {
961 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000962 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000963 continue_packet.PutChar ('s');
964 }
965 else if (num_continue_c_tids == 0 &&
966 num_continue_C_tids == 0 &&
967 num_continue_s_tids == 1 &&
968 num_continue_S_tids == 0 )
969 {
970 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +0000971 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000972 continue_packet.PutChar ('s');
973 }
974 else
975 {
976 // We can't represent this continue packet....
977 continue_packet_error = true;
978 }
979 }
980
981 if (!continue_packet_error && num_continue_S_tids > 0)
982 {
983 if (num_continue_S_tids == num_threads)
984 {
985 const int step_signo = m_continue_S_tids.front().second;
986 // Are all threads trying to step with the same signal?
987 if (num_continue_S_tids > 1)
988 {
989 for (size_t i=1; i<num_threads; ++i)
990 {
991 if (m_continue_S_tids[i].second != step_signo)
992 continue_packet_error = true;
993 }
994 }
995 if (!continue_packet_error)
996 {
997 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000998 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000999 continue_packet.Printf("S%2.2x", step_signo);
1000 }
1001 }
1002 else if (num_continue_c_tids == 0 &&
1003 num_continue_C_tids == 0 &&
1004 num_continue_s_tids == 0 &&
1005 num_continue_S_tids == 1 )
1006 {
1007 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001008 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001009 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1010 }
1011 else
1012 {
1013 // We can't represent this continue packet....
1014 continue_packet_error = true;
1015 }
1016 }
1017 }
1018
1019 if (continue_packet_error)
1020 {
1021 error.SetErrorString ("can't make continue packet for this resume");
1022 }
1023 else
1024 {
1025 EventSP event_sp;
1026 TimeValue timeout;
1027 timeout = TimeValue::Now();
1028 timeout.OffsetWithSeconds (5);
1029 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1030
1031 if (listener.WaitForEvent (&timeout, event_sp) == false)
1032 error.SetErrorString("Resume timed out.");
1033 }
Greg Claytonb749a262010-12-03 06:02:24 +00001034 }
1035
Jim Ingham3ae449a2010-11-17 02:32:00 +00001036 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001037}
1038
Chris Lattner24943d22010-06-08 16:52:24 +00001039uint32_t
1040ProcessGDBRemote::UpdateThreadListIfNeeded ()
1041{
1042 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001043 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001044 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001045 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1046
Greg Clayton5205f0b2010-09-03 17:10:42 +00001047 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001048 const uint32_t stop_id = GetStopID();
1049 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1050 {
1051 // Update the thread list's stop id immediately so we don't recurse into this function.
1052 ThreadList curr_thread_list (this);
1053 curr_thread_list.SetStopID(stop_id);
1054
1055 Error err;
1056 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001057 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, false);
Greg Clayton61d043b2011-03-22 04:00:09 +00001058 response.IsNormalResponse();
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001059 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001060 {
1061 char ch = response.GetChar();
1062 if (ch == 'l')
1063 break;
1064 if (ch == 'm')
1065 {
1066 do
1067 {
1068 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1069
1070 if (tid != LLDB_INVALID_THREAD_ID)
1071 {
1072 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001073 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001074 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1075 curr_thread_list.AddThread(thread_sp);
1076 }
1077
1078 ch = response.GetChar();
1079 } while (ch == ',');
1080 }
1081 }
1082
1083 m_thread_list = curr_thread_list;
1084
1085 SetThreadStopInfo (m_last_stop_packet);
1086 }
1087 return GetThreadList().GetSize(false);
1088}
1089
1090
1091StateType
1092ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1093{
1094 const char stop_type = stop_packet.GetChar();
1095 switch (stop_type)
1096 {
1097 case 'T':
1098 case 'S':
1099 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001100 if (GetStopID() == 0)
1101 {
1102 // Our first stop, make sure we have a process ID, and also make
1103 // sure we know about our registers
1104 if (GetID() == LLDB_INVALID_PROCESS_ID)
1105 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001106 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001107 if (pid != LLDB_INVALID_PROCESS_ID)
1108 SetID (pid);
1109 }
1110 BuildDynamicRegisterInfo (true);
1111 }
Chris Lattner24943d22010-06-08 16:52:24 +00001112 // Stop with signal and thread info
1113 const uint8_t signo = stop_packet.GetHexU8();
1114 std::string name;
1115 std::string value;
1116 std::string thread_name;
1117 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001118 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001119 uint32_t tid = LLDB_INVALID_THREAD_ID;
1120 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1121 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001122 ThreadSP thread_sp;
1123
Chris Lattner24943d22010-06-08 16:52:24 +00001124 while (stop_packet.GetNameColonValue(name, value))
1125 {
1126 if (name.compare("metype") == 0)
1127 {
1128 // exception type in big endian hex
1129 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1130 }
1131 else if (name.compare("mecount") == 0)
1132 {
1133 // exception count in big endian hex
1134 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1135 }
1136 else if (name.compare("medata") == 0)
1137 {
1138 // exception data in big endian hex
1139 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1140 }
1141 else if (name.compare("thread") == 0)
1142 {
1143 // thread in big endian hex
1144 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001145 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001146 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001147 if (!thread_sp)
1148 {
1149 // Create the thread if we need to
1150 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1151 m_thread_list.AddThread(thread_sp);
1152 }
Chris Lattner24943d22010-06-08 16:52:24 +00001153 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001154 else if (name.compare("hexname") == 0)
1155 {
1156 StringExtractor name_extractor;
1157 // Swap "value" over into "name_extractor"
1158 name_extractor.GetStringRef().swap(value);
1159 // Now convert the HEX bytes into a string value
1160 name_extractor.GetHexByteString (value);
1161 thread_name.swap (value);
1162 }
Chris Lattner24943d22010-06-08 16:52:24 +00001163 else if (name.compare("name") == 0)
1164 {
1165 thread_name.swap (value);
1166 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001167 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001168 {
1169 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1170 }
Greg Claytona875b642011-01-09 21:07:35 +00001171 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1172 {
1173 // We have a register number that contains an expedited
1174 // register value. Lets supply this register to our thread
1175 // so it won't have to go and read it.
1176 if (thread_sp)
1177 {
1178 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1179
1180 if (reg != UINT32_MAX)
1181 {
1182 StringExtractor reg_value_extractor;
1183 // Swap "value" over into "reg_value_extractor"
1184 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001185 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1186 {
1187 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1188 name.c_str(),
1189 reg,
1190 reg,
1191 reg_value_extractor.GetStringRef().c_str(),
1192 stop_packet.GetStringRef().c_str());
1193 }
Greg Claytona875b642011-01-09 21:07:35 +00001194 }
1195 }
1196 }
Chris Lattner24943d22010-06-08 16:52:24 +00001197 }
Chris Lattner24943d22010-06-08 16:52:24 +00001198
1199 if (thread_sp)
1200 {
1201 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1202
1203 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001204 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001205 if (exc_type != 0)
1206 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001207 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001208
1209 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1210 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001211 exc_data_size,
1212 exc_data_size >= 1 ? exc_data[0] : 0,
1213 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001214 }
1215 else if (signo)
1216 {
Greg Clayton643ee732010-08-04 01:40:35 +00001217 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001218 }
1219 else
1220 {
Greg Clayton643ee732010-08-04 01:40:35 +00001221 StopInfoSP invalid_stop_info_sp;
1222 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001223 }
1224 }
1225 return eStateStopped;
1226 }
1227 break;
1228
1229 case 'W':
1230 // process exited
1231 return eStateExited;
1232
1233 default:
1234 break;
1235 }
1236 return eStateInvalid;
1237}
1238
1239void
1240ProcessGDBRemote::RefreshStateAfterStop ()
1241{
Jim Ingham7508e732010-08-09 23:31:02 +00001242 // FIXME - add a variable to tell that we're in the middle of attaching if we
1243 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001244 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001245// if (!GetTarget().GetArchitecture().IsValid())
1246// {
1247// Module *exe_module = GetTarget().GetExecutableModule().get();
1248// if (exe_module)
1249// m_arch_spec = exe_module->GetArchitecture();
1250// }
1251
Chris Lattner24943d22010-06-08 16:52:24 +00001252 // Let all threads recover from stopping and do any clean up based
1253 // on the previous thread state (if any).
1254 m_thread_list.RefreshStateAfterStop();
1255
1256 // Discover new threads:
1257 UpdateThreadListIfNeeded ();
1258}
1259
1260Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001261ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001262{
1263 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001264
Greg Claytona4881d02011-01-22 07:12:45 +00001265 bool timed_out = false;
1266 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001267
1268 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001269 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001270 // We are being asked to halt during an attach. We need to just close
1271 // our file handle and debugserver will go away, and we can be done...
1272 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001273 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001274 else
1275 {
1276 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1277 {
1278 if (timed_out)
1279 error.SetErrorString("timed out sending interrupt packet");
1280 else
1281 error.SetErrorString("unknown error sending interrupt packet");
1282 }
1283 }
Chris Lattner24943d22010-06-08 16:52:24 +00001284 return error;
1285}
1286
1287Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001288ProcessGDBRemote::InterruptIfRunning
1289(
1290 bool discard_thread_plans,
1291 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001292 EventSP &stop_event_sp
1293)
Chris Lattner24943d22010-06-08 16:52:24 +00001294{
1295 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001296
Greg Clayton2860ba92011-01-23 19:58:49 +00001297 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1298
Greg Clayton68ca8232011-01-25 02:58:48 +00001299 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001300 const bool is_running = m_gdb_comm.IsRunning();
1301 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001302 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001303 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001304 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001305 is_running);
1306
Greg Clayton2860ba92011-01-23 19:58:49 +00001307 if (discard_thread_plans)
1308 {
1309 if (log)
1310 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1311 m_thread_list.DiscardThreadPlans();
1312 }
1313 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001314 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001315 if (catch_stop_event)
1316 {
1317 if (log)
1318 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1319 PausePrivateStateThread();
1320 paused_private_state_thread = true;
1321 }
1322
Greg Clayton4fb400f2010-09-27 21:07:38 +00001323 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001324 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001325 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001326
Greg Clayton72e1c782011-01-22 23:43:18 +00001327 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001328 {
1329 if (timed_out)
1330 error.SetErrorString("timed out sending interrupt packet");
1331 else
1332 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001333 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001334 ResumePrivateStateThread();
1335 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001336 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001337
Greg Clayton72e1c782011-01-22 23:43:18 +00001338 if (catch_stop_event)
1339 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001340 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001341 TimeValue timeout_time;
1342 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001343 timeout_time.OffsetWithSeconds(5);
1344 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001345
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001346 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001347 if (log)
1348 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001349
Greg Clayton2860ba92011-01-23 19:58:49 +00001350 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001351 error.SetErrorString("unable to verify target stopped");
1352 }
1353
Greg Clayton68ca8232011-01-25 02:58:48 +00001354 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001355 {
1356 if (log)
1357 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001358 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001359 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001360 }
Chris Lattner24943d22010-06-08 16:52:24 +00001361 return error;
1362}
1363
Greg Clayton4fb400f2010-09-27 21:07:38 +00001364Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001365ProcessGDBRemote::WillDetach ()
1366{
Greg Clayton2860ba92011-01-23 19:58:49 +00001367 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1368 if (log)
1369 log->Printf ("ProcessGDBRemote::WillDetach()");
1370
Greg Clayton72e1c782011-01-22 23:43:18 +00001371 bool discard_thread_plans = true;
1372 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001373 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001374 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001375}
1376
1377Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001378ProcessGDBRemote::DoDetach()
1379{
1380 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001381 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001382 if (log)
1383 log->Printf ("ProcessGDBRemote::DoDetach()");
1384
1385 DisableAllBreakpointSites ();
1386
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001387 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001388
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001389 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1390 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001391 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001392 if (response_size)
1393 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1394 else
1395 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001396 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001397 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001398 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001399
Greg Clayton4fb400f2010-09-27 21:07:38 +00001400 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001401 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001402
1403 SetPrivateState (eStateDetached);
1404 ResumePrivateStateThread();
1405
1406 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001407 return error;
1408}
Chris Lattner24943d22010-06-08 16:52:24 +00001409
1410Error
1411ProcessGDBRemote::DoDestroy ()
1412{
1413 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001414 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001415 if (log)
1416 log->Printf ("ProcessGDBRemote::DoDestroy()");
1417
1418 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001419 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001420 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001421 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001422 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001423 // We are being asked to halt during an attach. We need to just close
1424 // our file handle and debugserver will go away, and we can be done...
1425 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001426 }
1427 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001428 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001429
1430 StringExtractorGDBRemote response;
1431 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001432 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001433 {
1434 char packet_cmd = response.GetChar(0);
1435
1436 if (packet_cmd == 'W' || packet_cmd == 'X')
1437 {
1438 m_last_stop_packet = response;
1439 SetExitStatus(response.GetHexU8(), NULL);
1440 }
1441 }
1442 else
1443 {
1444 SetExitStatus(SIGABRT, NULL);
1445 //error.SetErrorString("kill packet failed");
1446 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001447 }
1448 }
Chris Lattner24943d22010-06-08 16:52:24 +00001449 StopAsyncThread ();
1450 m_gdb_comm.StopReadThread();
1451 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001452 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001453 return error;
1454}
1455
Chris Lattner24943d22010-06-08 16:52:24 +00001456//------------------------------------------------------------------
1457// Process Queries
1458//------------------------------------------------------------------
1459
1460bool
1461ProcessGDBRemote::IsAlive ()
1462{
Greg Clayton58e844b2010-12-08 05:08:21 +00001463 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001464}
1465
1466addr_t
1467ProcessGDBRemote::GetImageInfoAddress()
1468{
1469 if (!m_gdb_comm.IsRunning())
1470 {
1471 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001472 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001473 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001474 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001475 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1476 }
1477 }
1478 return LLDB_INVALID_ADDRESS;
1479}
1480
Chris Lattner24943d22010-06-08 16:52:24 +00001481//------------------------------------------------------------------
1482// Process Memory
1483//------------------------------------------------------------------
1484size_t
1485ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1486{
1487 if (size > m_max_memory_size)
1488 {
1489 // Keep memory read sizes down to a sane limit. This function will be
1490 // called multiple times in order to complete the task by
1491 // lldb_private::Process so it is ok to do this.
1492 size = m_max_memory_size;
1493 }
1494
1495 char packet[64];
1496 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1497 assert (packet_len + 1 < sizeof(packet));
1498 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001499 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001500 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001501 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001502 {
1503 error.Clear();
1504 return response.GetHexBytes(buf, size, '\xdd');
1505 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001506 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001507 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001508 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001509 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1510 else
1511 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1512 }
1513 else
1514 {
1515 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1516 }
1517 return 0;
1518}
1519
1520size_t
1521ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1522{
1523 StreamString packet;
1524 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001525 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001526 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001527 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001528 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001529 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001530 {
1531 error.Clear();
1532 return size;
1533 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001534 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001535 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001536 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001537 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1538 else
1539 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1540 }
1541 else
1542 {
1543 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1544 }
1545 return 0;
1546}
1547
1548lldb::addr_t
1549ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1550{
Greg Clayton989816b2011-05-14 01:50:35 +00001551 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1552
Greg Clayton2f085c62011-05-15 01:25:55 +00001553 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001554 switch (supported)
1555 {
1556 case eLazyBoolCalculate:
1557 case eLazyBoolYes:
1558 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1559 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1560 return allocated_addr;
1561
1562 case eLazyBoolNo:
1563 // Call mmap() to create executable memory in the inferior..
1564 {
1565 Thread *thread = GetThreadList().GetSelectedThread().get();
1566 if (thread == NULL)
1567 thread = GetThreadList().GetThreadAtIndex(0).get();
1568
1569 const bool append = true;
1570 const bool include_symbols = true;
1571 SymbolContextList sc_list;
1572 const uint32_t count = m_target.GetImages().FindFunctions (ConstString ("mmap"),
1573 eFunctionNameTypeFull,
1574 include_symbols,
1575 append,
1576 sc_list);
1577 if (count > 0)
1578 {
1579 SymbolContext sc;
1580 if (sc_list.GetContextAtIndex(0, sc))
1581 {
1582 const uint32_t range_scope = eSymbolContextFunction | eSymbolContextSymbol;
1583 const bool use_inline_block_range = false;
1584 const bool stop_other_threads = true;
1585 const bool discard_on_error = true;
1586 const bool try_all_threads = true;
1587 const uint32_t single_thread_timeout_usec = 500000;
1588 addr_t arg1_addr = 0;
1589 addr_t arg2_len = size;
1590 addr_t arg3_prot = PROT_NONE;
1591 addr_t arg4_flags = MAP_ANON;
1592 addr_t arg5_fd = -1;
1593 addr_t arg6_offset = 0;
1594 if (permissions & lldb::ePermissionsReadable)
1595 arg3_prot |= PROT_READ;
1596 if (permissions & lldb::ePermissionsWritable)
1597 arg3_prot |= PROT_WRITE;
1598 if (permissions & lldb::ePermissionsExecutable)
1599 arg3_prot |= PROT_EXEC;
1600
1601 AddressRange mmap_range;
1602 if (sc.GetAddressRange(range_scope, 0, use_inline_block_range, mmap_range))
1603 {
Greg Clayton2f085c62011-05-15 01:25:55 +00001604 ThreadPlanCallFunction *call_function_thread_plan = new ThreadPlanCallFunction (*thread,
1605 mmap_range.GetBaseAddress(),
1606 stop_other_threads,
1607 discard_on_error,
1608 &arg1_addr,
1609 &arg2_len,
1610 &arg3_prot,
1611 &arg4_flags,
1612 &arg5_fd,
1613 &arg6_offset);
1614 lldb::ThreadPlanSP call_plan_sp (call_function_thread_plan);
Greg Clayton989816b2011-05-14 01:50:35 +00001615 if (call_plan_sp)
1616 {
Greg Clayton2f085c62011-05-15 01:25:55 +00001617 ValueSP return_value_sp (new Value);
1618 ClangASTContext *clang_ast_context = m_target.GetScratchClangASTContext();
1619 lldb::clang_type_t clang_void_ptr_type = clang_ast_context->GetVoidPtrType(false);
1620 return_value_sp->SetValueType (Value::eValueTypeScalar);
1621 return_value_sp->SetContext (Value::eContextTypeClangType, clang_void_ptr_type);
1622 call_function_thread_plan->RequestReturnValue (return_value_sp);
1623
Greg Clayton989816b2011-05-14 01:50:35 +00001624 StreamFile error_strm;
1625 StackFrame *frame = thread->GetStackFrameAtIndex (0).get();
1626 if (frame)
1627 {
1628 ExecutionContext exe_ctx;
1629 frame->CalculateExecutionContext (exe_ctx);
Greg Clayton2f085c62011-05-15 01:25:55 +00001630 ExecutionResults result = RunThreadPlan (exe_ctx,
1631 call_plan_sp,
1632 stop_other_threads,
1633 try_all_threads,
1634 discard_on_error,
1635 single_thread_timeout_usec,
1636 error_strm);
1637 if (result == eExecutionCompleted)
1638 {
1639 allocated_addr = return_value_sp->GetScalar().ULongLong();
1640 m_addr_to_mmap_size[allocated_addr] = size;
1641 }
Greg Clayton989816b2011-05-14 01:50:35 +00001642 }
1643 }
1644 }
1645 }
1646 }
1647 }
1648 break;
1649 }
1650
Chris Lattner24943d22010-06-08 16:52:24 +00001651 if (allocated_addr == LLDB_INVALID_ADDRESS)
1652 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1653 else
1654 error.Clear();
1655 return allocated_addr;
1656}
1657
1658Error
1659ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1660{
1661 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001662 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1663
1664 switch (supported)
1665 {
1666 case eLazyBoolCalculate:
1667 // We should never be deallocating memory without allocating memory
1668 // first so we should never get eLazyBoolCalculate
1669 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1670 break;
1671
1672 case eLazyBoolYes:
1673 if (!m_gdb_comm.DeallocateMemory (addr))
1674 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1675 break;
1676
1677 case eLazyBoolNo:
1678 // Call munmap() to create executable memory in the inferior..
1679 {
1680 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
1681 if (pos != m_addr_to_mmap_size.end())
1682 {
1683 Thread *thread = GetThreadList().GetSelectedThread().get();
1684 if (thread == NULL)
1685 thread = GetThreadList().GetThreadAtIndex(0).get();
1686
1687 const bool append = true;
1688 const bool include_symbols = true;
1689 SymbolContextList sc_list;
1690 const uint32_t count = m_target.GetImages().FindFunctions (ConstString ("munmap"),
1691 eFunctionNameTypeFull,
1692 include_symbols,
1693 append,
1694 sc_list);
1695 if (count > 0)
1696 {
1697 SymbolContext sc;
1698 if (sc_list.GetContextAtIndex(0, sc))
1699 {
1700 const uint32_t range_scope = eSymbolContextFunction | eSymbolContextSymbol;
1701 const bool use_inline_block_range = false;
1702 const bool stop_other_threads = true;
1703 const bool discard_on_error = true;
1704 const bool try_all_threads = true;
1705 const uint32_t single_thread_timeout_usec = 500000;
1706 addr_t arg1_addr = addr;
1707 addr_t arg2_len = pos->second;
1708
1709 AddressRange munmap_range;
1710 if (sc.GetAddressRange(range_scope, 0, use_inline_block_range, munmap_range))
1711 {
1712 lldb::ThreadPlanSP call_plan_sp (new ThreadPlanCallFunction (*thread,
1713 munmap_range.GetBaseAddress(),
1714 stop_other_threads,
1715 discard_on_error,
1716 &arg1_addr,
1717 &arg2_len));
1718 if (call_plan_sp)
1719 {
1720 StreamFile error_strm;
1721 StackFrame *frame = thread->GetStackFrameAtIndex (0).get();
1722 if (frame)
1723 {
1724 ExecutionContext exe_ctx;
1725 frame->CalculateExecutionContext (exe_ctx);
1726 ExecutionResults result = RunThreadPlan (exe_ctx,
1727 call_plan_sp,
1728 stop_other_threads,
1729 try_all_threads,
1730 discard_on_error,
1731 single_thread_timeout_usec,
1732 error_strm);
1733 if (result == eExecutionCompleted)
1734 {
1735 m_addr_to_mmap_size.erase (pos);
1736 }
1737 }
1738 }
1739 }
1740 }
1741 }
1742 }
1743 }
1744 break;
1745 }
1746
Chris Lattner24943d22010-06-08 16:52:24 +00001747 return error;
1748}
1749
1750
1751//------------------------------------------------------------------
1752// Process STDIO
1753//------------------------------------------------------------------
1754
1755size_t
1756ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1757{
1758 Mutex::Locker locker(m_stdio_mutex);
1759 size_t bytes_available = m_stdout_data.size();
1760 if (bytes_available > 0)
1761 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001762 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1763 if (log)
1764 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001765 if (bytes_available > buf_size)
1766 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001767 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001768 m_stdout_data.erase(0, buf_size);
1769 bytes_available = buf_size;
1770 }
1771 else
1772 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001773 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001774 m_stdout_data.clear();
1775
1776 //ResetEventBits(eBroadcastBitSTDOUT);
1777 }
1778 }
1779 return bytes_available;
1780}
1781
1782size_t
1783ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1784{
1785 // Can we get STDERR through the remote protocol?
1786 return 0;
1787}
1788
1789size_t
1790ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1791{
1792 if (m_stdio_communication.IsConnected())
1793 {
1794 ConnectionStatus status;
1795 m_stdio_communication.Write(src, src_len, status, NULL);
1796 }
1797 return 0;
1798}
1799
1800Error
1801ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1802{
1803 Error error;
1804 assert (bp_site != NULL);
1805
Greg Claytone005f2c2010-11-06 01:53:30 +00001806 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001807 user_id_t site_id = bp_site->GetID();
1808 const addr_t addr = bp_site->GetLoadAddress();
1809 if (log)
1810 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1811
1812 if (bp_site->IsEnabled())
1813 {
1814 if (log)
1815 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1816 return error;
1817 }
1818 else
1819 {
1820 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1821
1822 if (bp_site->HardwarePreferred())
1823 {
1824 // Try and set hardware breakpoint, and if that fails, fall through
1825 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001826 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001827 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001828 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001829 {
1830 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001831 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001832 return error;
1833 }
Chris Lattner24943d22010-06-08 16:52:24 +00001834 }
1835 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001836
1837 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001838 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001839 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1840 {
1841 bp_site->SetEnabled(true);
1842 bp_site->SetType (BreakpointSite::eExternal);
1843 return error;
1844 }
Chris Lattner24943d22010-06-08 16:52:24 +00001845 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001846
1847 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001848 }
1849
1850 if (log)
1851 {
1852 const char *err_string = error.AsCString();
1853 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1854 bp_site->GetLoadAddress(),
1855 err_string ? err_string : "NULL");
1856 }
1857 // We shouldn't reach here on a successful breakpoint enable...
1858 if (error.Success())
1859 error.SetErrorToGenericError();
1860 return error;
1861}
1862
1863Error
1864ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1865{
1866 Error error;
1867 assert (bp_site != NULL);
1868 addr_t addr = bp_site->GetLoadAddress();
1869 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001870 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001871 if (log)
1872 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1873
1874 if (bp_site->IsEnabled())
1875 {
1876 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1877
Greg Claytonb72d0f02011-04-12 05:54:46 +00001878 BreakpointSite::Type bp_type = bp_site->GetType();
1879 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001880 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001881 case BreakpointSite::eSoftware:
1882 error = DisableSoftwareBreakpoint (bp_site);
1883 break;
1884
1885 case BreakpointSite::eHardware:
1886 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1887 error.SetErrorToGenericError();
1888 break;
1889
1890 case BreakpointSite::eExternal:
1891 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1892 error.SetErrorToGenericError();
1893 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001894 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001895 if (error.Success())
1896 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001897 }
1898 else
1899 {
1900 if (log)
1901 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1902 return error;
1903 }
1904
1905 if (error.Success())
1906 error.SetErrorToGenericError();
1907 return error;
1908}
1909
1910Error
1911ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1912{
1913 Error error;
1914 if (wp)
1915 {
1916 user_id_t watchID = wp->GetID();
1917 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001918 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001919 if (log)
1920 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1921 if (wp->IsEnabled())
1922 {
1923 if (log)
1924 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1925 return error;
1926 }
1927 else
1928 {
1929 // Pass down an appropriate z/Z packet...
1930 error.SetErrorString("watchpoints not supported");
1931 }
1932 }
1933 else
1934 {
1935 error.SetErrorString("Watchpoint location argument was NULL.");
1936 }
1937 if (error.Success())
1938 error.SetErrorToGenericError();
1939 return error;
1940}
1941
1942Error
1943ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1944{
1945 Error error;
1946 if (wp)
1947 {
1948 user_id_t watchID = wp->GetID();
1949
Greg Claytone005f2c2010-11-06 01:53:30 +00001950 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001951
1952 addr_t addr = wp->GetLoadAddress();
1953 if (log)
1954 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1955
1956 if (wp->IsHardware())
1957 {
1958 // Pass down an appropriate z/Z packet...
1959 error.SetErrorString("watchpoints not supported");
1960 }
1961 // TODO: clear software watchpoints if we implement them
1962 }
1963 else
1964 {
1965 error.SetErrorString("Watchpoint location argument was NULL.");
1966 }
1967 if (error.Success())
1968 error.SetErrorToGenericError();
1969 return error;
1970}
1971
1972void
1973ProcessGDBRemote::Clear()
1974{
1975 m_flags = 0;
1976 m_thread_list.Clear();
1977 {
1978 Mutex::Locker locker(m_stdio_mutex);
1979 m_stdout_data.clear();
1980 }
Chris Lattner24943d22010-06-08 16:52:24 +00001981}
1982
1983Error
1984ProcessGDBRemote::DoSignal (int signo)
1985{
1986 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001987 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001988 if (log)
1989 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1990
1991 if (!m_gdb_comm.SendAsyncSignal (signo))
1992 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1993 return error;
1994}
1995
Chris Lattner24943d22010-06-08 16:52:24 +00001996Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00001997ProcessGDBRemote::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 +00001998{
1999 Error error;
2000 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2001 {
2002 // If we locate debugserver, keep that located version around
2003 static FileSpec g_debugserver_file_spec;
2004
Greg Claytonb72d0f02011-04-12 05:54:46 +00002005 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002006 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002007 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002008
2009 // Always check to see if we have an environment override for the path
2010 // to the debugserver to use and use it if we do.
2011 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2012 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002013 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002014 else
2015 debugserver_file_spec = g_debugserver_file_spec;
2016 bool debugserver_exists = debugserver_file_spec.Exists();
2017 if (!debugserver_exists)
2018 {
2019 // The debugserver binary is in the LLDB.framework/Resources
2020 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002021 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002022 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002023 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002024 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002025 if (debugserver_exists)
2026 {
2027 g_debugserver_file_spec = debugserver_file_spec;
2028 }
2029 else
2030 {
2031 g_debugserver_file_spec.Clear();
2032 debugserver_file_spec.Clear();
2033 }
Chris Lattner24943d22010-06-08 16:52:24 +00002034 }
2035 }
2036
2037 if (debugserver_exists)
2038 {
2039 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2040
2041 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002042
Greg Claytone005f2c2010-11-06 01:53:30 +00002043 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002044
Greg Claytonb72d0f02011-04-12 05:54:46 +00002045 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002046 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002047
Chris Lattner24943d22010-06-08 16:52:24 +00002048 // Start args with "debugserver /file/path -r --"
2049 debugserver_args.AppendArgument(debugserver_path);
2050 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002051 // use native registers, not the GDB registers
2052 debugserver_args.AppendArgument("--native-regs");
2053 // make debugserver run in its own session so signals generated by
2054 // special terminal key sequences (^C) don't affect debugserver
2055 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002056
Chris Lattner24943d22010-06-08 16:52:24 +00002057 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2058 if (env_debugserver_log_file)
2059 {
2060 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2061 debugserver_args.AppendArgument(arg_cstr);
2062 }
2063
2064 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2065 if (env_debugserver_log_flags)
2066 {
2067 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2068 debugserver_args.AppendArgument(arg_cstr);
2069 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002070// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002071// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002072
Greg Claytonb72d0f02011-04-12 05:54:46 +00002073 // We currently send down all arguments, attach pids, or attach
2074 // process names in dedicated GDB server packets, so we don't need
2075 // to pass them as arguments. This is currently because of all the
2076 // things we need to setup prior to launching: the environment,
2077 // current working dir, file actions, etc.
2078#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002079 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002080 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002081 {
Greg Claytona2f74232011-02-24 22:24:29 +00002082 // Terminate the debugserver args so we can now append the inferior args
2083 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002084
Greg Claytona2f74232011-02-24 22:24:29 +00002085 for (int i = 0; inferior_argv[i] != NULL; ++i)
2086 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002087 }
2088 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2089 {
2090 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2091 debugserver_args.AppendArgument (arg_cstr);
2092 }
2093 else if (attach_name && attach_name[0])
2094 {
2095 if (wait_for_launch)
2096 debugserver_args.AppendArgument ("--waitfor");
2097 else
2098 debugserver_args.AppendArgument ("--attach");
2099 debugserver_args.AppendArgument (attach_name);
2100 }
Chris Lattner24943d22010-06-08 16:52:24 +00002101#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002102
2103 ProcessLaunchInfo::FileAction file_action;
2104
2105 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2106 // to "/dev/null" if we run into any problems.
2107 file_action.Close (STDIN_FILENO);
2108 launch_info.AppendFileAction (file_action);
2109 file_action.Close (STDOUT_FILENO);
2110 launch_info.AppendFileAction (file_action);
2111 file_action.Close (STDERR_FILENO);
2112 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002113
2114 if (log)
2115 {
2116 StreamString strm;
2117 debugserver_args.Dump (&strm);
2118 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2119 }
2120
Greg Claytonb72d0f02011-04-12 05:54:46 +00002121 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002122
Greg Claytonb72d0f02011-04-12 05:54:46 +00002123 if (error.Success ())
2124 m_debugserver_pid = launch_info.GetProcessID();
2125 else
Chris Lattner24943d22010-06-08 16:52:24 +00002126 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2127
2128 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002129 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002130 }
2131 else
2132 {
2133 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2134 }
2135
2136 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2137 StartAsyncThread ();
2138 }
2139 return error;
2140}
2141
2142bool
2143ProcessGDBRemote::MonitorDebugserverProcess
2144(
2145 void *callback_baton,
2146 lldb::pid_t debugserver_pid,
2147 int signo, // Zero for no signal
2148 int exit_status // Exit value of process if signal is zero
2149)
2150{
2151 // We pass in the ProcessGDBRemote inferior process it and name it
2152 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2153 // pointer value itself, thus we need the double cast...
2154
2155 // "debugserver_pid" argument passed in is the process ID for
2156 // debugserver that we are tracking...
2157
Greg Clayton75ccf502010-08-21 02:22:51 +00002158 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002159
2160 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2161 if (log)
2162 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2163
Greg Clayton75ccf502010-08-21 02:22:51 +00002164 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002165 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002166 // Sleep for a half a second to make sure our inferior process has
2167 // time to set its exit status before we set it incorrectly when
2168 // both the debugserver and the inferior process shut down.
2169 usleep (500000);
2170 // If our process hasn't yet exited, debugserver might have died.
2171 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002172 const StateType state = process->GetState();
2173
2174 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2175 state != eStateInvalid &&
2176 state != eStateUnloaded &&
2177 state != eStateExited &&
2178 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002179 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002180 char error_str[1024];
2181 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002182 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002183 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2184 if (signal_cstr)
2185 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002186 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002187 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002188 }
2189 else
2190 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002191 ::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 +00002192 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002193
2194 process->SetExitStatus (-1, error_str);
2195 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002196 // Debugserver has exited we need to let our ProcessGDBRemote
2197 // know that it no longer has a debugserver instance
2198 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2199 // We are returning true to this function below, so we can
2200 // forget about the monitor handle.
2201 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002202 }
2203 return true;
2204}
2205
2206void
2207ProcessGDBRemote::KillDebugserverProcess ()
2208{
2209 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2210 {
2211 ::kill (m_debugserver_pid, SIGINT);
2212 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2213 }
2214}
2215
2216void
2217ProcessGDBRemote::Initialize()
2218{
2219 static bool g_initialized = false;
2220
2221 if (g_initialized == false)
2222 {
2223 g_initialized = true;
2224 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2225 GetPluginDescriptionStatic(),
2226 CreateInstance);
2227
2228 Log::Callbacks log_callbacks = {
2229 ProcessGDBRemoteLog::DisableLog,
2230 ProcessGDBRemoteLog::EnableLog,
2231 ProcessGDBRemoteLog::ListLogCategories
2232 };
2233
2234 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2235 }
2236}
2237
2238bool
Chris Lattner24943d22010-06-08 16:52:24 +00002239ProcessGDBRemote::StartAsyncThread ()
2240{
Greg Claytone005f2c2010-11-06 01:53:30 +00002241 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002242
2243 if (log)
2244 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2245
2246 // Create a thread that watches our internal state and controls which
2247 // events make it to clients (into the DCProcess event queue).
2248 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002249 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002250}
2251
2252void
2253ProcessGDBRemote::StopAsyncThread ()
2254{
Greg Claytone005f2c2010-11-06 01:53:30 +00002255 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002256
2257 if (log)
2258 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2259
2260 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2261
2262 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002263 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002264 {
2265 Host::ThreadJoin (m_async_thread, NULL, NULL);
2266 }
2267}
2268
2269
2270void *
2271ProcessGDBRemote::AsyncThread (void *arg)
2272{
2273 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2274
Greg Claytone005f2c2010-11-06 01:53:30 +00002275 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002276 if (log)
2277 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2278
2279 Listener listener ("ProcessGDBRemote::AsyncThread");
2280 EventSP event_sp;
2281 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2282 eBroadcastBitAsyncThreadShouldExit;
2283
2284 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2285 {
Greg Claytona2f74232011-02-24 22:24:29 +00002286 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2287
Chris Lattner24943d22010-06-08 16:52:24 +00002288 bool done = false;
2289 while (!done)
2290 {
2291 if (log)
2292 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2293 if (listener.WaitForEvent (NULL, event_sp))
2294 {
2295 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002296 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002297 {
Greg Claytona2f74232011-02-24 22:24:29 +00002298 if (log)
2299 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 +00002300
Greg Claytona2f74232011-02-24 22:24:29 +00002301 switch (event_type)
2302 {
2303 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002304 {
Greg Claytona2f74232011-02-24 22:24:29 +00002305 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002306
Greg Claytona2f74232011-02-24 22:24:29 +00002307 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002308 {
Greg Claytona2f74232011-02-24 22:24:29 +00002309 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2310 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2311 if (log)
2312 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002313
Greg Claytona2f74232011-02-24 22:24:29 +00002314 if (::strstr (continue_cstr, "vAttach") == NULL)
2315 process->SetPrivateState(eStateRunning);
2316 StringExtractorGDBRemote response;
2317 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002318
Greg Claytona2f74232011-02-24 22:24:29 +00002319 switch (stop_state)
2320 {
2321 case eStateStopped:
2322 case eStateCrashed:
2323 case eStateSuspended:
2324 process->m_last_stop_packet = response;
2325 process->m_last_stop_packet.SetFilePos (0);
2326 process->SetPrivateState (stop_state);
2327 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002328
Greg Claytona2f74232011-02-24 22:24:29 +00002329 case eStateExited:
2330 process->m_last_stop_packet = response;
2331 process->m_last_stop_packet.SetFilePos (0);
2332 response.SetFilePos(1);
2333 process->SetExitStatus(response.GetHexU8(), NULL);
2334 done = true;
2335 break;
2336
2337 case eStateInvalid:
2338 process->SetExitStatus(-1, "lost connection");
2339 break;
2340
2341 default:
2342 process->SetPrivateState (stop_state);
2343 break;
2344 }
Chris Lattner24943d22010-06-08 16:52:24 +00002345 }
2346 }
Greg Claytona2f74232011-02-24 22:24:29 +00002347 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002348
Greg Claytona2f74232011-02-24 22:24:29 +00002349 case eBroadcastBitAsyncThreadShouldExit:
2350 if (log)
2351 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2352 done = true;
2353 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002354
Greg Claytona2f74232011-02-24 22:24:29 +00002355 default:
2356 if (log)
2357 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2358 done = true;
2359 break;
2360 }
2361 }
2362 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2363 {
2364 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2365 {
2366 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002367 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002368 }
Chris Lattner24943d22010-06-08 16:52:24 +00002369 }
2370 }
2371 else
2372 {
2373 if (log)
2374 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2375 done = true;
2376 }
2377 }
2378 }
2379
2380 if (log)
2381 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2382
2383 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2384 return NULL;
2385}
2386
Chris Lattner24943d22010-06-08 16:52:24 +00002387const char *
2388ProcessGDBRemote::GetDispatchQueueNameForThread
2389(
2390 addr_t thread_dispatch_qaddr,
2391 std::string &dispatch_queue_name
2392)
2393{
2394 dispatch_queue_name.clear();
2395 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2396 {
2397 // Cache the dispatch_queue_offsets_addr value so we don't always have
2398 // to look it up
2399 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2400 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002401 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2402 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002403 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002404 if (module_sp)
2405 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2406
2407 if (dispatch_queue_offsets_symbol == NULL)
2408 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002409 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002410 if (module_sp)
2411 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2412 }
Chris Lattner24943d22010-06-08 16:52:24 +00002413 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002414 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002415
2416 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2417 return NULL;
2418 }
2419
2420 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002421 DataExtractor data (memory_buffer,
2422 sizeof(memory_buffer),
2423 m_target.GetArchitecture().GetByteOrder(),
2424 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002425
2426 // Excerpt from src/queue_private.h
2427 struct dispatch_queue_offsets_s
2428 {
2429 uint16_t dqo_version;
2430 uint16_t dqo_label;
2431 uint16_t dqo_label_size;
2432 } dispatch_queue_offsets;
2433
2434
2435 Error error;
2436 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2437 {
2438 uint32_t data_offset = 0;
2439 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2440 {
2441 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2442 {
2443 data_offset = 0;
2444 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2445 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2446 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2447 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2448 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2449 dispatch_queue_name.erase (bytes_read);
2450 }
2451 }
2452 }
2453 }
2454 if (dispatch_queue_name.empty())
2455 return NULL;
2456 return dispatch_queue_name.c_str();
2457}
2458
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002459//uint32_t
2460//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2461//{
2462// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2463// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2464// if (m_local_debugserver)
2465// {
2466// return Host::ListProcessesMatchingName (name, matches, pids);
2467// }
2468// else
2469// {
2470// // FIXME: Implement talking to the remote debugserver.
2471// return 0;
2472// }
2473//
2474//}
2475//
Jim Ingham55e01d82011-01-22 01:33:44 +00002476bool
2477ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2478 lldb_private::StoppointCallbackContext *context,
2479 lldb::user_id_t break_id,
2480 lldb::user_id_t break_loc_id)
2481{
2482 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2483 // run so I can stop it if that's what I want to do.
2484 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2485 if (log)
2486 log->Printf("Hit New Thread Notification breakpoint.");
2487 return false;
2488}
2489
2490
2491bool
2492ProcessGDBRemote::StartNoticingNewThreads()
2493{
2494 static const char *bp_names[] =
2495 {
2496 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002497 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002498 "_pthread_start",
2499 NULL
2500 };
2501
2502 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2503 size_t num_bps = m_thread_observation_bps.size();
2504 if (num_bps != 0)
2505 {
2506 for (int i = 0; i < num_bps; i++)
2507 {
2508 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2509 if (break_sp)
2510 {
2511 if (log)
2512 log->Printf("Enabled noticing new thread breakpoint.");
2513 break_sp->SetEnabled(true);
2514 }
2515 }
2516 }
2517 else
2518 {
2519 for (int i = 0; bp_names[i] != NULL; i++)
2520 {
2521 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2522 if (breakpoint)
2523 {
2524 if (log)
2525 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2526 m_thread_observation_bps.push_back(breakpoint->GetID());
2527 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2528 }
2529 else
2530 {
2531 if (log)
2532 log->Printf("Failed to create new thread notification breakpoint.");
2533 return false;
2534 }
2535 }
2536 }
2537
2538 return true;
2539}
2540
2541bool
2542ProcessGDBRemote::StopNoticingNewThreads()
2543{
Jim Inghamff276fe2011-02-08 05:19:01 +00002544 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2545 if (log)
2546 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002547 size_t num_bps = m_thread_observation_bps.size();
2548 if (num_bps != 0)
2549 {
2550 for (int i = 0; i < num_bps; i++)
2551 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002552
2553 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2554 if (break_sp)
2555 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002556 break_sp->SetEnabled(false);
2557 }
2558 }
2559 }
2560 return true;
2561}
2562
2563