blob: 5cfc52a66752b55296f4b461fa408269ccf02f09 [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
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001055 std::vector<lldb::tid_t> thread_ids;
1056 bool sequence_mutex_unavailable = false;
1057 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1058 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001059 {
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001060 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001061 {
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001062 tid_t tid = thread_ids[i];
1063 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
1064 if (!thread_sp)
1065 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1066 curr_thread_list.AddThread(thread_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001067 }
1068 }
1069
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001070 if (sequence_mutex_unavailable == false)
1071 {
1072 m_thread_list = curr_thread_list;
1073 SetThreadStopInfo (m_last_stop_packet);
1074 }
Chris Lattner24943d22010-06-08 16:52:24 +00001075 }
1076 return GetThreadList().GetSize(false);
1077}
1078
1079
1080StateType
1081ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1082{
1083 const char stop_type = stop_packet.GetChar();
1084 switch (stop_type)
1085 {
1086 case 'T':
1087 case 'S':
1088 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001089 if (GetStopID() == 0)
1090 {
1091 // Our first stop, make sure we have a process ID, and also make
1092 // sure we know about our registers
1093 if (GetID() == LLDB_INVALID_PROCESS_ID)
1094 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001095 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001096 if (pid != LLDB_INVALID_PROCESS_ID)
1097 SetID (pid);
1098 }
1099 BuildDynamicRegisterInfo (true);
1100 }
Chris Lattner24943d22010-06-08 16:52:24 +00001101 // Stop with signal and thread info
1102 const uint8_t signo = stop_packet.GetHexU8();
1103 std::string name;
1104 std::string value;
1105 std::string thread_name;
1106 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001107 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001108 uint32_t tid = LLDB_INVALID_THREAD_ID;
1109 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1110 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001111 ThreadSP thread_sp;
1112
Chris Lattner24943d22010-06-08 16:52:24 +00001113 while (stop_packet.GetNameColonValue(name, value))
1114 {
1115 if (name.compare("metype") == 0)
1116 {
1117 // exception type in big endian hex
1118 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1119 }
1120 else if (name.compare("mecount") == 0)
1121 {
1122 // exception count in big endian hex
1123 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1124 }
1125 else if (name.compare("medata") == 0)
1126 {
1127 // exception data in big endian hex
1128 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1129 }
1130 else if (name.compare("thread") == 0)
1131 {
1132 // thread in big endian hex
1133 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001134 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001135 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001136 if (!thread_sp)
1137 {
1138 // Create the thread if we need to
1139 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1140 m_thread_list.AddThread(thread_sp);
1141 }
Chris Lattner24943d22010-06-08 16:52:24 +00001142 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001143 else if (name.compare("hexname") == 0)
1144 {
1145 StringExtractor name_extractor;
1146 // Swap "value" over into "name_extractor"
1147 name_extractor.GetStringRef().swap(value);
1148 // Now convert the HEX bytes into a string value
1149 name_extractor.GetHexByteString (value);
1150 thread_name.swap (value);
1151 }
Chris Lattner24943d22010-06-08 16:52:24 +00001152 else if (name.compare("name") == 0)
1153 {
1154 thread_name.swap (value);
1155 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001156 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001157 {
1158 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1159 }
Greg Claytona875b642011-01-09 21:07:35 +00001160 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1161 {
1162 // We have a register number that contains an expedited
1163 // register value. Lets supply this register to our thread
1164 // so it won't have to go and read it.
1165 if (thread_sp)
1166 {
1167 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1168
1169 if (reg != UINT32_MAX)
1170 {
1171 StringExtractor reg_value_extractor;
1172 // Swap "value" over into "reg_value_extractor"
1173 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001174 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1175 {
1176 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1177 name.c_str(),
1178 reg,
1179 reg,
1180 reg_value_extractor.GetStringRef().c_str(),
1181 stop_packet.GetStringRef().c_str());
1182 }
Greg Claytona875b642011-01-09 21:07:35 +00001183 }
1184 }
1185 }
Chris Lattner24943d22010-06-08 16:52:24 +00001186 }
Chris Lattner24943d22010-06-08 16:52:24 +00001187
1188 if (thread_sp)
1189 {
1190 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1191
1192 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001193 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001194 if (exc_type != 0)
1195 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001196 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001197
1198 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1199 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001200 exc_data_size,
1201 exc_data_size >= 1 ? exc_data[0] : 0,
1202 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001203 }
1204 else if (signo)
1205 {
Greg Clayton643ee732010-08-04 01:40:35 +00001206 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001207 }
1208 else
1209 {
Greg Clayton643ee732010-08-04 01:40:35 +00001210 StopInfoSP invalid_stop_info_sp;
1211 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001212 }
1213 }
1214 return eStateStopped;
1215 }
1216 break;
1217
1218 case 'W':
1219 // process exited
1220 return eStateExited;
1221
1222 default:
1223 break;
1224 }
1225 return eStateInvalid;
1226}
1227
1228void
1229ProcessGDBRemote::RefreshStateAfterStop ()
1230{
Jim Ingham7508e732010-08-09 23:31:02 +00001231 // FIXME - add a variable to tell that we're in the middle of attaching if we
1232 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001233 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001234// if (!GetTarget().GetArchitecture().IsValid())
1235// {
1236// Module *exe_module = GetTarget().GetExecutableModule().get();
1237// if (exe_module)
1238// m_arch_spec = exe_module->GetArchitecture();
1239// }
1240
Chris Lattner24943d22010-06-08 16:52:24 +00001241 // Let all threads recover from stopping and do any clean up based
1242 // on the previous thread state (if any).
1243 m_thread_list.RefreshStateAfterStop();
1244
1245 // Discover new threads:
1246 UpdateThreadListIfNeeded ();
1247}
1248
1249Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001250ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001251{
1252 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001253
Greg Claytona4881d02011-01-22 07:12:45 +00001254 bool timed_out = false;
1255 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001256
1257 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001258 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001259 // We are being asked to halt during an attach. We need to just close
1260 // our file handle and debugserver will go away, and we can be done...
1261 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001262 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001263 else
1264 {
1265 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1266 {
1267 if (timed_out)
1268 error.SetErrorString("timed out sending interrupt packet");
1269 else
1270 error.SetErrorString("unknown error sending interrupt packet");
1271 }
1272 }
Chris Lattner24943d22010-06-08 16:52:24 +00001273 return error;
1274}
1275
1276Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001277ProcessGDBRemote::InterruptIfRunning
1278(
1279 bool discard_thread_plans,
1280 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001281 EventSP &stop_event_sp
1282)
Chris Lattner24943d22010-06-08 16:52:24 +00001283{
1284 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001285
Greg Clayton2860ba92011-01-23 19:58:49 +00001286 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1287
Greg Clayton68ca8232011-01-25 02:58:48 +00001288 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001289 const bool is_running = m_gdb_comm.IsRunning();
1290 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001291 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001292 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001293 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001294 is_running);
1295
Greg Clayton2860ba92011-01-23 19:58:49 +00001296 if (discard_thread_plans)
1297 {
1298 if (log)
1299 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1300 m_thread_list.DiscardThreadPlans();
1301 }
1302 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001303 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001304 if (catch_stop_event)
1305 {
1306 if (log)
1307 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1308 PausePrivateStateThread();
1309 paused_private_state_thread = true;
1310 }
1311
Greg Clayton4fb400f2010-09-27 21:07:38 +00001312 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001313 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001314 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001315
Greg Clayton72e1c782011-01-22 23:43:18 +00001316 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001317 {
1318 if (timed_out)
1319 error.SetErrorString("timed out sending interrupt packet");
1320 else
1321 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001322 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001323 ResumePrivateStateThread();
1324 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001325 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001326
Greg Clayton72e1c782011-01-22 23:43:18 +00001327 if (catch_stop_event)
1328 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001329 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001330 TimeValue timeout_time;
1331 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001332 timeout_time.OffsetWithSeconds(5);
1333 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001334
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001335 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001336 if (log)
1337 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001338
Greg Clayton2860ba92011-01-23 19:58:49 +00001339 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001340 error.SetErrorString("unable to verify target stopped");
1341 }
1342
Greg Clayton68ca8232011-01-25 02:58:48 +00001343 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001344 {
1345 if (log)
1346 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001347 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001348 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001349 }
Chris Lattner24943d22010-06-08 16:52:24 +00001350 return error;
1351}
1352
Greg Clayton4fb400f2010-09-27 21:07:38 +00001353Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001354ProcessGDBRemote::WillDetach ()
1355{
Greg Clayton2860ba92011-01-23 19:58:49 +00001356 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1357 if (log)
1358 log->Printf ("ProcessGDBRemote::WillDetach()");
1359
Greg Clayton72e1c782011-01-22 23:43:18 +00001360 bool discard_thread_plans = true;
1361 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001362 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001363 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001364}
1365
1366Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001367ProcessGDBRemote::DoDetach()
1368{
1369 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001370 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001371 if (log)
1372 log->Printf ("ProcessGDBRemote::DoDetach()");
1373
1374 DisableAllBreakpointSites ();
1375
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001376 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001377
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001378 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1379 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001380 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001381 if (response_size)
1382 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1383 else
1384 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001385 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001386 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001387 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001388
Greg Clayton4fb400f2010-09-27 21:07:38 +00001389 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001390 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001391
1392 SetPrivateState (eStateDetached);
1393 ResumePrivateStateThread();
1394
1395 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001396 return error;
1397}
Chris Lattner24943d22010-06-08 16:52:24 +00001398
1399Error
1400ProcessGDBRemote::DoDestroy ()
1401{
1402 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001403 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001404 if (log)
1405 log->Printf ("ProcessGDBRemote::DoDestroy()");
1406
1407 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001408 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001409 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001410 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001411 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001412 // We are being asked to halt during an attach. We need to just close
1413 // our file handle and debugserver will go away, and we can be done...
1414 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001415 }
1416 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001417 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001418
1419 StringExtractorGDBRemote response;
1420 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001421 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001422 {
1423 char packet_cmd = response.GetChar(0);
1424
1425 if (packet_cmd == 'W' || packet_cmd == 'X')
1426 {
1427 m_last_stop_packet = response;
1428 SetExitStatus(response.GetHexU8(), NULL);
1429 }
1430 }
1431 else
1432 {
1433 SetExitStatus(SIGABRT, NULL);
1434 //error.SetErrorString("kill packet failed");
1435 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001436 }
1437 }
Chris Lattner24943d22010-06-08 16:52:24 +00001438 StopAsyncThread ();
1439 m_gdb_comm.StopReadThread();
1440 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001441 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001442 return error;
1443}
1444
Chris Lattner24943d22010-06-08 16:52:24 +00001445//------------------------------------------------------------------
1446// Process Queries
1447//------------------------------------------------------------------
1448
1449bool
1450ProcessGDBRemote::IsAlive ()
1451{
Greg Clayton58e844b2010-12-08 05:08:21 +00001452 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001453}
1454
1455addr_t
1456ProcessGDBRemote::GetImageInfoAddress()
1457{
1458 if (!m_gdb_comm.IsRunning())
1459 {
1460 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001461 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001462 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001463 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001464 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1465 }
1466 }
1467 return LLDB_INVALID_ADDRESS;
1468}
1469
Chris Lattner24943d22010-06-08 16:52:24 +00001470//------------------------------------------------------------------
1471// Process Memory
1472//------------------------------------------------------------------
1473size_t
1474ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1475{
1476 if (size > m_max_memory_size)
1477 {
1478 // Keep memory read sizes down to a sane limit. This function will be
1479 // called multiple times in order to complete the task by
1480 // lldb_private::Process so it is ok to do this.
1481 size = m_max_memory_size;
1482 }
1483
1484 char packet[64];
1485 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1486 assert (packet_len + 1 < sizeof(packet));
1487 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001488 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001489 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001490 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001491 {
1492 error.Clear();
1493 return response.GetHexBytes(buf, size, '\xdd');
1494 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001495 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001496 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001497 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001498 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1499 else
1500 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1501 }
1502 else
1503 {
1504 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1505 }
1506 return 0;
1507}
1508
1509size_t
1510ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1511{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001512 if (size > m_max_memory_size)
1513 {
1514 // Keep memory read sizes down to a sane limit. This function will be
1515 // called multiple times in order to complete the task by
1516 // lldb_private::Process so it is ok to do this.
1517 size = m_max_memory_size;
1518 }
1519
Chris Lattner24943d22010-06-08 16:52:24 +00001520 StreamString packet;
1521 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001522 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001523 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001524 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001525 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001526 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001527 {
1528 error.Clear();
1529 return size;
1530 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001531 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001532 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001533 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001534 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1535 else
1536 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1537 }
1538 else
1539 {
1540 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1541 }
1542 return 0;
1543}
1544
1545lldb::addr_t
1546ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1547{
Greg Clayton989816b2011-05-14 01:50:35 +00001548 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1549
Greg Clayton2f085c62011-05-15 01:25:55 +00001550 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001551 switch (supported)
1552 {
1553 case eLazyBoolCalculate:
1554 case eLazyBoolYes:
1555 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1556 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1557 return allocated_addr;
1558
1559 case eLazyBoolNo:
1560 // Call mmap() to create executable memory in the inferior..
1561 {
1562 Thread *thread = GetThreadList().GetSelectedThread().get();
1563 if (thread == NULL)
1564 thread = GetThreadList().GetThreadAtIndex(0).get();
1565
1566 const bool append = true;
1567 const bool include_symbols = true;
1568 SymbolContextList sc_list;
1569 const uint32_t count = m_target.GetImages().FindFunctions (ConstString ("mmap"),
1570 eFunctionNameTypeFull,
1571 include_symbols,
1572 append,
1573 sc_list);
1574 if (count > 0)
1575 {
1576 SymbolContext sc;
1577 if (sc_list.GetContextAtIndex(0, sc))
1578 {
1579 const uint32_t range_scope = eSymbolContextFunction | eSymbolContextSymbol;
1580 const bool use_inline_block_range = false;
1581 const bool stop_other_threads = true;
1582 const bool discard_on_error = true;
1583 const bool try_all_threads = true;
1584 const uint32_t single_thread_timeout_usec = 500000;
1585 addr_t arg1_addr = 0;
1586 addr_t arg2_len = size;
1587 addr_t arg3_prot = PROT_NONE;
Greg Clayton30581972011-05-17 03:51:29 +00001588 addr_t arg4_flags = MAP_ANON | MAP_PRIVATE;
Greg Clayton989816b2011-05-14 01:50:35 +00001589 addr_t arg5_fd = -1;
1590 addr_t arg6_offset = 0;
1591 if (permissions & lldb::ePermissionsReadable)
1592 arg3_prot |= PROT_READ;
1593 if (permissions & lldb::ePermissionsWritable)
1594 arg3_prot |= PROT_WRITE;
1595 if (permissions & lldb::ePermissionsExecutable)
1596 arg3_prot |= PROT_EXEC;
1597
1598 AddressRange mmap_range;
1599 if (sc.GetAddressRange(range_scope, 0, use_inline_block_range, mmap_range))
1600 {
Greg Clayton2f085c62011-05-15 01:25:55 +00001601 ThreadPlanCallFunction *call_function_thread_plan = new ThreadPlanCallFunction (*thread,
1602 mmap_range.GetBaseAddress(),
1603 stop_other_threads,
1604 discard_on_error,
1605 &arg1_addr,
1606 &arg2_len,
1607 &arg3_prot,
1608 &arg4_flags,
1609 &arg5_fd,
1610 &arg6_offset);
1611 lldb::ThreadPlanSP call_plan_sp (call_function_thread_plan);
Greg Clayton989816b2011-05-14 01:50:35 +00001612 if (call_plan_sp)
1613 {
Greg Clayton2f085c62011-05-15 01:25:55 +00001614 ValueSP return_value_sp (new Value);
1615 ClangASTContext *clang_ast_context = m_target.GetScratchClangASTContext();
1616 lldb::clang_type_t clang_void_ptr_type = clang_ast_context->GetVoidPtrType(false);
1617 return_value_sp->SetValueType (Value::eValueTypeScalar);
1618 return_value_sp->SetContext (Value::eContextTypeClangType, clang_void_ptr_type);
1619 call_function_thread_plan->RequestReturnValue (return_value_sp);
1620
Greg Clayton989816b2011-05-14 01:50:35 +00001621 StreamFile error_strm;
1622 StackFrame *frame = thread->GetStackFrameAtIndex (0).get();
1623 if (frame)
1624 {
1625 ExecutionContext exe_ctx;
1626 frame->CalculateExecutionContext (exe_ctx);
Greg Clayton2f085c62011-05-15 01:25:55 +00001627 ExecutionResults result = RunThreadPlan (exe_ctx,
1628 call_plan_sp,
1629 stop_other_threads,
1630 try_all_threads,
1631 discard_on_error,
1632 single_thread_timeout_usec,
1633 error_strm);
1634 if (result == eExecutionCompleted)
1635 {
1636 allocated_addr = return_value_sp->GetScalar().ULongLong();
Greg Clayton9d2b3212011-05-15 23:56:52 +00001637 if (GetAddressByteSize() == 4)
1638 {
1639 if (allocated_addr == UINT32_MAX)
1640 allocated_addr = LLDB_INVALID_ADDRESS;
1641 }
1642 if (allocated_addr != LLDB_INVALID_ADDRESS)
1643 m_addr_to_mmap_size[allocated_addr] = size;
Greg Clayton2f085c62011-05-15 01:25:55 +00001644 }
Greg Clayton989816b2011-05-14 01:50:35 +00001645 }
1646 }
1647 }
1648 }
1649 }
1650 }
1651 break;
1652 }
1653
Chris Lattner24943d22010-06-08 16:52:24 +00001654 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001655 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001656 else
1657 error.Clear();
1658 return allocated_addr;
1659}
1660
1661Error
1662ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1663{
1664 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001665 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1666
1667 switch (supported)
1668 {
1669 case eLazyBoolCalculate:
1670 // We should never be deallocating memory without allocating memory
1671 // first so we should never get eLazyBoolCalculate
1672 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1673 break;
1674
1675 case eLazyBoolYes:
1676 if (!m_gdb_comm.DeallocateMemory (addr))
1677 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1678 break;
1679
1680 case eLazyBoolNo:
1681 // Call munmap() to create executable memory in the inferior..
1682 {
1683 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
1684 if (pos != m_addr_to_mmap_size.end())
1685 {
1686 Thread *thread = GetThreadList().GetSelectedThread().get();
1687 if (thread == NULL)
1688 thread = GetThreadList().GetThreadAtIndex(0).get();
1689
1690 const bool append = true;
1691 const bool include_symbols = true;
1692 SymbolContextList sc_list;
1693 const uint32_t count = m_target.GetImages().FindFunctions (ConstString ("munmap"),
1694 eFunctionNameTypeFull,
1695 include_symbols,
1696 append,
1697 sc_list);
1698 if (count > 0)
1699 {
1700 SymbolContext sc;
1701 if (sc_list.GetContextAtIndex(0, sc))
1702 {
1703 const uint32_t range_scope = eSymbolContextFunction | eSymbolContextSymbol;
1704 const bool use_inline_block_range = false;
1705 const bool stop_other_threads = true;
1706 const bool discard_on_error = true;
1707 const bool try_all_threads = true;
1708 const uint32_t single_thread_timeout_usec = 500000;
1709 addr_t arg1_addr = addr;
1710 addr_t arg2_len = pos->second;
1711
1712 AddressRange munmap_range;
1713 if (sc.GetAddressRange(range_scope, 0, use_inline_block_range, munmap_range))
1714 {
1715 lldb::ThreadPlanSP call_plan_sp (new ThreadPlanCallFunction (*thread,
1716 munmap_range.GetBaseAddress(),
1717 stop_other_threads,
1718 discard_on_error,
1719 &arg1_addr,
1720 &arg2_len));
1721 if (call_plan_sp)
1722 {
1723 StreamFile error_strm;
1724 StackFrame *frame = thread->GetStackFrameAtIndex (0).get();
1725 if (frame)
1726 {
1727 ExecutionContext exe_ctx;
1728 frame->CalculateExecutionContext (exe_ctx);
1729 ExecutionResults result = RunThreadPlan (exe_ctx,
1730 call_plan_sp,
1731 stop_other_threads,
1732 try_all_threads,
1733 discard_on_error,
1734 single_thread_timeout_usec,
1735 error_strm);
1736 if (result == eExecutionCompleted)
1737 {
1738 m_addr_to_mmap_size.erase (pos);
1739 }
1740 }
1741 }
1742 }
1743 }
1744 }
1745 }
1746 }
1747 break;
1748 }
1749
Chris Lattner24943d22010-06-08 16:52:24 +00001750 return error;
1751}
1752
1753
1754//------------------------------------------------------------------
1755// Process STDIO
1756//------------------------------------------------------------------
1757
1758size_t
1759ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1760{
1761 Mutex::Locker locker(m_stdio_mutex);
1762 size_t bytes_available = m_stdout_data.size();
1763 if (bytes_available > 0)
1764 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001765 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1766 if (log)
1767 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001768 if (bytes_available > buf_size)
1769 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001770 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001771 m_stdout_data.erase(0, buf_size);
1772 bytes_available = buf_size;
1773 }
1774 else
1775 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001776 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001777 m_stdout_data.clear();
1778
1779 //ResetEventBits(eBroadcastBitSTDOUT);
1780 }
1781 }
1782 return bytes_available;
1783}
1784
1785size_t
1786ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1787{
1788 // Can we get STDERR through the remote protocol?
1789 return 0;
1790}
1791
1792size_t
1793ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1794{
1795 if (m_stdio_communication.IsConnected())
1796 {
1797 ConnectionStatus status;
1798 m_stdio_communication.Write(src, src_len, status, NULL);
1799 }
1800 return 0;
1801}
1802
1803Error
1804ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1805{
1806 Error error;
1807 assert (bp_site != NULL);
1808
Greg Claytone005f2c2010-11-06 01:53:30 +00001809 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001810 user_id_t site_id = bp_site->GetID();
1811 const addr_t addr = bp_site->GetLoadAddress();
1812 if (log)
1813 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1814
1815 if (bp_site->IsEnabled())
1816 {
1817 if (log)
1818 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1819 return error;
1820 }
1821 else
1822 {
1823 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1824
1825 if (bp_site->HardwarePreferred())
1826 {
1827 // Try and set hardware breakpoint, and if that fails, fall through
1828 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001829 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001830 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001831 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001832 {
1833 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001834 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001835 return error;
1836 }
Chris Lattner24943d22010-06-08 16:52:24 +00001837 }
1838 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001839
1840 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001841 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001842 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1843 {
1844 bp_site->SetEnabled(true);
1845 bp_site->SetType (BreakpointSite::eExternal);
1846 return error;
1847 }
Chris Lattner24943d22010-06-08 16:52:24 +00001848 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001849
1850 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001851 }
1852
1853 if (log)
1854 {
1855 const char *err_string = error.AsCString();
1856 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1857 bp_site->GetLoadAddress(),
1858 err_string ? err_string : "NULL");
1859 }
1860 // We shouldn't reach here on a successful breakpoint enable...
1861 if (error.Success())
1862 error.SetErrorToGenericError();
1863 return error;
1864}
1865
1866Error
1867ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1868{
1869 Error error;
1870 assert (bp_site != NULL);
1871 addr_t addr = bp_site->GetLoadAddress();
1872 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001873 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001874 if (log)
1875 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1876
1877 if (bp_site->IsEnabled())
1878 {
1879 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1880
Greg Claytonb72d0f02011-04-12 05:54:46 +00001881 BreakpointSite::Type bp_type = bp_site->GetType();
1882 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001883 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001884 case BreakpointSite::eSoftware:
1885 error = DisableSoftwareBreakpoint (bp_site);
1886 break;
1887
1888 case BreakpointSite::eHardware:
1889 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1890 error.SetErrorToGenericError();
1891 break;
1892
1893 case BreakpointSite::eExternal:
1894 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1895 error.SetErrorToGenericError();
1896 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001897 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001898 if (error.Success())
1899 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001900 }
1901 else
1902 {
1903 if (log)
1904 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1905 return error;
1906 }
1907
1908 if (error.Success())
1909 error.SetErrorToGenericError();
1910 return error;
1911}
1912
1913Error
1914ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1915{
1916 Error error;
1917 if (wp)
1918 {
1919 user_id_t watchID = wp->GetID();
1920 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001921 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001922 if (log)
1923 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1924 if (wp->IsEnabled())
1925 {
1926 if (log)
1927 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1928 return error;
1929 }
1930 else
1931 {
1932 // Pass down an appropriate z/Z packet...
1933 error.SetErrorString("watchpoints not supported");
1934 }
1935 }
1936 else
1937 {
1938 error.SetErrorString("Watchpoint location argument was NULL.");
1939 }
1940 if (error.Success())
1941 error.SetErrorToGenericError();
1942 return error;
1943}
1944
1945Error
1946ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1947{
1948 Error error;
1949 if (wp)
1950 {
1951 user_id_t watchID = wp->GetID();
1952
Greg Claytone005f2c2010-11-06 01:53:30 +00001953 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001954
1955 addr_t addr = wp->GetLoadAddress();
1956 if (log)
1957 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1958
1959 if (wp->IsHardware())
1960 {
1961 // Pass down an appropriate z/Z packet...
1962 error.SetErrorString("watchpoints not supported");
1963 }
1964 // TODO: clear software watchpoints if we implement them
1965 }
1966 else
1967 {
1968 error.SetErrorString("Watchpoint location argument was NULL.");
1969 }
1970 if (error.Success())
1971 error.SetErrorToGenericError();
1972 return error;
1973}
1974
1975void
1976ProcessGDBRemote::Clear()
1977{
1978 m_flags = 0;
1979 m_thread_list.Clear();
1980 {
1981 Mutex::Locker locker(m_stdio_mutex);
1982 m_stdout_data.clear();
1983 }
Chris Lattner24943d22010-06-08 16:52:24 +00001984}
1985
1986Error
1987ProcessGDBRemote::DoSignal (int signo)
1988{
1989 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001990 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001991 if (log)
1992 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1993
1994 if (!m_gdb_comm.SendAsyncSignal (signo))
1995 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1996 return error;
1997}
1998
Chris Lattner24943d22010-06-08 16:52:24 +00001999Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002000ProcessGDBRemote::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 +00002001{
2002 Error error;
2003 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2004 {
2005 // If we locate debugserver, keep that located version around
2006 static FileSpec g_debugserver_file_spec;
2007
Greg Claytonb72d0f02011-04-12 05:54:46 +00002008 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002009 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002010 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002011
2012 // Always check to see if we have an environment override for the path
2013 // to the debugserver to use and use it if we do.
2014 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2015 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002016 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002017 else
2018 debugserver_file_spec = g_debugserver_file_spec;
2019 bool debugserver_exists = debugserver_file_spec.Exists();
2020 if (!debugserver_exists)
2021 {
2022 // The debugserver binary is in the LLDB.framework/Resources
2023 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002024 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002025 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002026 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002027 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002028 if (debugserver_exists)
2029 {
2030 g_debugserver_file_spec = debugserver_file_spec;
2031 }
2032 else
2033 {
2034 g_debugserver_file_spec.Clear();
2035 debugserver_file_spec.Clear();
2036 }
Chris Lattner24943d22010-06-08 16:52:24 +00002037 }
2038 }
2039
2040 if (debugserver_exists)
2041 {
2042 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2043
2044 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002045
Greg Claytone005f2c2010-11-06 01:53:30 +00002046 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002047
Greg Claytonb72d0f02011-04-12 05:54:46 +00002048 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002049 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002050
Chris Lattner24943d22010-06-08 16:52:24 +00002051 // Start args with "debugserver /file/path -r --"
2052 debugserver_args.AppendArgument(debugserver_path);
2053 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002054 // use native registers, not the GDB registers
2055 debugserver_args.AppendArgument("--native-regs");
2056 // make debugserver run in its own session so signals generated by
2057 // special terminal key sequences (^C) don't affect debugserver
2058 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002059
Chris Lattner24943d22010-06-08 16:52:24 +00002060 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2061 if (env_debugserver_log_file)
2062 {
2063 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2064 debugserver_args.AppendArgument(arg_cstr);
2065 }
2066
2067 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2068 if (env_debugserver_log_flags)
2069 {
2070 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2071 debugserver_args.AppendArgument(arg_cstr);
2072 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002073// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002074// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002075
Greg Claytonb72d0f02011-04-12 05:54:46 +00002076 // We currently send down all arguments, attach pids, or attach
2077 // process names in dedicated GDB server packets, so we don't need
2078 // to pass them as arguments. This is currently because of all the
2079 // things we need to setup prior to launching: the environment,
2080 // current working dir, file actions, etc.
2081#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002082 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002083 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002084 {
Greg Claytona2f74232011-02-24 22:24:29 +00002085 // Terminate the debugserver args so we can now append the inferior args
2086 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002087
Greg Claytona2f74232011-02-24 22:24:29 +00002088 for (int i = 0; inferior_argv[i] != NULL; ++i)
2089 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002090 }
2091 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2092 {
2093 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2094 debugserver_args.AppendArgument (arg_cstr);
2095 }
2096 else if (attach_name && attach_name[0])
2097 {
2098 if (wait_for_launch)
2099 debugserver_args.AppendArgument ("--waitfor");
2100 else
2101 debugserver_args.AppendArgument ("--attach");
2102 debugserver_args.AppendArgument (attach_name);
2103 }
Chris Lattner24943d22010-06-08 16:52:24 +00002104#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002105
2106 ProcessLaunchInfo::FileAction file_action;
2107
2108 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2109 // to "/dev/null" if we run into any problems.
2110 file_action.Close (STDIN_FILENO);
2111 launch_info.AppendFileAction (file_action);
2112 file_action.Close (STDOUT_FILENO);
2113 launch_info.AppendFileAction (file_action);
2114 file_action.Close (STDERR_FILENO);
2115 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002116
2117 if (log)
2118 {
2119 StreamString strm;
2120 debugserver_args.Dump (&strm);
2121 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2122 }
2123
Greg Claytonb72d0f02011-04-12 05:54:46 +00002124 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002125
Greg Claytonb72d0f02011-04-12 05:54:46 +00002126 if (error.Success ())
2127 m_debugserver_pid = launch_info.GetProcessID();
2128 else
Chris Lattner24943d22010-06-08 16:52:24 +00002129 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2130
2131 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002132 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002133 }
2134 else
2135 {
2136 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2137 }
2138
2139 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2140 StartAsyncThread ();
2141 }
2142 return error;
2143}
2144
2145bool
2146ProcessGDBRemote::MonitorDebugserverProcess
2147(
2148 void *callback_baton,
2149 lldb::pid_t debugserver_pid,
2150 int signo, // Zero for no signal
2151 int exit_status // Exit value of process if signal is zero
2152)
2153{
2154 // We pass in the ProcessGDBRemote inferior process it and name it
2155 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2156 // pointer value itself, thus we need the double cast...
2157
2158 // "debugserver_pid" argument passed in is the process ID for
2159 // debugserver that we are tracking...
2160
Greg Clayton75ccf502010-08-21 02:22:51 +00002161 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002162
2163 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2164 if (log)
2165 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2166
Greg Clayton75ccf502010-08-21 02:22:51 +00002167 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002168 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002169 // Sleep for a half a second to make sure our inferior process has
2170 // time to set its exit status before we set it incorrectly when
2171 // both the debugserver and the inferior process shut down.
2172 usleep (500000);
2173 // If our process hasn't yet exited, debugserver might have died.
2174 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002175 const StateType state = process->GetState();
2176
2177 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2178 state != eStateInvalid &&
2179 state != eStateUnloaded &&
2180 state != eStateExited &&
2181 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002182 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002183 char error_str[1024];
2184 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002185 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002186 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2187 if (signal_cstr)
2188 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002189 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002190 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002191 }
2192 else
2193 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002194 ::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 +00002195 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002196
2197 process->SetExitStatus (-1, error_str);
2198 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002199 // Debugserver has exited we need to let our ProcessGDBRemote
2200 // know that it no longer has a debugserver instance
2201 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2202 // We are returning true to this function below, so we can
2203 // forget about the monitor handle.
2204 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002205 }
2206 return true;
2207}
2208
2209void
2210ProcessGDBRemote::KillDebugserverProcess ()
2211{
2212 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2213 {
2214 ::kill (m_debugserver_pid, SIGINT);
2215 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2216 }
2217}
2218
2219void
2220ProcessGDBRemote::Initialize()
2221{
2222 static bool g_initialized = false;
2223
2224 if (g_initialized == false)
2225 {
2226 g_initialized = true;
2227 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2228 GetPluginDescriptionStatic(),
2229 CreateInstance);
2230
2231 Log::Callbacks log_callbacks = {
2232 ProcessGDBRemoteLog::DisableLog,
2233 ProcessGDBRemoteLog::EnableLog,
2234 ProcessGDBRemoteLog::ListLogCategories
2235 };
2236
2237 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2238 }
2239}
2240
2241bool
Chris Lattner24943d22010-06-08 16:52:24 +00002242ProcessGDBRemote::StartAsyncThread ()
2243{
Greg Claytone005f2c2010-11-06 01:53:30 +00002244 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002245
2246 if (log)
2247 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2248
2249 // Create a thread that watches our internal state and controls which
2250 // events make it to clients (into the DCProcess event queue).
2251 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002252 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002253}
2254
2255void
2256ProcessGDBRemote::StopAsyncThread ()
2257{
Greg Claytone005f2c2010-11-06 01:53:30 +00002258 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002259
2260 if (log)
2261 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2262
2263 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2264
2265 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002266 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002267 {
2268 Host::ThreadJoin (m_async_thread, NULL, NULL);
2269 }
2270}
2271
2272
2273void *
2274ProcessGDBRemote::AsyncThread (void *arg)
2275{
2276 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2277
Greg Claytone005f2c2010-11-06 01:53:30 +00002278 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002279 if (log)
2280 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2281
2282 Listener listener ("ProcessGDBRemote::AsyncThread");
2283 EventSP event_sp;
2284 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2285 eBroadcastBitAsyncThreadShouldExit;
2286
2287 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2288 {
Greg Claytona2f74232011-02-24 22:24:29 +00002289 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2290
Chris Lattner24943d22010-06-08 16:52:24 +00002291 bool done = false;
2292 while (!done)
2293 {
2294 if (log)
2295 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2296 if (listener.WaitForEvent (NULL, event_sp))
2297 {
2298 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002299 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002300 {
Greg Claytona2f74232011-02-24 22:24:29 +00002301 if (log)
2302 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 +00002303
Greg Claytona2f74232011-02-24 22:24:29 +00002304 switch (event_type)
2305 {
2306 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002307 {
Greg Claytona2f74232011-02-24 22:24:29 +00002308 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002309
Greg Claytona2f74232011-02-24 22:24:29 +00002310 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002311 {
Greg Claytona2f74232011-02-24 22:24:29 +00002312 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2313 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2314 if (log)
2315 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002316
Greg Claytona2f74232011-02-24 22:24:29 +00002317 if (::strstr (continue_cstr, "vAttach") == NULL)
2318 process->SetPrivateState(eStateRunning);
2319 StringExtractorGDBRemote response;
2320 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002321
Greg Claytona2f74232011-02-24 22:24:29 +00002322 switch (stop_state)
2323 {
2324 case eStateStopped:
2325 case eStateCrashed:
2326 case eStateSuspended:
2327 process->m_last_stop_packet = response;
2328 process->m_last_stop_packet.SetFilePos (0);
2329 process->SetPrivateState (stop_state);
2330 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002331
Greg Claytona2f74232011-02-24 22:24:29 +00002332 case eStateExited:
2333 process->m_last_stop_packet = response;
2334 process->m_last_stop_packet.SetFilePos (0);
2335 response.SetFilePos(1);
2336 process->SetExitStatus(response.GetHexU8(), NULL);
2337 done = true;
2338 break;
2339
2340 case eStateInvalid:
2341 process->SetExitStatus(-1, "lost connection");
2342 break;
2343
2344 default:
2345 process->SetPrivateState (stop_state);
2346 break;
2347 }
Chris Lattner24943d22010-06-08 16:52:24 +00002348 }
2349 }
Greg Claytona2f74232011-02-24 22:24:29 +00002350 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002351
Greg Claytona2f74232011-02-24 22:24:29 +00002352 case eBroadcastBitAsyncThreadShouldExit:
2353 if (log)
2354 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2355 done = true;
2356 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002357
Greg Claytona2f74232011-02-24 22:24:29 +00002358 default:
2359 if (log)
2360 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2361 done = true;
2362 break;
2363 }
2364 }
2365 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2366 {
2367 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2368 {
2369 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002370 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002371 }
Chris Lattner24943d22010-06-08 16:52:24 +00002372 }
2373 }
2374 else
2375 {
2376 if (log)
2377 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2378 done = true;
2379 }
2380 }
2381 }
2382
2383 if (log)
2384 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2385
2386 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2387 return NULL;
2388}
2389
Chris Lattner24943d22010-06-08 16:52:24 +00002390const char *
2391ProcessGDBRemote::GetDispatchQueueNameForThread
2392(
2393 addr_t thread_dispatch_qaddr,
2394 std::string &dispatch_queue_name
2395)
2396{
2397 dispatch_queue_name.clear();
2398 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2399 {
2400 // Cache the dispatch_queue_offsets_addr value so we don't always have
2401 // to look it up
2402 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2403 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002404 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2405 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002406 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002407 if (module_sp)
2408 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2409
2410 if (dispatch_queue_offsets_symbol == NULL)
2411 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002412 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002413 if (module_sp)
2414 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2415 }
Chris Lattner24943d22010-06-08 16:52:24 +00002416 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002417 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002418
2419 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2420 return NULL;
2421 }
2422
2423 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002424 DataExtractor data (memory_buffer,
2425 sizeof(memory_buffer),
2426 m_target.GetArchitecture().GetByteOrder(),
2427 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002428
2429 // Excerpt from src/queue_private.h
2430 struct dispatch_queue_offsets_s
2431 {
2432 uint16_t dqo_version;
2433 uint16_t dqo_label;
2434 uint16_t dqo_label_size;
2435 } dispatch_queue_offsets;
2436
2437
2438 Error error;
2439 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2440 {
2441 uint32_t data_offset = 0;
2442 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2443 {
2444 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2445 {
2446 data_offset = 0;
2447 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2448 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2449 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2450 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2451 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2452 dispatch_queue_name.erase (bytes_read);
2453 }
2454 }
2455 }
2456 }
2457 if (dispatch_queue_name.empty())
2458 return NULL;
2459 return dispatch_queue_name.c_str();
2460}
2461
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002462//uint32_t
2463//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2464//{
2465// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2466// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2467// if (m_local_debugserver)
2468// {
2469// return Host::ListProcessesMatchingName (name, matches, pids);
2470// }
2471// else
2472// {
2473// // FIXME: Implement talking to the remote debugserver.
2474// return 0;
2475// }
2476//
2477//}
2478//
Jim Ingham55e01d82011-01-22 01:33:44 +00002479bool
2480ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2481 lldb_private::StoppointCallbackContext *context,
2482 lldb::user_id_t break_id,
2483 lldb::user_id_t break_loc_id)
2484{
2485 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2486 // run so I can stop it if that's what I want to do.
2487 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2488 if (log)
2489 log->Printf("Hit New Thread Notification breakpoint.");
2490 return false;
2491}
2492
2493
2494bool
2495ProcessGDBRemote::StartNoticingNewThreads()
2496{
2497 static const char *bp_names[] =
2498 {
2499 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002500 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002501 "_pthread_start",
2502 NULL
2503 };
2504
2505 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2506 size_t num_bps = m_thread_observation_bps.size();
2507 if (num_bps != 0)
2508 {
2509 for (int i = 0; i < num_bps; i++)
2510 {
2511 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2512 if (break_sp)
2513 {
2514 if (log)
2515 log->Printf("Enabled noticing new thread breakpoint.");
2516 break_sp->SetEnabled(true);
2517 }
2518 }
2519 }
2520 else
2521 {
2522 for (int i = 0; bp_names[i] != NULL; i++)
2523 {
2524 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2525 if (breakpoint)
2526 {
2527 if (log)
2528 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2529 m_thread_observation_bps.push_back(breakpoint->GetID());
2530 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2531 }
2532 else
2533 {
2534 if (log)
2535 log->Printf("Failed to create new thread notification breakpoint.");
2536 return false;
2537 }
2538 }
2539 }
2540
2541 return true;
2542}
2543
2544bool
2545ProcessGDBRemote::StopNoticingNewThreads()
2546{
Jim Inghamff276fe2011-02-08 05:19:01 +00002547 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2548 if (log)
2549 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002550 size_t num_bps = m_thread_observation_bps.size();
2551 if (num_bps != 0)
2552 {
2553 for (int i = 0; i < num_bps; i++)
2554 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002555
2556 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2557 if (break_sp)
2558 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002559 break_sp->SetEnabled(false);
2560 }
2561 }
2562 }
2563 return true;
2564}
2565
2566