blob: 6ba0bd28b0bd75b2a512c8cd9b1a9a34513d0d70 [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"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000048#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000049#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000050#include "GDBRemoteRegisterContext.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000054#include "StopInfoMachException.h"
55
Chris Lattner24943d22010-06-08 16:52:24 +000056
Chris Lattner24943d22010-06-08 16:52:24 +000057
58#define DEBUGSERVER_BASENAME "debugserver"
59using namespace lldb;
60using namespace lldb_private;
61
Jim Inghamf9600482011-03-29 21:45:47 +000062static bool rand_initialized = false;
63
Chris Lattner24943d22010-06-08 16:52:24 +000064static inline uint16_t
65get_random_port ()
66{
Jim Inghamf9600482011-03-29 21:45:47 +000067 if (!rand_initialized)
68 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000069 time_t seed = time(NULL);
70
Jim Inghamf9600482011-03-29 21:45:47 +000071 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000072 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000073 }
Stephen Wilson50daf772011-03-25 18:16:28 +000074 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000075}
76
77
78const char *
79ProcessGDBRemote::GetPluginNameStatic()
80{
Greg Claytonb1888f22011-03-19 01:12:21 +000081 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000082}
83
84const char *
85ProcessGDBRemote::GetPluginDescriptionStatic()
86{
87 return "GDB Remote protocol based debugging plug-in.";
88}
89
90void
91ProcessGDBRemote::Terminate()
92{
93 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
94}
95
96
97Process*
98ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
99{
100 return new ProcessGDBRemote (target, listener);
101}
102
103bool
104ProcessGDBRemote::CanDebug(Target &target)
105{
106 // For now we are just making sure the file exists for a given module
107 ModuleSP exe_module_sp(target.GetExecutableModule());
108 if (exe_module_sp.get())
109 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000110 // However, if there is no executable module, we return true since we might be preparing to attach.
111 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000112}
113
114//----------------------------------------------------------------------
115// ProcessGDBRemote constructor
116//----------------------------------------------------------------------
117ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
118 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000119 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000120 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000121 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000123 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000124 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000125 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000126 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
127 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000128 m_continue_c_tids (),
129 m_continue_C_tids (),
130 m_continue_s_tids (),
131 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000132 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000133 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000134 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000135 m_local_debugserver (true),
136 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000137{
Greg Claytonff39f742011-04-01 00:29:43 +0000138 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
139 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000140}
141
142//----------------------------------------------------------------------
143// Destructor
144//----------------------------------------------------------------------
145ProcessGDBRemote::~ProcessGDBRemote()
146{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000147 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000148 {
149 Host::ThreadCancel (m_debugserver_thread, NULL);
150 thread_result_t thread_result;
151 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
152 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
153 }
Chris Lattner24943d22010-06-08 16:52:24 +0000154 // m_mach_process.UnregisterNotificationCallbacks (this);
155 Clear();
156}
157
158//----------------------------------------------------------------------
159// PluginInterface
160//----------------------------------------------------------------------
161const char *
162ProcessGDBRemote::GetPluginName()
163{
164 return "Process debugging plug-in that uses the GDB remote protocol";
165}
166
167const char *
168ProcessGDBRemote::GetShortPluginName()
169{
170 return GetPluginNameStatic();
171}
172
173uint32_t
174ProcessGDBRemote::GetPluginVersion()
175{
176 return 1;
177}
178
179void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000180ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000181{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000182 if (!force && m_register_info.GetNumRegisters() > 0)
183 return;
184
185 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000186 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000187 uint32_t reg_offset = 0;
188 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000189 StringExtractorGDBRemote::ResponseType response_type;
190 for (response_type = StringExtractorGDBRemote::eResponse;
191 response_type == StringExtractorGDBRemote::eResponse;
192 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000193 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000194 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
195 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000196 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000197 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000198 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000199 response_type = response.GetResponseType();
200 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000201 {
202 std::string name;
203 std::string value;
204 ConstString reg_name;
205 ConstString alt_name;
206 ConstString set_name;
207 RegisterInfo reg_info = { NULL, // Name
208 NULL, // Alt name
209 0, // byte size
210 reg_offset, // offset
211 eEncodingUint, // encoding
212 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000213 {
214 LLDB_INVALID_REGNUM, // GCC reg num
215 LLDB_INVALID_REGNUM, // DWARF reg num
216 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000217 reg_num, // GDB reg num
218 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000219 }
220 };
221
222 while (response.GetNameColonValue(name, value))
223 {
224 if (name.compare("name") == 0)
225 {
226 reg_name.SetCString(value.c_str());
227 }
228 else if (name.compare("alt-name") == 0)
229 {
230 alt_name.SetCString(value.c_str());
231 }
232 else if (name.compare("bitsize") == 0)
233 {
234 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
235 }
236 else if (name.compare("offset") == 0)
237 {
238 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000239 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000240 {
241 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000242 }
243 }
244 else if (name.compare("encoding") == 0)
245 {
246 if (value.compare("uint") == 0)
247 reg_info.encoding = eEncodingUint;
248 else if (value.compare("sint") == 0)
249 reg_info.encoding = eEncodingSint;
250 else if (value.compare("ieee754") == 0)
251 reg_info.encoding = eEncodingIEEE754;
252 else if (value.compare("vector") == 0)
253 reg_info.encoding = eEncodingVector;
254 }
255 else if (name.compare("format") == 0)
256 {
257 if (value.compare("binary") == 0)
258 reg_info.format = eFormatBinary;
259 else if (value.compare("decimal") == 0)
260 reg_info.format = eFormatDecimal;
261 else if (value.compare("hex") == 0)
262 reg_info.format = eFormatHex;
263 else if (value.compare("float") == 0)
264 reg_info.format = eFormatFloat;
265 else if (value.compare("vector-sint8") == 0)
266 reg_info.format = eFormatVectorOfSInt8;
267 else if (value.compare("vector-uint8") == 0)
268 reg_info.format = eFormatVectorOfUInt8;
269 else if (value.compare("vector-sint16") == 0)
270 reg_info.format = eFormatVectorOfSInt16;
271 else if (value.compare("vector-uint16") == 0)
272 reg_info.format = eFormatVectorOfUInt16;
273 else if (value.compare("vector-sint32") == 0)
274 reg_info.format = eFormatVectorOfSInt32;
275 else if (value.compare("vector-uint32") == 0)
276 reg_info.format = eFormatVectorOfUInt32;
277 else if (value.compare("vector-float32") == 0)
278 reg_info.format = eFormatVectorOfFloat32;
279 else if (value.compare("vector-uint128") == 0)
280 reg_info.format = eFormatVectorOfUInt128;
281 }
282 else if (name.compare("set") == 0)
283 {
284 set_name.SetCString(value.c_str());
285 }
286 else if (name.compare("gcc") == 0)
287 {
288 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
289 }
290 else if (name.compare("dwarf") == 0)
291 {
292 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
293 }
294 else if (name.compare("generic") == 0)
295 {
296 if (value.compare("pc") == 0)
297 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
298 else if (value.compare("sp") == 0)
299 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
300 else if (value.compare("fp") == 0)
301 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
302 else if (value.compare("ra") == 0)
303 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
304 else if (value.compare("flags") == 0)
305 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000306 else if (value.find("arg") == 0)
307 {
308 if (value.size() == 4)
309 {
310 switch (value[3])
311 {
312 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
313 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
314 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
315 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
316 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
317 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
318 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
319 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
320 }
321 }
322 }
Chris Lattner24943d22010-06-08 16:52:24 +0000323 }
324 }
325
Jason Molenda53d96862010-06-11 23:44:18 +0000326 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000327 assert (reg_info.byte_size != 0);
328 reg_offset += reg_info.byte_size;
329 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
330 }
331 }
332 else
333 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000334 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000335 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000336 }
337 }
338
339 if (reg_num == 0)
340 {
341 // We didn't get anything. See if we are debugging ARM and fill with
342 // a hard coded register set until we can get an updated debugserver
343 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000344 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000345 m_register_info.HardcodeARMRegisters();
346 }
347 m_register_info.Finalize ();
348}
349
350Error
351ProcessGDBRemote::WillLaunch (Module* module)
352{
353 return WillLaunchOrAttach ();
354}
355
356Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000357ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000358{
359 return WillLaunchOrAttach ();
360}
361
362Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000363ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000364{
365 return WillLaunchOrAttach ();
366}
367
368Error
Greg Claytone71e2582011-02-04 01:58:07 +0000369ProcessGDBRemote::DoConnectRemote (const char *remote_url)
370{
371 Error error (WillLaunchOrAttach ());
372
373 if (error.Fail())
374 return error;
375
Greg Clayton180546b2011-04-30 01:09:13 +0000376 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000377
378 if (error.Fail())
379 return error;
380 StartAsyncThread ();
381
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000382 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000383 if (pid == LLDB_INVALID_PROCESS_ID)
384 {
385 // We don't have a valid process ID, so note that we are connected
386 // and could now request to launch or attach, or get remote process
387 // listings...
388 SetPrivateState (eStateConnected);
389 }
390 else
391 {
392 // We have a valid process
393 SetID (pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000394 UpdateThreadListIfNeeded ();
Greg Clayton261a18b2011-06-02 22:22:38 +0000395 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000396 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000397 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000398 if (state == eStateStopped)
399 {
400 SetPrivateState (state);
401 }
402 else
403 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
404 }
405 else
406 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
407 }
408 return error;
409}
410
411Error
Chris Lattner24943d22010-06-08 16:52:24 +0000412ProcessGDBRemote::WillLaunchOrAttach ()
413{
414 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000415 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000416 return error;
417}
418
419//----------------------------------------------------------------------
420// Process Control
421//----------------------------------------------------------------------
422Error
423ProcessGDBRemote::DoLaunch
424(
425 Module* module,
426 char const *argv[],
427 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000428 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000429 const char *stdin_path,
430 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000431 const char *stderr_path,
432 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000433)
434{
Greg Clayton4b407112010-09-30 21:49:03 +0000435 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000436 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
437 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
438 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000439
440 ObjectFile * object_file = module->GetObjectFile();
441 if (object_file)
442 {
Chris Lattner24943d22010-06-08 16:52:24 +0000443 char host_port[128];
444 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000445 char connect_url[128];
446 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000447
Greg Claytona2f74232011-02-24 22:24:29 +0000448 // Make sure we aren't already connected?
449 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000450 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000451 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000452 if (error.Fail())
453 return error;
454
Greg Claytone71e2582011-02-04 01:58:07 +0000455 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000456 }
457
458 if (error.Success())
459 {
460 lldb_utility::PseudoTerminal pty;
461 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000462
463 // If the debugserver is local and we aren't disabling STDIO, lets use
464 // a pseudo terminal to instead of relying on the 'O' packets for stdio
465 // since 'O' packets can really slow down debugging if the inferior
466 // does a lot of output.
467 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000468 {
469 const char *slave_name = NULL;
470 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000471 {
Greg Claytona2f74232011-02-24 22:24:29 +0000472 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
473 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000474 }
Greg Claytona2f74232011-02-24 22:24:29 +0000475 if (stdin_path == NULL)
476 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000477
Greg Claytona2f74232011-02-24 22:24:29 +0000478 if (stdout_path == NULL)
479 stdout_path = slave_name;
480
481 if (stderr_path == NULL)
482 stderr_path = slave_name;
483 }
484
Greg Claytonafb81862011-03-02 21:34:46 +0000485 // Set STDIN to /dev/null if we want STDIO disabled or if either
486 // STDOUT or STDERR have been set to something and STDIN hasn't
487 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000488 stdin_path = "/dev/null";
489
Greg Claytonafb81862011-03-02 21:34:46 +0000490 // Set STDOUT to /dev/null if we want STDIO disabled or if either
491 // STDIN or STDERR have been set to something and STDOUT hasn't
492 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000493 stdout_path = "/dev/null";
494
Greg Claytonafb81862011-03-02 21:34:46 +0000495 // Set STDERR to /dev/null if we want STDIO disabled or if either
496 // STDIN or STDOUT have been set to something and STDERR hasn't
497 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000498 stderr_path = "/dev/null";
499
500 if (stdin_path)
501 m_gdb_comm.SetSTDIN (stdin_path);
502 if (stdout_path)
503 m_gdb_comm.SetSTDOUT (stdout_path);
504 if (stderr_path)
505 m_gdb_comm.SetSTDERR (stderr_path);
506
507 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
508
Greg Claytona4582402011-05-08 04:53:50 +0000509 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000510
511 if (working_dir && working_dir[0])
512 {
513 m_gdb_comm.SetWorkingDir (working_dir);
514 }
515
516 // Send the environment and the program + arguments after we connect
517 if (envp)
518 {
519 const char *env_entry;
520 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000521 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000522 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000523 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000524 }
Greg Claytona2f74232011-02-24 22:24:29 +0000525 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000526
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000527 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
528 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
529 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000530 if (arg_packet_err == 0)
531 {
532 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000533 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000534 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000535 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000536 }
537 else
538 {
Greg Claytona2f74232011-02-24 22:24:29 +0000539 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000540 }
Greg Claytona2f74232011-02-24 22:24:29 +0000541 }
542 else
543 {
544 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
545 }
Chris Lattner24943d22010-06-08 16:52:24 +0000546
Greg Claytona2f74232011-02-24 22:24:29 +0000547 if (GetID() == LLDB_INVALID_PROCESS_ID)
548 {
549 KillDebugserverProcess ();
550 return error;
551 }
552
Greg Clayton261a18b2011-06-02 22:22:38 +0000553 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000554 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000555 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000556
557 if (!disable_stdio)
558 {
559 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
560 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
561 }
Chris Lattner24943d22010-06-08 16:52:24 +0000562 }
563 }
Chris Lattner24943d22010-06-08 16:52:24 +0000564 }
565 else
566 {
567 // Set our user ID to an invalid process ID.
568 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000569 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
570 module->GetFileSpec().GetFilename().AsCString(),
571 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000572 }
Chris Lattner24943d22010-06-08 16:52:24 +0000573 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000574
Chris Lattner24943d22010-06-08 16:52:24 +0000575}
576
577
578Error
Greg Claytone71e2582011-02-04 01:58:07 +0000579ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000580{
581 Error error;
582 // Sleep and wait a bit for debugserver to start to listen...
583 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
584 if (conn_ap.get())
585 {
Chris Lattner24943d22010-06-08 16:52:24 +0000586 const uint32_t max_retry_count = 50;
587 uint32_t retry_count = 0;
588 while (!m_gdb_comm.IsConnected())
589 {
Greg Claytone71e2582011-02-04 01:58:07 +0000590 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000591 {
592 m_gdb_comm.SetConnection (conn_ap.release());
593 break;
594 }
595 retry_count++;
596
597 if (retry_count >= max_retry_count)
598 break;
599
600 usleep (100000);
601 }
602 }
603
604 if (!m_gdb_comm.IsConnected())
605 {
606 if (error.Success())
607 error.SetErrorString("not connected to remote gdb server");
608 return error;
609 }
610
Greg Clayton24bc5d92011-03-30 18:16:51 +0000611 // We always seem to be able to open a connection to a local port
612 // so we need to make sure we can then send data to it. If we can't
613 // then we aren't actually connected to anything, so try and do the
614 // handshake with the remote GDB server and make sure that goes
615 // alright.
616 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000617 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000618 m_gdb_comm.Disconnect();
619 if (error.Success())
620 error.SetErrorString("not connected to remote gdb server");
621 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000622 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000623 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
624 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
625 this,
626 m_debugserver_pid,
627 false);
628 m_gdb_comm.ResetDiscoverableSettings();
629 m_gdb_comm.QueryNoAckModeSupported ();
630 m_gdb_comm.GetThreadSuffixSupported ();
631 m_gdb_comm.GetHostInfo ();
632 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000633 return error;
634}
635
636void
637ProcessGDBRemote::DidLaunchOrAttach ()
638{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000639 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
640 if (log)
641 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000642 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000643 {
644 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
645
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000646 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000647
Chris Lattner24943d22010-06-08 16:52:24 +0000648 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000649
Greg Claytoncb8977d2011-03-23 00:09:55 +0000650 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
651 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000652 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000653 ArchSpec &target_arch = GetTarget().GetArchitecture();
654
655 if (target_arch.IsValid())
656 {
657 // If the remote host is ARM and we have apple as the vendor, then
658 // ARM executables and shared libraries can have mixed ARM architectures.
659 // You can have an armv6 executable, and if the host is armv7, then the
660 // system will load the best possible architecture for all shared libraries
661 // it has, so we really need to take the remote host architecture as our
662 // defacto architecture in this case.
663
664 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
665 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
666 {
667 target_arch = gdb_remote_arch;
668 }
669 else
670 {
671 // Fill in what is missing in the triple
672 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
673 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000674 if (target_triple.getVendorName().size() == 0)
675 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000676 target_triple.setVendor (remote_triple.getVendor());
677
Greg Clayton2f085c62011-05-15 01:25:55 +0000678 if (target_triple.getOSName().size() == 0)
679 {
680 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000681
Greg Clayton2f085c62011-05-15 01:25:55 +0000682 if (target_triple.getEnvironmentName().size() == 0)
683 target_triple.setEnvironment (remote_triple.getEnvironment());
684 }
685 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000686 }
687 }
688 else
689 {
690 // The target doesn't have a valid architecture yet, set it from
691 // the architecture we got from the remote GDB server
692 target_arch = gdb_remote_arch;
693 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000694 }
Chris Lattner24943d22010-06-08 16:52:24 +0000695 }
696}
697
698void
699ProcessGDBRemote::DidLaunch ()
700{
701 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000702}
703
704Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000705ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000706{
707 Error error;
708 // Clear out and clean up from any current state
709 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000710 if (attach_pid != LLDB_INVALID_PROCESS_ID)
711 {
Greg Claytona2f74232011-02-24 22:24:29 +0000712 // Make sure we aren't already connected?
713 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000714 {
Greg Claytona2f74232011-02-24 22:24:29 +0000715 char host_port[128];
716 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
717 char connect_url[128];
718 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000719
Greg Claytonb72d0f02011-04-12 05:54:46 +0000720 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000721
722 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000723 {
Greg Claytona2f74232011-02-24 22:24:29 +0000724 const char *error_string = error.AsCString();
725 if (error_string == NULL)
726 error_string = "unable to launch " DEBUGSERVER_BASENAME;
727
728 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000729 }
Greg Claytona2f74232011-02-24 22:24:29 +0000730 else
731 {
732 error = ConnectToDebugserver (connect_url);
733 }
734 }
735
736 if (error.Success())
737 {
738 char packet[64];
739 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
740
741 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000742 }
743 }
Chris Lattner24943d22010-06-08 16:52:24 +0000744 return error;
745}
746
747size_t
748ProcessGDBRemote::AttachInputReaderCallback
749(
750 void *baton,
751 InputReader *reader,
752 lldb::InputReaderAction notification,
753 const char *bytes,
754 size_t bytes_len
755)
756{
757 if (notification == eInputReaderGotToken)
758 {
759 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
760 if (gdb_process->m_waiting_for_attach)
761 gdb_process->m_waiting_for_attach = false;
762 reader->SetIsDone(true);
763 return 1;
764 }
765 return 0;
766}
767
768Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000769ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000770{
771 Error error;
772 // Clear out and clean up from any current state
773 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000774
Chris Lattner24943d22010-06-08 16:52:24 +0000775 if (process_name && process_name[0])
776 {
Greg Claytona2f74232011-02-24 22:24:29 +0000777 // Make sure we aren't already connected?
778 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000779 {
Greg Claytona2f74232011-02-24 22:24:29 +0000780 char host_port[128];
781 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
782 char connect_url[128];
783 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
784
Greg Claytonb72d0f02011-04-12 05:54:46 +0000785 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000786 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000787 {
Greg Claytona2f74232011-02-24 22:24:29 +0000788 const char *error_string = error.AsCString();
789 if (error_string == NULL)
790 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000791
Greg Claytona2f74232011-02-24 22:24:29 +0000792 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000793 }
Greg Claytona2f74232011-02-24 22:24:29 +0000794 else
795 {
796 error = ConnectToDebugserver (connect_url);
797 }
798 }
799
800 if (error.Success())
801 {
802 StreamString packet;
803
804 if (wait_for_launch)
805 packet.PutCString("vAttachWait");
806 else
807 packet.PutCString("vAttachName");
808 packet.PutChar(';');
809 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
810
811 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
812
Chris Lattner24943d22010-06-08 16:52:24 +0000813 }
814 }
Chris Lattner24943d22010-06-08 16:52:24 +0000815 return error;
816}
817
Chris Lattner24943d22010-06-08 16:52:24 +0000818
819void
820ProcessGDBRemote::DidAttach ()
821{
Greg Claytone71e2582011-02-04 01:58:07 +0000822 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000823}
824
825Error
826ProcessGDBRemote::WillResume ()
827{
Greg Claytonc1f45872011-02-12 06:28:37 +0000828 m_continue_c_tids.clear();
829 m_continue_C_tids.clear();
830 m_continue_s_tids.clear();
831 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000832 return Error();
833}
834
835Error
836ProcessGDBRemote::DoResume ()
837{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000838 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000839 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
840 if (log)
841 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000842
843 Listener listener ("gdb-remote.resume-packet-sent");
844 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
845 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000846 StreamString continue_packet;
847 bool continue_packet_error = false;
848 if (m_gdb_comm.HasAnyVContSupport ())
849 {
850 continue_packet.PutCString ("vCont");
851
852 if (!m_continue_c_tids.empty())
853 {
854 if (m_gdb_comm.GetVContSupported ('c'))
855 {
856 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)
857 continue_packet.Printf(";c:%4.4x", *t_pos);
858 }
859 else
860 continue_packet_error = true;
861 }
862
863 if (!continue_packet_error && !m_continue_C_tids.empty())
864 {
865 if (m_gdb_comm.GetVContSupported ('C'))
866 {
867 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)
868 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
869 }
870 else
871 continue_packet_error = true;
872 }
Greg Claytonb749a262010-12-03 06:02:24 +0000873
Greg Claytonc1f45872011-02-12 06:28:37 +0000874 if (!continue_packet_error && !m_continue_s_tids.empty())
875 {
876 if (m_gdb_comm.GetVContSupported ('s'))
877 {
878 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)
879 continue_packet.Printf(";s:%4.4x", *t_pos);
880 }
881 else
882 continue_packet_error = true;
883 }
884
885 if (!continue_packet_error && !m_continue_S_tids.empty())
886 {
887 if (m_gdb_comm.GetVContSupported ('S'))
888 {
889 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)
890 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
891 }
892 else
893 continue_packet_error = true;
894 }
895
896 if (continue_packet_error)
897 continue_packet.GetString().clear();
898 }
899 else
900 continue_packet_error = true;
901
902 if (continue_packet_error)
903 {
904 continue_packet_error = false;
905 // Either no vCont support, or we tried to use part of the vCont
906 // packet that wasn't supported by the remote GDB server.
907 // We need to try and make a simple packet that can do our continue
908 const size_t num_threads = GetThreadList().GetSize();
909 const size_t num_continue_c_tids = m_continue_c_tids.size();
910 const size_t num_continue_C_tids = m_continue_C_tids.size();
911 const size_t num_continue_s_tids = m_continue_s_tids.size();
912 const size_t num_continue_S_tids = m_continue_S_tids.size();
913 if (num_continue_c_tids > 0)
914 {
915 if (num_continue_c_tids == num_threads)
916 {
917 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000918 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000919 continue_packet.PutChar ('c');
920 }
921 else if (num_continue_c_tids == 1 &&
922 num_continue_C_tids == 0 &&
923 num_continue_s_tids == 0 &&
924 num_continue_S_tids == 0 )
925 {
926 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000927 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000928 continue_packet.PutChar ('c');
929 }
930 else
931 {
932 // We can't represent this continue packet....
933 continue_packet_error = true;
934 }
935 }
936
937 if (!continue_packet_error && num_continue_C_tids > 0)
938 {
939 if (num_continue_C_tids == num_threads)
940 {
941 const int continue_signo = m_continue_C_tids.front().second;
942 if (num_continue_C_tids > 1)
943 {
944 for (size_t i=1; i<num_threads; ++i)
945 {
946 if (m_continue_C_tids[i].second != continue_signo)
947 continue_packet_error = true;
948 }
949 }
950 if (!continue_packet_error)
951 {
952 // Add threads continuing with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000953 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000954 continue_packet.Printf("C%2.2x", continue_signo);
955 }
956 }
957 else if (num_continue_c_tids == 0 &&
958 num_continue_C_tids == 1 &&
959 num_continue_s_tids == 0 &&
960 num_continue_S_tids == 0 )
961 {
962 // Only one thread is continuing with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +0000963 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000964 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
965 }
966 else
967 {
968 // We can't represent this continue packet....
969 continue_packet_error = true;
970 }
971 }
972
973 if (!continue_packet_error && num_continue_s_tids > 0)
974 {
975 if (num_continue_s_tids == num_threads)
976 {
977 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000978 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000979 continue_packet.PutChar ('s');
980 }
981 else if (num_continue_c_tids == 0 &&
982 num_continue_C_tids == 0 &&
983 num_continue_s_tids == 1 &&
984 num_continue_S_tids == 0 )
985 {
986 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +0000987 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000988 continue_packet.PutChar ('s');
989 }
990 else
991 {
992 // We can't represent this continue packet....
993 continue_packet_error = true;
994 }
995 }
996
997 if (!continue_packet_error && num_continue_S_tids > 0)
998 {
999 if (num_continue_S_tids == num_threads)
1000 {
1001 const int step_signo = m_continue_S_tids.front().second;
1002 // Are all threads trying to step with the same signal?
1003 if (num_continue_S_tids > 1)
1004 {
1005 for (size_t i=1; i<num_threads; ++i)
1006 {
1007 if (m_continue_S_tids[i].second != step_signo)
1008 continue_packet_error = true;
1009 }
1010 }
1011 if (!continue_packet_error)
1012 {
1013 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001014 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001015 continue_packet.Printf("S%2.2x", step_signo);
1016 }
1017 }
1018 else if (num_continue_c_tids == 0 &&
1019 num_continue_C_tids == 0 &&
1020 num_continue_s_tids == 0 &&
1021 num_continue_S_tids == 1 )
1022 {
1023 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001024 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001025 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1026 }
1027 else
1028 {
1029 // We can't represent this continue packet....
1030 continue_packet_error = true;
1031 }
1032 }
1033 }
1034
1035 if (continue_packet_error)
1036 {
1037 error.SetErrorString ("can't make continue packet for this resume");
1038 }
1039 else
1040 {
1041 EventSP event_sp;
1042 TimeValue timeout;
1043 timeout = TimeValue::Now();
1044 timeout.OffsetWithSeconds (5);
1045 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1046
1047 if (listener.WaitForEvent (&timeout, event_sp) == false)
1048 error.SetErrorString("Resume timed out.");
1049 }
Greg Claytonb749a262010-12-03 06:02:24 +00001050 }
1051
Jim Ingham3ae449a2010-11-17 02:32:00 +00001052 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001053}
1054
Chris Lattner24943d22010-06-08 16:52:24 +00001055uint32_t
1056ProcessGDBRemote::UpdateThreadListIfNeeded ()
1057{
1058 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001059 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001060 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001061 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1062
Greg Clayton5205f0b2010-09-03 17:10:42 +00001063 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001064 const uint32_t stop_id = GetStopID();
1065 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1066 {
1067 // Update the thread list's stop id immediately so we don't recurse into this function.
1068 ThreadList curr_thread_list (this);
1069 curr_thread_list.SetStopID(stop_id);
1070
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001071 std::vector<lldb::tid_t> thread_ids;
1072 bool sequence_mutex_unavailable = false;
1073 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1074 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001075 {
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001076 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001077 {
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001078 tid_t tid = thread_ids[i];
1079 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
1080 if (!thread_sp)
1081 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1082 curr_thread_list.AddThread(thread_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001083 }
1084 }
1085
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001086 if (sequence_mutex_unavailable == false)
1087 {
1088 m_thread_list = curr_thread_list;
1089 SetThreadStopInfo (m_last_stop_packet);
1090 }
Chris Lattner24943d22010-06-08 16:52:24 +00001091 }
1092 return GetThreadList().GetSize(false);
1093}
1094
1095
1096StateType
1097ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1098{
Greg Clayton261a18b2011-06-02 22:22:38 +00001099 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001100 const char stop_type = stop_packet.GetChar();
1101 switch (stop_type)
1102 {
1103 case 'T':
1104 case 'S':
1105 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001106 if (GetStopID() == 0)
1107 {
1108 // Our first stop, make sure we have a process ID, and also make
1109 // sure we know about our registers
1110 if (GetID() == LLDB_INVALID_PROCESS_ID)
1111 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001112 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001113 if (pid != LLDB_INVALID_PROCESS_ID)
1114 SetID (pid);
1115 }
1116 BuildDynamicRegisterInfo (true);
1117 }
Chris Lattner24943d22010-06-08 16:52:24 +00001118 // Stop with signal and thread info
1119 const uint8_t signo = stop_packet.GetHexU8();
1120 std::string name;
1121 std::string value;
1122 std::string thread_name;
1123 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001124 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001125 uint32_t tid = LLDB_INVALID_THREAD_ID;
1126 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1127 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001128 ThreadSP thread_sp;
1129
Chris Lattner24943d22010-06-08 16:52:24 +00001130 while (stop_packet.GetNameColonValue(name, value))
1131 {
1132 if (name.compare("metype") == 0)
1133 {
1134 // exception type in big endian hex
1135 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1136 }
1137 else if (name.compare("mecount") == 0)
1138 {
1139 // exception count in big endian hex
1140 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1141 }
1142 else if (name.compare("medata") == 0)
1143 {
1144 // exception data in big endian hex
1145 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1146 }
1147 else if (name.compare("thread") == 0)
1148 {
1149 // thread in big endian hex
1150 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001151 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001152 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001153 if (!thread_sp)
1154 {
1155 // Create the thread if we need to
1156 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1157 m_thread_list.AddThread(thread_sp);
1158 }
Chris Lattner24943d22010-06-08 16:52:24 +00001159 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001160 else if (name.compare("hexname") == 0)
1161 {
1162 StringExtractor name_extractor;
1163 // Swap "value" over into "name_extractor"
1164 name_extractor.GetStringRef().swap(value);
1165 // Now convert the HEX bytes into a string value
1166 name_extractor.GetHexByteString (value);
1167 thread_name.swap (value);
1168 }
Chris Lattner24943d22010-06-08 16:52:24 +00001169 else if (name.compare("name") == 0)
1170 {
1171 thread_name.swap (value);
1172 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001173 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001174 {
1175 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1176 }
Greg Claytona875b642011-01-09 21:07:35 +00001177 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1178 {
1179 // We have a register number that contains an expedited
1180 // register value. Lets supply this register to our thread
1181 // so it won't have to go and read it.
1182 if (thread_sp)
1183 {
1184 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1185
1186 if (reg != UINT32_MAX)
1187 {
1188 StringExtractor reg_value_extractor;
1189 // Swap "value" over into "reg_value_extractor"
1190 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001191 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1192 {
1193 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1194 name.c_str(),
1195 reg,
1196 reg,
1197 reg_value_extractor.GetStringRef().c_str(),
1198 stop_packet.GetStringRef().c_str());
1199 }
Greg Claytona875b642011-01-09 21:07:35 +00001200 }
1201 }
1202 }
Chris Lattner24943d22010-06-08 16:52:24 +00001203 }
Chris Lattner24943d22010-06-08 16:52:24 +00001204
1205 if (thread_sp)
1206 {
1207 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1208
1209 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001210 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001211 if (exc_type != 0)
1212 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001213 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001214
1215 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1216 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001217 exc_data_size,
1218 exc_data_size >= 1 ? exc_data[0] : 0,
1219 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001220 }
1221 else if (signo)
1222 {
Greg Clayton643ee732010-08-04 01:40:35 +00001223 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001224 }
1225 else
1226 {
Greg Clayton643ee732010-08-04 01:40:35 +00001227 StopInfoSP invalid_stop_info_sp;
1228 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001229 }
1230 }
1231 return eStateStopped;
1232 }
1233 break;
1234
1235 case 'W':
1236 // process exited
1237 return eStateExited;
1238
1239 default:
1240 break;
1241 }
1242 return eStateInvalid;
1243}
1244
1245void
1246ProcessGDBRemote::RefreshStateAfterStop ()
1247{
Chris Lattner24943d22010-06-08 16:52:24 +00001248 // Let all threads recover from stopping and do any clean up based
1249 // on the previous thread state (if any).
1250 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001251 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001252}
1253
1254Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001255ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001256{
1257 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001258
Greg Claytona4881d02011-01-22 07:12:45 +00001259 bool timed_out = false;
1260 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001261
1262 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001263 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001264 // We are being asked to halt during an attach. We need to just close
1265 // our file handle and debugserver will go away, and we can be done...
1266 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001267 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001268 else
1269 {
1270 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1271 {
1272 if (timed_out)
1273 error.SetErrorString("timed out sending interrupt packet");
1274 else
1275 error.SetErrorString("unknown error sending interrupt packet");
1276 }
1277 }
Chris Lattner24943d22010-06-08 16:52:24 +00001278 return error;
1279}
1280
1281Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001282ProcessGDBRemote::InterruptIfRunning
1283(
1284 bool discard_thread_plans,
1285 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001286 EventSP &stop_event_sp
1287)
Chris Lattner24943d22010-06-08 16:52:24 +00001288{
1289 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001290
Greg Clayton2860ba92011-01-23 19:58:49 +00001291 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1292
Greg Clayton68ca8232011-01-25 02:58:48 +00001293 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001294 const bool is_running = m_gdb_comm.IsRunning();
1295 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001296 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001297 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001298 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001299 is_running);
1300
Greg Clayton2860ba92011-01-23 19:58:49 +00001301 if (discard_thread_plans)
1302 {
1303 if (log)
1304 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1305 m_thread_list.DiscardThreadPlans();
1306 }
1307 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001308 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001309 if (catch_stop_event)
1310 {
1311 if (log)
1312 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1313 PausePrivateStateThread();
1314 paused_private_state_thread = true;
1315 }
1316
Greg Clayton4fb400f2010-09-27 21:07:38 +00001317 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001318 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001319 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001320
Greg Clayton72e1c782011-01-22 23:43:18 +00001321 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001322 {
1323 if (timed_out)
1324 error.SetErrorString("timed out sending interrupt packet");
1325 else
1326 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001327 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001328 ResumePrivateStateThread();
1329 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001330 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001331
Greg Clayton72e1c782011-01-22 23:43:18 +00001332 if (catch_stop_event)
1333 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001334 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001335 TimeValue timeout_time;
1336 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001337 timeout_time.OffsetWithSeconds(5);
1338 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001339
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001340 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001341 if (log)
1342 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001343
Greg Clayton2860ba92011-01-23 19:58:49 +00001344 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001345 error.SetErrorString("unable to verify target stopped");
1346 }
1347
Greg Clayton68ca8232011-01-25 02:58:48 +00001348 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001349 {
1350 if (log)
1351 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001352 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001353 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001354 }
Chris Lattner24943d22010-06-08 16:52:24 +00001355 return error;
1356}
1357
Greg Clayton4fb400f2010-09-27 21:07:38 +00001358Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001359ProcessGDBRemote::WillDetach ()
1360{
Greg Clayton2860ba92011-01-23 19:58:49 +00001361 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1362 if (log)
1363 log->Printf ("ProcessGDBRemote::WillDetach()");
1364
Greg Clayton72e1c782011-01-22 23:43:18 +00001365 bool discard_thread_plans = true;
1366 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001367 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001368 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001369}
1370
1371Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001372ProcessGDBRemote::DoDetach()
1373{
1374 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001375 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001376 if (log)
1377 log->Printf ("ProcessGDBRemote::DoDetach()");
1378
1379 DisableAllBreakpointSites ();
1380
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001381 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001382
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001383 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1384 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001385 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001386 if (response_size)
1387 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1388 else
1389 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001390 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001391 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001392 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001393
Greg Clayton4fb400f2010-09-27 21:07:38 +00001394 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001395 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001396
1397 SetPrivateState (eStateDetached);
1398 ResumePrivateStateThread();
1399
1400 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001401 return error;
1402}
Chris Lattner24943d22010-06-08 16:52:24 +00001403
1404Error
1405ProcessGDBRemote::DoDestroy ()
1406{
1407 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001408 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001409 if (log)
1410 log->Printf ("ProcessGDBRemote::DoDestroy()");
1411
1412 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001413 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001414 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001415 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001416 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001417 // We are being asked to halt during an attach. We need to just close
1418 // our file handle and debugserver will go away, and we can be done...
1419 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001420 }
1421 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001422 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001423
1424 StringExtractorGDBRemote response;
1425 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001426 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001427 {
1428 char packet_cmd = response.GetChar(0);
1429
1430 if (packet_cmd == 'W' || packet_cmd == 'X')
1431 {
1432 m_last_stop_packet = response;
1433 SetExitStatus(response.GetHexU8(), NULL);
1434 }
1435 }
1436 else
1437 {
1438 SetExitStatus(SIGABRT, NULL);
1439 //error.SetErrorString("kill packet failed");
1440 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001441 }
1442 }
Chris Lattner24943d22010-06-08 16:52:24 +00001443 StopAsyncThread ();
1444 m_gdb_comm.StopReadThread();
1445 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001446 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001447 return error;
1448}
1449
Chris Lattner24943d22010-06-08 16:52:24 +00001450//------------------------------------------------------------------
1451// Process Queries
1452//------------------------------------------------------------------
1453
1454bool
1455ProcessGDBRemote::IsAlive ()
1456{
Greg Clayton58e844b2010-12-08 05:08:21 +00001457 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001458}
1459
1460addr_t
1461ProcessGDBRemote::GetImageInfoAddress()
1462{
1463 if (!m_gdb_comm.IsRunning())
1464 {
1465 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001466 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001467 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001468 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001469 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1470 }
1471 }
1472 return LLDB_INVALID_ADDRESS;
1473}
1474
Chris Lattner24943d22010-06-08 16:52:24 +00001475//------------------------------------------------------------------
1476// Process Memory
1477//------------------------------------------------------------------
1478size_t
1479ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1480{
1481 if (size > m_max_memory_size)
1482 {
1483 // Keep memory read sizes down to a sane limit. This function will be
1484 // called multiple times in order to complete the task by
1485 // lldb_private::Process so it is ok to do this.
1486 size = m_max_memory_size;
1487 }
1488
1489 char packet[64];
1490 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1491 assert (packet_len + 1 < sizeof(packet));
1492 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001493 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001494 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001495 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001496 {
1497 error.Clear();
1498 return response.GetHexBytes(buf, size, '\xdd');
1499 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001500 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001501 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001502 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001503 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1504 else
1505 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1506 }
1507 else
1508 {
1509 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1510 }
1511 return 0;
1512}
1513
1514size_t
1515ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1516{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001517 if (size > m_max_memory_size)
1518 {
1519 // Keep memory read sizes down to a sane limit. This function will be
1520 // called multiple times in order to complete the task by
1521 // lldb_private::Process so it is ok to do this.
1522 size = m_max_memory_size;
1523 }
1524
Chris Lattner24943d22010-06-08 16:52:24 +00001525 StreamString packet;
1526 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001527 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001528 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001529 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001530 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001531 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001532 {
1533 error.Clear();
1534 return size;
1535 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001536 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001537 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001538 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001539 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1540 else
1541 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1542 }
1543 else
1544 {
1545 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1546 }
1547 return 0;
1548}
1549
1550lldb::addr_t
1551ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1552{
Greg Clayton989816b2011-05-14 01:50:35 +00001553 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1554
Greg Clayton2f085c62011-05-15 01:25:55 +00001555 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001556 switch (supported)
1557 {
1558 case eLazyBoolCalculate:
1559 case eLazyBoolYes:
1560 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1561 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1562 return allocated_addr;
1563
1564 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001565 // Call mmap() to create memory in the inferior..
1566 unsigned prot = 0;
1567 if (permissions & lldb::ePermissionsReadable)
1568 prot |= eMmapProtRead;
1569 if (permissions & lldb::ePermissionsWritable)
1570 prot |= eMmapProtWrite;
1571 if (permissions & lldb::ePermissionsExecutable)
1572 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001573
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001574 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1575 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1576 m_addr_to_mmap_size[allocated_addr] = size;
1577 else
1578 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001579 break;
1580 }
1581
Chris Lattner24943d22010-06-08 16:52:24 +00001582 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001583 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001584 else
1585 error.Clear();
1586 return allocated_addr;
1587}
1588
1589Error
1590ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1591{
1592 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001593 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1594
1595 switch (supported)
1596 {
1597 case eLazyBoolCalculate:
1598 // We should never be deallocating memory without allocating memory
1599 // first so we should never get eLazyBoolCalculate
1600 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1601 break;
1602
1603 case eLazyBoolYes:
1604 if (!m_gdb_comm.DeallocateMemory (addr))
1605 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1606 break;
1607
1608 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001609 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001610 {
1611 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001612 if (pos != m_addr_to_mmap_size.end() &&
1613 InferiorCallMunmap(this, addr, pos->second))
1614 m_addr_to_mmap_size.erase (pos);
1615 else
1616 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001617 }
1618 break;
1619 }
1620
Chris Lattner24943d22010-06-08 16:52:24 +00001621 return error;
1622}
1623
1624
1625//------------------------------------------------------------------
1626// Process STDIO
1627//------------------------------------------------------------------
1628
1629size_t
1630ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1631{
1632 Mutex::Locker locker(m_stdio_mutex);
1633 size_t bytes_available = m_stdout_data.size();
1634 if (bytes_available > 0)
1635 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001636 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1637 if (log)
1638 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001639 if (bytes_available > buf_size)
1640 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001641 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001642 m_stdout_data.erase(0, buf_size);
1643 bytes_available = buf_size;
1644 }
1645 else
1646 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001647 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001648 m_stdout_data.clear();
1649
1650 //ResetEventBits(eBroadcastBitSTDOUT);
1651 }
1652 }
1653 return bytes_available;
1654}
1655
1656size_t
1657ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1658{
1659 // Can we get STDERR through the remote protocol?
1660 return 0;
1661}
1662
1663size_t
1664ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1665{
1666 if (m_stdio_communication.IsConnected())
1667 {
1668 ConnectionStatus status;
1669 m_stdio_communication.Write(src, src_len, status, NULL);
1670 }
1671 return 0;
1672}
1673
1674Error
1675ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1676{
1677 Error error;
1678 assert (bp_site != NULL);
1679
Greg Claytone005f2c2010-11-06 01:53:30 +00001680 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001681 user_id_t site_id = bp_site->GetID();
1682 const addr_t addr = bp_site->GetLoadAddress();
1683 if (log)
1684 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1685
1686 if (bp_site->IsEnabled())
1687 {
1688 if (log)
1689 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1690 return error;
1691 }
1692 else
1693 {
1694 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1695
1696 if (bp_site->HardwarePreferred())
1697 {
1698 // Try and set hardware breakpoint, and if that fails, fall through
1699 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001700 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001701 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001702 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001703 {
1704 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001705 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001706 return error;
1707 }
Chris Lattner24943d22010-06-08 16:52:24 +00001708 }
1709 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001710
1711 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001712 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001713 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1714 {
1715 bp_site->SetEnabled(true);
1716 bp_site->SetType (BreakpointSite::eExternal);
1717 return error;
1718 }
Chris Lattner24943d22010-06-08 16:52:24 +00001719 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001720
1721 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001722 }
1723
1724 if (log)
1725 {
1726 const char *err_string = error.AsCString();
1727 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1728 bp_site->GetLoadAddress(),
1729 err_string ? err_string : "NULL");
1730 }
1731 // We shouldn't reach here on a successful breakpoint enable...
1732 if (error.Success())
1733 error.SetErrorToGenericError();
1734 return error;
1735}
1736
1737Error
1738ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1739{
1740 Error error;
1741 assert (bp_site != NULL);
1742 addr_t addr = bp_site->GetLoadAddress();
1743 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001744 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001745 if (log)
1746 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1747
1748 if (bp_site->IsEnabled())
1749 {
1750 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1751
Greg Claytonb72d0f02011-04-12 05:54:46 +00001752 BreakpointSite::Type bp_type = bp_site->GetType();
1753 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001754 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001755 case BreakpointSite::eSoftware:
1756 error = DisableSoftwareBreakpoint (bp_site);
1757 break;
1758
1759 case BreakpointSite::eHardware:
1760 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1761 error.SetErrorToGenericError();
1762 break;
1763
1764 case BreakpointSite::eExternal:
1765 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1766 error.SetErrorToGenericError();
1767 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001768 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001769 if (error.Success())
1770 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001771 }
1772 else
1773 {
1774 if (log)
1775 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1776 return error;
1777 }
1778
1779 if (error.Success())
1780 error.SetErrorToGenericError();
1781 return error;
1782}
1783
1784Error
1785ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1786{
1787 Error error;
1788 if (wp)
1789 {
1790 user_id_t watchID = wp->GetID();
1791 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001792 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001793 if (log)
1794 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1795 if (wp->IsEnabled())
1796 {
1797 if (log)
1798 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1799 return error;
1800 }
1801 else
1802 {
1803 // Pass down an appropriate z/Z packet...
1804 error.SetErrorString("watchpoints not supported");
1805 }
1806 }
1807 else
1808 {
1809 error.SetErrorString("Watchpoint location argument was NULL.");
1810 }
1811 if (error.Success())
1812 error.SetErrorToGenericError();
1813 return error;
1814}
1815
1816Error
1817ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1818{
1819 Error error;
1820 if (wp)
1821 {
1822 user_id_t watchID = wp->GetID();
1823
Greg Claytone005f2c2010-11-06 01:53:30 +00001824 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001825
1826 addr_t addr = wp->GetLoadAddress();
1827 if (log)
1828 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1829
1830 if (wp->IsHardware())
1831 {
1832 // Pass down an appropriate z/Z packet...
1833 error.SetErrorString("watchpoints not supported");
1834 }
1835 // TODO: clear software watchpoints if we implement them
1836 }
1837 else
1838 {
1839 error.SetErrorString("Watchpoint location argument was NULL.");
1840 }
1841 if (error.Success())
1842 error.SetErrorToGenericError();
1843 return error;
1844}
1845
1846void
1847ProcessGDBRemote::Clear()
1848{
1849 m_flags = 0;
1850 m_thread_list.Clear();
1851 {
1852 Mutex::Locker locker(m_stdio_mutex);
1853 m_stdout_data.clear();
1854 }
Chris Lattner24943d22010-06-08 16:52:24 +00001855}
1856
1857Error
1858ProcessGDBRemote::DoSignal (int signo)
1859{
1860 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001861 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001862 if (log)
1863 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1864
1865 if (!m_gdb_comm.SendAsyncSignal (signo))
1866 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1867 return error;
1868}
1869
Chris Lattner24943d22010-06-08 16:52:24 +00001870Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00001871ProcessGDBRemote::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 +00001872{
1873 Error error;
1874 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1875 {
1876 // If we locate debugserver, keep that located version around
1877 static FileSpec g_debugserver_file_spec;
1878
Greg Claytonb72d0f02011-04-12 05:54:46 +00001879 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00001880 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00001881 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00001882
1883 // Always check to see if we have an environment override for the path
1884 // to the debugserver to use and use it if we do.
1885 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1886 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001887 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001888 else
1889 debugserver_file_spec = g_debugserver_file_spec;
1890 bool debugserver_exists = debugserver_file_spec.Exists();
1891 if (!debugserver_exists)
1892 {
1893 // The debugserver binary is in the LLDB.framework/Resources
1894 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001895 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001896 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001897 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001898 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001899 if (debugserver_exists)
1900 {
1901 g_debugserver_file_spec = debugserver_file_spec;
1902 }
1903 else
1904 {
1905 g_debugserver_file_spec.Clear();
1906 debugserver_file_spec.Clear();
1907 }
Chris Lattner24943d22010-06-08 16:52:24 +00001908 }
1909 }
1910
1911 if (debugserver_exists)
1912 {
1913 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1914
1915 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001916
Greg Claytone005f2c2010-11-06 01:53:30 +00001917 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001918
Greg Claytonb72d0f02011-04-12 05:54:46 +00001919 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00001920 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001921
Chris Lattner24943d22010-06-08 16:52:24 +00001922 // Start args with "debugserver /file/path -r --"
1923 debugserver_args.AppendArgument(debugserver_path);
1924 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001925 // use native registers, not the GDB registers
1926 debugserver_args.AppendArgument("--native-regs");
1927 // make debugserver run in its own session so signals generated by
1928 // special terminal key sequences (^C) don't affect debugserver
1929 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001930
Chris Lattner24943d22010-06-08 16:52:24 +00001931 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1932 if (env_debugserver_log_file)
1933 {
1934 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1935 debugserver_args.AppendArgument(arg_cstr);
1936 }
1937
1938 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1939 if (env_debugserver_log_flags)
1940 {
1941 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1942 debugserver_args.AppendArgument(arg_cstr);
1943 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001944// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001945// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001946
Greg Claytonb72d0f02011-04-12 05:54:46 +00001947 // We currently send down all arguments, attach pids, or attach
1948 // process names in dedicated GDB server packets, so we don't need
1949 // to pass them as arguments. This is currently because of all the
1950 // things we need to setup prior to launching: the environment,
1951 // current working dir, file actions, etc.
1952#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00001953 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00001954 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00001955 {
Greg Claytona2f74232011-02-24 22:24:29 +00001956 // Terminate the debugserver args so we can now append the inferior args
1957 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00001958
Greg Claytona2f74232011-02-24 22:24:29 +00001959 for (int i = 0; inferior_argv[i] != NULL; ++i)
1960 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00001961 }
1962 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1963 {
1964 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1965 debugserver_args.AppendArgument (arg_cstr);
1966 }
1967 else if (attach_name && attach_name[0])
1968 {
1969 if (wait_for_launch)
1970 debugserver_args.AppendArgument ("--waitfor");
1971 else
1972 debugserver_args.AppendArgument ("--attach");
1973 debugserver_args.AppendArgument (attach_name);
1974 }
Chris Lattner24943d22010-06-08 16:52:24 +00001975#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00001976
1977 ProcessLaunchInfo::FileAction file_action;
1978
1979 // Close STDIN, STDOUT and STDERR. We might need to redirect them
1980 // to "/dev/null" if we run into any problems.
1981 file_action.Close (STDIN_FILENO);
1982 launch_info.AppendFileAction (file_action);
1983 file_action.Close (STDOUT_FILENO);
1984 launch_info.AppendFileAction (file_action);
1985 file_action.Close (STDERR_FILENO);
1986 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00001987
1988 if (log)
1989 {
1990 StreamString strm;
1991 debugserver_args.Dump (&strm);
1992 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1993 }
1994
Greg Claytonb72d0f02011-04-12 05:54:46 +00001995 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00001996
Greg Claytonb72d0f02011-04-12 05:54:46 +00001997 if (error.Success ())
1998 m_debugserver_pid = launch_info.GetProcessID();
1999 else
Chris Lattner24943d22010-06-08 16:52:24 +00002000 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2001
2002 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002003 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002004 }
2005 else
2006 {
2007 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2008 }
2009
2010 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2011 StartAsyncThread ();
2012 }
2013 return error;
2014}
2015
2016bool
2017ProcessGDBRemote::MonitorDebugserverProcess
2018(
2019 void *callback_baton,
2020 lldb::pid_t debugserver_pid,
2021 int signo, // Zero for no signal
2022 int exit_status // Exit value of process if signal is zero
2023)
2024{
2025 // We pass in the ProcessGDBRemote inferior process it and name it
2026 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2027 // pointer value itself, thus we need the double cast...
2028
2029 // "debugserver_pid" argument passed in is the process ID for
2030 // debugserver that we are tracking...
2031
Greg Clayton75ccf502010-08-21 02:22:51 +00002032 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002033
2034 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2035 if (log)
2036 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2037
Greg Clayton75ccf502010-08-21 02:22:51 +00002038 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002039 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002040 // Sleep for a half a second to make sure our inferior process has
2041 // time to set its exit status before we set it incorrectly when
2042 // both the debugserver and the inferior process shut down.
2043 usleep (500000);
2044 // If our process hasn't yet exited, debugserver might have died.
2045 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002046 const StateType state = process->GetState();
2047
2048 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2049 state != eStateInvalid &&
2050 state != eStateUnloaded &&
2051 state != eStateExited &&
2052 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002053 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002054 char error_str[1024];
2055 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002056 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002057 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2058 if (signal_cstr)
2059 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002060 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002061 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002062 }
2063 else
2064 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002065 ::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 +00002066 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002067
2068 process->SetExitStatus (-1, error_str);
2069 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002070 // Debugserver has exited we need to let our ProcessGDBRemote
2071 // know that it no longer has a debugserver instance
2072 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2073 // We are returning true to this function below, so we can
2074 // forget about the monitor handle.
2075 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002076 }
2077 return true;
2078}
2079
2080void
2081ProcessGDBRemote::KillDebugserverProcess ()
2082{
2083 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2084 {
2085 ::kill (m_debugserver_pid, SIGINT);
2086 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2087 }
2088}
2089
2090void
2091ProcessGDBRemote::Initialize()
2092{
2093 static bool g_initialized = false;
2094
2095 if (g_initialized == false)
2096 {
2097 g_initialized = true;
2098 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2099 GetPluginDescriptionStatic(),
2100 CreateInstance);
2101
2102 Log::Callbacks log_callbacks = {
2103 ProcessGDBRemoteLog::DisableLog,
2104 ProcessGDBRemoteLog::EnableLog,
2105 ProcessGDBRemoteLog::ListLogCategories
2106 };
2107
2108 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2109 }
2110}
2111
2112bool
Chris Lattner24943d22010-06-08 16:52:24 +00002113ProcessGDBRemote::StartAsyncThread ()
2114{
Greg Claytone005f2c2010-11-06 01:53:30 +00002115 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002116
2117 if (log)
2118 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2119
2120 // Create a thread that watches our internal state and controls which
2121 // events make it to clients (into the DCProcess event queue).
2122 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002123 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002124}
2125
2126void
2127ProcessGDBRemote::StopAsyncThread ()
2128{
Greg Claytone005f2c2010-11-06 01:53:30 +00002129 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002130
2131 if (log)
2132 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2133
2134 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2135
2136 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002137 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002138 {
2139 Host::ThreadJoin (m_async_thread, NULL, NULL);
2140 }
2141}
2142
2143
2144void *
2145ProcessGDBRemote::AsyncThread (void *arg)
2146{
2147 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2148
Greg Claytone005f2c2010-11-06 01:53:30 +00002149 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002150 if (log)
2151 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2152
2153 Listener listener ("ProcessGDBRemote::AsyncThread");
2154 EventSP event_sp;
2155 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2156 eBroadcastBitAsyncThreadShouldExit;
2157
2158 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2159 {
Greg Claytona2f74232011-02-24 22:24:29 +00002160 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2161
Chris Lattner24943d22010-06-08 16:52:24 +00002162 bool done = false;
2163 while (!done)
2164 {
2165 if (log)
2166 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2167 if (listener.WaitForEvent (NULL, event_sp))
2168 {
2169 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002170 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002171 {
Greg Claytona2f74232011-02-24 22:24:29 +00002172 if (log)
2173 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 +00002174
Greg Claytona2f74232011-02-24 22:24:29 +00002175 switch (event_type)
2176 {
2177 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002178 {
Greg Claytona2f74232011-02-24 22:24:29 +00002179 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002180
Greg Claytona2f74232011-02-24 22:24:29 +00002181 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002182 {
Greg Claytona2f74232011-02-24 22:24:29 +00002183 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2184 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2185 if (log)
2186 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002187
Greg Claytona2f74232011-02-24 22:24:29 +00002188 if (::strstr (continue_cstr, "vAttach") == NULL)
2189 process->SetPrivateState(eStateRunning);
2190 StringExtractorGDBRemote response;
2191 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002192
Greg Claytona2f74232011-02-24 22:24:29 +00002193 switch (stop_state)
2194 {
2195 case eStateStopped:
2196 case eStateCrashed:
2197 case eStateSuspended:
2198 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002199 process->SetPrivateState (stop_state);
2200 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002201
Greg Claytona2f74232011-02-24 22:24:29 +00002202 case eStateExited:
2203 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002204 response.SetFilePos(1);
2205 process->SetExitStatus(response.GetHexU8(), NULL);
2206 done = true;
2207 break;
2208
2209 case eStateInvalid:
2210 process->SetExitStatus(-1, "lost connection");
2211 break;
2212
2213 default:
2214 process->SetPrivateState (stop_state);
2215 break;
2216 }
Chris Lattner24943d22010-06-08 16:52:24 +00002217 }
2218 }
Greg Claytona2f74232011-02-24 22:24:29 +00002219 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002220
Greg Claytona2f74232011-02-24 22:24:29 +00002221 case eBroadcastBitAsyncThreadShouldExit:
2222 if (log)
2223 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2224 done = true;
2225 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002226
Greg Claytona2f74232011-02-24 22:24:29 +00002227 default:
2228 if (log)
2229 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2230 done = true;
2231 break;
2232 }
2233 }
2234 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2235 {
2236 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2237 {
2238 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002239 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002240 }
Chris Lattner24943d22010-06-08 16:52:24 +00002241 }
2242 }
2243 else
2244 {
2245 if (log)
2246 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2247 done = true;
2248 }
2249 }
2250 }
2251
2252 if (log)
2253 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2254
2255 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2256 return NULL;
2257}
2258
Chris Lattner24943d22010-06-08 16:52:24 +00002259const char *
2260ProcessGDBRemote::GetDispatchQueueNameForThread
2261(
2262 addr_t thread_dispatch_qaddr,
2263 std::string &dispatch_queue_name
2264)
2265{
2266 dispatch_queue_name.clear();
2267 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2268 {
2269 // Cache the dispatch_queue_offsets_addr value so we don't always have
2270 // to look it up
2271 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2272 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002273 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2274 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002275 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002276 if (module_sp)
2277 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2278
2279 if (dispatch_queue_offsets_symbol == NULL)
2280 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002281 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002282 if (module_sp)
2283 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2284 }
Chris Lattner24943d22010-06-08 16:52:24 +00002285 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002286 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002287
2288 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2289 return NULL;
2290 }
2291
2292 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002293 DataExtractor data (memory_buffer,
2294 sizeof(memory_buffer),
2295 m_target.GetArchitecture().GetByteOrder(),
2296 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002297
2298 // Excerpt from src/queue_private.h
2299 struct dispatch_queue_offsets_s
2300 {
2301 uint16_t dqo_version;
2302 uint16_t dqo_label;
2303 uint16_t dqo_label_size;
2304 } dispatch_queue_offsets;
2305
2306
2307 Error error;
2308 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2309 {
2310 uint32_t data_offset = 0;
2311 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2312 {
2313 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2314 {
2315 data_offset = 0;
2316 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2317 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2318 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2319 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2320 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2321 dispatch_queue_name.erase (bytes_read);
2322 }
2323 }
2324 }
2325 }
2326 if (dispatch_queue_name.empty())
2327 return NULL;
2328 return dispatch_queue_name.c_str();
2329}
2330
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002331//uint32_t
2332//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2333//{
2334// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2335// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2336// if (m_local_debugserver)
2337// {
2338// return Host::ListProcessesMatchingName (name, matches, pids);
2339// }
2340// else
2341// {
2342// // FIXME: Implement talking to the remote debugserver.
2343// return 0;
2344// }
2345//
2346//}
2347//
Jim Ingham55e01d82011-01-22 01:33:44 +00002348bool
2349ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2350 lldb_private::StoppointCallbackContext *context,
2351 lldb::user_id_t break_id,
2352 lldb::user_id_t break_loc_id)
2353{
2354 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2355 // run so I can stop it if that's what I want to do.
2356 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2357 if (log)
2358 log->Printf("Hit New Thread Notification breakpoint.");
2359 return false;
2360}
2361
2362
2363bool
2364ProcessGDBRemote::StartNoticingNewThreads()
2365{
2366 static const char *bp_names[] =
2367 {
2368 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002369 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002370 "_pthread_start",
2371 NULL
2372 };
2373
2374 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2375 size_t num_bps = m_thread_observation_bps.size();
2376 if (num_bps != 0)
2377 {
2378 for (int i = 0; i < num_bps; i++)
2379 {
2380 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2381 if (break_sp)
2382 {
2383 if (log)
2384 log->Printf("Enabled noticing new thread breakpoint.");
2385 break_sp->SetEnabled(true);
2386 }
2387 }
2388 }
2389 else
2390 {
2391 for (int i = 0; bp_names[i] != NULL; i++)
2392 {
2393 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2394 if (breakpoint)
2395 {
2396 if (log)
2397 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2398 m_thread_observation_bps.push_back(breakpoint->GetID());
2399 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2400 }
2401 else
2402 {
2403 if (log)
2404 log->Printf("Failed to create new thread notification breakpoint.");
2405 return false;
2406 }
2407 }
2408 }
2409
2410 return true;
2411}
2412
2413bool
2414ProcessGDBRemote::StopNoticingNewThreads()
2415{
Jim Inghamff276fe2011-02-08 05:19:01 +00002416 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2417 if (log)
2418 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002419 size_t num_bps = m_thread_observation_bps.size();
2420 if (num_bps != 0)
2421 {
2422 for (int i = 0; i < num_bps; i++)
2423 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002424
2425 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2426 if (break_sp)
2427 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002428 break_sp->SetEnabled(false);
2429 }
2430 }
2431 }
2432 return true;
2433}
2434
2435