blob: 27018db6f14eba026fe76fc8523b446087672d83 [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;
Greg Clayton65611552011-06-04 01:26:29 +00001123 std::string reason;
1124 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001125 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001126 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001127 uint32_t tid = LLDB_INVALID_THREAD_ID;
1128 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1129 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001130 ThreadSP thread_sp;
1131
Chris Lattner24943d22010-06-08 16:52:24 +00001132 while (stop_packet.GetNameColonValue(name, value))
1133 {
1134 if (name.compare("metype") == 0)
1135 {
1136 // exception type in big endian hex
1137 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1138 }
1139 else if (name.compare("mecount") == 0)
1140 {
1141 // exception count in big endian hex
1142 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1143 }
1144 else if (name.compare("medata") == 0)
1145 {
1146 // exception data in big endian hex
1147 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1148 }
1149 else if (name.compare("thread") == 0)
1150 {
1151 // thread in big endian hex
1152 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001153 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001154 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001155 if (!thread_sp)
1156 {
1157 // Create the thread if we need to
1158 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1159 m_thread_list.AddThread(thread_sp);
1160 }
Chris Lattner24943d22010-06-08 16:52:24 +00001161 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001162 else if (name.compare("hexname") == 0)
1163 {
1164 StringExtractor name_extractor;
1165 // Swap "value" over into "name_extractor"
1166 name_extractor.GetStringRef().swap(value);
1167 // Now convert the HEX bytes into a string value
1168 name_extractor.GetHexByteString (value);
1169 thread_name.swap (value);
1170 }
Chris Lattner24943d22010-06-08 16:52:24 +00001171 else if (name.compare("name") == 0)
1172 {
1173 thread_name.swap (value);
1174 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001175 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001176 {
1177 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1178 }
Greg Clayton65611552011-06-04 01:26:29 +00001179 else if (name.compare("reason") == 0)
1180 {
1181 reason.swap(value);
1182 }
1183 else if (name.compare("description") == 0)
1184 {
1185 StringExtractor desc_extractor;
1186 // Swap "value" over into "name_extractor"
1187 desc_extractor.GetStringRef().swap(value);
1188 // Now convert the HEX bytes into a string value
1189 desc_extractor.GetHexByteString (thread_name);
1190 }
Greg Claytona875b642011-01-09 21:07:35 +00001191 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1192 {
1193 // We have a register number that contains an expedited
1194 // register value. Lets supply this register to our thread
1195 // so it won't have to go and read it.
1196 if (thread_sp)
1197 {
1198 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1199
1200 if (reg != UINT32_MAX)
1201 {
1202 StringExtractor reg_value_extractor;
1203 // Swap "value" over into "reg_value_extractor"
1204 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001205 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1206 {
1207 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1208 name.c_str(),
1209 reg,
1210 reg,
1211 reg_value_extractor.GetStringRef().c_str(),
1212 stop_packet.GetStringRef().c_str());
1213 }
Greg Claytona875b642011-01-09 21:07:35 +00001214 }
1215 }
1216 }
Chris Lattner24943d22010-06-08 16:52:24 +00001217 }
Chris Lattner24943d22010-06-08 16:52:24 +00001218
1219 if (thread_sp)
1220 {
1221 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1222
1223 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001224 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001225 if (exc_type != 0)
1226 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001227 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001228
1229 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1230 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001231 exc_data_size,
1232 exc_data_size >= 1 ? exc_data[0] : 0,
1233 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001234 }
Greg Clayton65611552011-06-04 01:26:29 +00001235 else
Chris Lattner24943d22010-06-08 16:52:24 +00001236 {
Greg Clayton65611552011-06-04 01:26:29 +00001237 bool handled = false;
1238 if (!reason.empty())
1239 {
1240 if (reason.compare("trace") == 0)
1241 {
1242 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1243 handled = true;
1244 }
1245 else if (reason.compare("breakpoint") == 0)
1246 {
1247 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1248 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1249 if (bp_site_sp)
1250 {
1251 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1252 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1253 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1254 if (bp_site_sp->ValidForThisThread (gdb_thread))
1255 {
1256 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1257 handled = true;
1258 }
1259 }
1260
1261 if (!handled)
1262 {
1263 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1264 }
1265 }
1266 else if (reason.compare("trap") == 0)
1267 {
1268 // Let the trap just use the standard signal stop reason below...
1269 }
1270 else if (reason.compare("watchpoint") == 0)
1271 {
1272 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1273 // TODO: locate the watchpoint somehow...
1274 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1275 handled = true;
1276 }
1277 else if (reason.compare("exception") == 0)
1278 {
1279 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1280 handled = true;
1281 }
1282 }
1283
1284 if (signo)
1285 {
1286 if (signo == SIGTRAP)
1287 {
1288 // Currently we are going to assume SIGTRAP means we are either
1289 // hitting a breakpoint or hardware single stepping.
1290 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1291 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1292 if (bp_site_sp)
1293 {
1294 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1295 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1296 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1297 if (bp_site_sp->ValidForThisThread (gdb_thread))
1298 {
1299 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1300 handled = true;
1301 }
1302 }
1303 if (!handled)
1304 {
1305 // TODO: check for breakpoint or trap opcode in case there is a hard
1306 // coded software trap
1307 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1308 handled = true;
1309 }
1310 }
1311 if (!handled)
Greg Clayton643ee732010-08-04 01:40:35 +00001312 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001313 }
1314 else
1315 {
Greg Clayton643ee732010-08-04 01:40:35 +00001316 StopInfoSP invalid_stop_info_sp;
1317 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001318 }
Greg Clayton65611552011-06-04 01:26:29 +00001319
1320 if (!description.empty())
1321 {
1322 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1323 if (stop_info_sp)
1324 {
1325 stop_info_sp->SetDescription (description.c_str());
1326 }
1327 else
1328 {
1329 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1330 }
1331 }
1332 }
Chris Lattner24943d22010-06-08 16:52:24 +00001333 }
1334 return eStateStopped;
1335 }
1336 break;
1337
1338 case 'W':
1339 // process exited
1340 return eStateExited;
1341
1342 default:
1343 break;
1344 }
1345 return eStateInvalid;
1346}
1347
1348void
1349ProcessGDBRemote::RefreshStateAfterStop ()
1350{
Chris Lattner24943d22010-06-08 16:52:24 +00001351 // Let all threads recover from stopping and do any clean up based
1352 // on the previous thread state (if any).
1353 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001354 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001355}
1356
1357Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001358ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001359{
1360 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001361
Greg Claytona4881d02011-01-22 07:12:45 +00001362 bool timed_out = false;
1363 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001364
1365 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001366 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001367 // We are being asked to halt during an attach. We need to just close
1368 // our file handle and debugserver will go away, and we can be done...
1369 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001370 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001371 else
1372 {
1373 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1374 {
1375 if (timed_out)
1376 error.SetErrorString("timed out sending interrupt packet");
1377 else
1378 error.SetErrorString("unknown error sending interrupt packet");
1379 }
1380 }
Chris Lattner24943d22010-06-08 16:52:24 +00001381 return error;
1382}
1383
1384Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001385ProcessGDBRemote::InterruptIfRunning
1386(
1387 bool discard_thread_plans,
1388 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001389 EventSP &stop_event_sp
1390)
Chris Lattner24943d22010-06-08 16:52:24 +00001391{
1392 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001393
Greg Clayton2860ba92011-01-23 19:58:49 +00001394 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1395
Greg Clayton68ca8232011-01-25 02:58:48 +00001396 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001397 const bool is_running = m_gdb_comm.IsRunning();
1398 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001399 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001400 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001401 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001402 is_running);
1403
Greg Clayton2860ba92011-01-23 19:58:49 +00001404 if (discard_thread_plans)
1405 {
1406 if (log)
1407 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1408 m_thread_list.DiscardThreadPlans();
1409 }
1410 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001411 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001412 if (catch_stop_event)
1413 {
1414 if (log)
1415 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1416 PausePrivateStateThread();
1417 paused_private_state_thread = true;
1418 }
1419
Greg Clayton4fb400f2010-09-27 21:07:38 +00001420 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001421 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001422 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001423
Greg Clayton72e1c782011-01-22 23:43:18 +00001424 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001425 {
1426 if (timed_out)
1427 error.SetErrorString("timed out sending interrupt packet");
1428 else
1429 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001430 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001431 ResumePrivateStateThread();
1432 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001433 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001434
Greg Clayton72e1c782011-01-22 23:43:18 +00001435 if (catch_stop_event)
1436 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001437 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001438 TimeValue timeout_time;
1439 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001440 timeout_time.OffsetWithSeconds(5);
1441 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001442
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001443 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001444 if (log)
1445 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001446
Greg Clayton2860ba92011-01-23 19:58:49 +00001447 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001448 error.SetErrorString("unable to verify target stopped");
1449 }
1450
Greg Clayton68ca8232011-01-25 02:58:48 +00001451 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001452 {
1453 if (log)
1454 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001455 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001456 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001457 }
Chris Lattner24943d22010-06-08 16:52:24 +00001458 return error;
1459}
1460
Greg Clayton4fb400f2010-09-27 21:07:38 +00001461Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001462ProcessGDBRemote::WillDetach ()
1463{
Greg Clayton2860ba92011-01-23 19:58:49 +00001464 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1465 if (log)
1466 log->Printf ("ProcessGDBRemote::WillDetach()");
1467
Greg Clayton72e1c782011-01-22 23:43:18 +00001468 bool discard_thread_plans = true;
1469 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001470 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001471 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001472}
1473
1474Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001475ProcessGDBRemote::DoDetach()
1476{
1477 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001478 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001479 if (log)
1480 log->Printf ("ProcessGDBRemote::DoDetach()");
1481
1482 DisableAllBreakpointSites ();
1483
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001484 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001485
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001486 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1487 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001488 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001489 if (response_size)
1490 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1491 else
1492 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001493 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001494 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001495 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001496
Greg Clayton4fb400f2010-09-27 21:07:38 +00001497 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001498 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001499
1500 SetPrivateState (eStateDetached);
1501 ResumePrivateStateThread();
1502
1503 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001504 return error;
1505}
Chris Lattner24943d22010-06-08 16:52:24 +00001506
1507Error
1508ProcessGDBRemote::DoDestroy ()
1509{
1510 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001511 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001512 if (log)
1513 log->Printf ("ProcessGDBRemote::DoDestroy()");
1514
1515 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001516 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001517 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001518 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001519 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001520 // We are being asked to halt during an attach. We need to just close
1521 // our file handle and debugserver will go away, and we can be done...
1522 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001523 }
1524 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001525 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001526
1527 StringExtractorGDBRemote response;
1528 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001529 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001530 {
1531 char packet_cmd = response.GetChar(0);
1532
1533 if (packet_cmd == 'W' || packet_cmd == 'X')
1534 {
1535 m_last_stop_packet = response;
1536 SetExitStatus(response.GetHexU8(), NULL);
1537 }
1538 }
1539 else
1540 {
1541 SetExitStatus(SIGABRT, NULL);
1542 //error.SetErrorString("kill packet failed");
1543 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001544 }
1545 }
Chris Lattner24943d22010-06-08 16:52:24 +00001546 StopAsyncThread ();
1547 m_gdb_comm.StopReadThread();
1548 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001549 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001550 return error;
1551}
1552
Chris Lattner24943d22010-06-08 16:52:24 +00001553//------------------------------------------------------------------
1554// Process Queries
1555//------------------------------------------------------------------
1556
1557bool
1558ProcessGDBRemote::IsAlive ()
1559{
Greg Clayton58e844b2010-12-08 05:08:21 +00001560 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001561}
1562
1563addr_t
1564ProcessGDBRemote::GetImageInfoAddress()
1565{
1566 if (!m_gdb_comm.IsRunning())
1567 {
1568 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001569 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001570 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001571 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001572 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1573 }
1574 }
1575 return LLDB_INVALID_ADDRESS;
1576}
1577
Chris Lattner24943d22010-06-08 16:52:24 +00001578//------------------------------------------------------------------
1579// Process Memory
1580//------------------------------------------------------------------
1581size_t
1582ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1583{
1584 if (size > m_max_memory_size)
1585 {
1586 // Keep memory read sizes down to a sane limit. This function will be
1587 // called multiple times in order to complete the task by
1588 // lldb_private::Process so it is ok to do this.
1589 size = m_max_memory_size;
1590 }
1591
1592 char packet[64];
1593 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1594 assert (packet_len + 1 < sizeof(packet));
1595 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001596 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001597 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001598 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001599 {
1600 error.Clear();
1601 return response.GetHexBytes(buf, size, '\xdd');
1602 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001603 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001604 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001605 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001606 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1607 else
1608 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1609 }
1610 else
1611 {
1612 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1613 }
1614 return 0;
1615}
1616
1617size_t
1618ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1619{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001620 if (size > m_max_memory_size)
1621 {
1622 // Keep memory read sizes down to a sane limit. This function will be
1623 // called multiple times in order to complete the task by
1624 // lldb_private::Process so it is ok to do this.
1625 size = m_max_memory_size;
1626 }
1627
Chris Lattner24943d22010-06-08 16:52:24 +00001628 StreamString packet;
1629 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001630 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001631 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001632 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001633 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001634 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001635 {
1636 error.Clear();
1637 return size;
1638 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001639 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001640 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001641 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001642 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1643 else
1644 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1645 }
1646 else
1647 {
1648 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1649 }
1650 return 0;
1651}
1652
1653lldb::addr_t
1654ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1655{
Greg Clayton989816b2011-05-14 01:50:35 +00001656 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1657
Greg Clayton2f085c62011-05-15 01:25:55 +00001658 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001659 switch (supported)
1660 {
1661 case eLazyBoolCalculate:
1662 case eLazyBoolYes:
1663 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1664 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1665 return allocated_addr;
1666
1667 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001668 // Call mmap() to create memory in the inferior..
1669 unsigned prot = 0;
1670 if (permissions & lldb::ePermissionsReadable)
1671 prot |= eMmapProtRead;
1672 if (permissions & lldb::ePermissionsWritable)
1673 prot |= eMmapProtWrite;
1674 if (permissions & lldb::ePermissionsExecutable)
1675 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001676
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001677 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1678 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1679 m_addr_to_mmap_size[allocated_addr] = size;
1680 else
1681 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001682 break;
1683 }
1684
Chris Lattner24943d22010-06-08 16:52:24 +00001685 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001686 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001687 else
1688 error.Clear();
1689 return allocated_addr;
1690}
1691
1692Error
1693ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1694{
1695 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001696 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1697
1698 switch (supported)
1699 {
1700 case eLazyBoolCalculate:
1701 // We should never be deallocating memory without allocating memory
1702 // first so we should never get eLazyBoolCalculate
1703 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1704 break;
1705
1706 case eLazyBoolYes:
1707 if (!m_gdb_comm.DeallocateMemory (addr))
1708 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1709 break;
1710
1711 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001712 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001713 {
1714 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001715 if (pos != m_addr_to_mmap_size.end() &&
1716 InferiorCallMunmap(this, addr, pos->second))
1717 m_addr_to_mmap_size.erase (pos);
1718 else
1719 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001720 }
1721 break;
1722 }
1723
Chris Lattner24943d22010-06-08 16:52:24 +00001724 return error;
1725}
1726
1727
1728//------------------------------------------------------------------
1729// Process STDIO
1730//------------------------------------------------------------------
1731
1732size_t
1733ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1734{
1735 Mutex::Locker locker(m_stdio_mutex);
1736 size_t bytes_available = m_stdout_data.size();
1737 if (bytes_available > 0)
1738 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001739 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1740 if (log)
1741 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001742 if (bytes_available > buf_size)
1743 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001744 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001745 m_stdout_data.erase(0, buf_size);
1746 bytes_available = buf_size;
1747 }
1748 else
1749 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001750 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001751 m_stdout_data.clear();
1752
1753 //ResetEventBits(eBroadcastBitSTDOUT);
1754 }
1755 }
1756 return bytes_available;
1757}
1758
1759size_t
1760ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1761{
1762 // Can we get STDERR through the remote protocol?
1763 return 0;
1764}
1765
1766size_t
1767ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1768{
1769 if (m_stdio_communication.IsConnected())
1770 {
1771 ConnectionStatus status;
1772 m_stdio_communication.Write(src, src_len, status, NULL);
1773 }
1774 return 0;
1775}
1776
1777Error
1778ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1779{
1780 Error error;
1781 assert (bp_site != NULL);
1782
Greg Claytone005f2c2010-11-06 01:53:30 +00001783 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001784 user_id_t site_id = bp_site->GetID();
1785 const addr_t addr = bp_site->GetLoadAddress();
1786 if (log)
1787 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1788
1789 if (bp_site->IsEnabled())
1790 {
1791 if (log)
1792 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1793 return error;
1794 }
1795 else
1796 {
1797 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1798
1799 if (bp_site->HardwarePreferred())
1800 {
1801 // Try and set hardware breakpoint, and if that fails, fall through
1802 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001803 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001804 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001805 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001806 {
1807 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001808 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001809 return error;
1810 }
Chris Lattner24943d22010-06-08 16:52:24 +00001811 }
1812 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001813
1814 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001815 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001816 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1817 {
1818 bp_site->SetEnabled(true);
1819 bp_site->SetType (BreakpointSite::eExternal);
1820 return error;
1821 }
Chris Lattner24943d22010-06-08 16:52:24 +00001822 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001823
1824 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001825 }
1826
1827 if (log)
1828 {
1829 const char *err_string = error.AsCString();
1830 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1831 bp_site->GetLoadAddress(),
1832 err_string ? err_string : "NULL");
1833 }
1834 // We shouldn't reach here on a successful breakpoint enable...
1835 if (error.Success())
1836 error.SetErrorToGenericError();
1837 return error;
1838}
1839
1840Error
1841ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1842{
1843 Error error;
1844 assert (bp_site != NULL);
1845 addr_t addr = bp_site->GetLoadAddress();
1846 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001847 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001848 if (log)
1849 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1850
1851 if (bp_site->IsEnabled())
1852 {
1853 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1854
Greg Claytonb72d0f02011-04-12 05:54:46 +00001855 BreakpointSite::Type bp_type = bp_site->GetType();
1856 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001857 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001858 case BreakpointSite::eSoftware:
1859 error = DisableSoftwareBreakpoint (bp_site);
1860 break;
1861
1862 case BreakpointSite::eHardware:
1863 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1864 error.SetErrorToGenericError();
1865 break;
1866
1867 case BreakpointSite::eExternal:
1868 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1869 error.SetErrorToGenericError();
1870 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001871 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001872 if (error.Success())
1873 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001874 }
1875 else
1876 {
1877 if (log)
1878 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1879 return error;
1880 }
1881
1882 if (error.Success())
1883 error.SetErrorToGenericError();
1884 return error;
1885}
1886
1887Error
1888ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1889{
1890 Error error;
1891 if (wp)
1892 {
1893 user_id_t watchID = wp->GetID();
1894 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001895 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001896 if (log)
1897 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1898 if (wp->IsEnabled())
1899 {
1900 if (log)
1901 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1902 return error;
1903 }
1904 else
1905 {
1906 // Pass down an appropriate z/Z packet...
1907 error.SetErrorString("watchpoints not supported");
1908 }
1909 }
1910 else
1911 {
1912 error.SetErrorString("Watchpoint location argument was NULL.");
1913 }
1914 if (error.Success())
1915 error.SetErrorToGenericError();
1916 return error;
1917}
1918
1919Error
1920ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1921{
1922 Error error;
1923 if (wp)
1924 {
1925 user_id_t watchID = wp->GetID();
1926
Greg Claytone005f2c2010-11-06 01:53:30 +00001927 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001928
1929 addr_t addr = wp->GetLoadAddress();
1930 if (log)
1931 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1932
1933 if (wp->IsHardware())
1934 {
1935 // Pass down an appropriate z/Z packet...
1936 error.SetErrorString("watchpoints not supported");
1937 }
1938 // TODO: clear software watchpoints if we implement them
1939 }
1940 else
1941 {
1942 error.SetErrorString("Watchpoint location argument was NULL.");
1943 }
1944 if (error.Success())
1945 error.SetErrorToGenericError();
1946 return error;
1947}
1948
1949void
1950ProcessGDBRemote::Clear()
1951{
1952 m_flags = 0;
1953 m_thread_list.Clear();
1954 {
1955 Mutex::Locker locker(m_stdio_mutex);
1956 m_stdout_data.clear();
1957 }
Chris Lattner24943d22010-06-08 16:52:24 +00001958}
1959
1960Error
1961ProcessGDBRemote::DoSignal (int signo)
1962{
1963 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001964 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001965 if (log)
1966 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1967
1968 if (!m_gdb_comm.SendAsyncSignal (signo))
1969 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1970 return error;
1971}
1972
Chris Lattner24943d22010-06-08 16:52:24 +00001973Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00001974ProcessGDBRemote::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 +00001975{
1976 Error error;
1977 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1978 {
1979 // If we locate debugserver, keep that located version around
1980 static FileSpec g_debugserver_file_spec;
1981
Greg Claytonb72d0f02011-04-12 05:54:46 +00001982 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00001983 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00001984 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00001985
1986 // Always check to see if we have an environment override for the path
1987 // to the debugserver to use and use it if we do.
1988 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1989 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001990 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001991 else
1992 debugserver_file_spec = g_debugserver_file_spec;
1993 bool debugserver_exists = debugserver_file_spec.Exists();
1994 if (!debugserver_exists)
1995 {
1996 // The debugserver binary is in the LLDB.framework/Resources
1997 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001998 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001999 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002000 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002001 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002002 if (debugserver_exists)
2003 {
2004 g_debugserver_file_spec = debugserver_file_spec;
2005 }
2006 else
2007 {
2008 g_debugserver_file_spec.Clear();
2009 debugserver_file_spec.Clear();
2010 }
Chris Lattner24943d22010-06-08 16:52:24 +00002011 }
2012 }
2013
2014 if (debugserver_exists)
2015 {
2016 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2017
2018 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002019
Greg Claytone005f2c2010-11-06 01:53:30 +00002020 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002021
Greg Claytonb72d0f02011-04-12 05:54:46 +00002022 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002023 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002024
Chris Lattner24943d22010-06-08 16:52:24 +00002025 // Start args with "debugserver /file/path -r --"
2026 debugserver_args.AppendArgument(debugserver_path);
2027 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002028 // use native registers, not the GDB registers
2029 debugserver_args.AppendArgument("--native-regs");
2030 // make debugserver run in its own session so signals generated by
2031 // special terminal key sequences (^C) don't affect debugserver
2032 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002033
Chris Lattner24943d22010-06-08 16:52:24 +00002034 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2035 if (env_debugserver_log_file)
2036 {
2037 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2038 debugserver_args.AppendArgument(arg_cstr);
2039 }
2040
2041 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2042 if (env_debugserver_log_flags)
2043 {
2044 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2045 debugserver_args.AppendArgument(arg_cstr);
2046 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002047// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002048// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002049
Greg Claytonb72d0f02011-04-12 05:54:46 +00002050 // We currently send down all arguments, attach pids, or attach
2051 // process names in dedicated GDB server packets, so we don't need
2052 // to pass them as arguments. This is currently because of all the
2053 // things we need to setup prior to launching: the environment,
2054 // current working dir, file actions, etc.
2055#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002056 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002057 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002058 {
Greg Claytona2f74232011-02-24 22:24:29 +00002059 // Terminate the debugserver args so we can now append the inferior args
2060 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002061
Greg Claytona2f74232011-02-24 22:24:29 +00002062 for (int i = 0; inferior_argv[i] != NULL; ++i)
2063 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002064 }
2065 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2066 {
2067 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2068 debugserver_args.AppendArgument (arg_cstr);
2069 }
2070 else if (attach_name && attach_name[0])
2071 {
2072 if (wait_for_launch)
2073 debugserver_args.AppendArgument ("--waitfor");
2074 else
2075 debugserver_args.AppendArgument ("--attach");
2076 debugserver_args.AppendArgument (attach_name);
2077 }
Chris Lattner24943d22010-06-08 16:52:24 +00002078#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002079
2080 ProcessLaunchInfo::FileAction file_action;
2081
2082 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2083 // to "/dev/null" if we run into any problems.
2084 file_action.Close (STDIN_FILENO);
2085 launch_info.AppendFileAction (file_action);
2086 file_action.Close (STDOUT_FILENO);
2087 launch_info.AppendFileAction (file_action);
2088 file_action.Close (STDERR_FILENO);
2089 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002090
2091 if (log)
2092 {
2093 StreamString strm;
2094 debugserver_args.Dump (&strm);
2095 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2096 }
2097
Greg Claytonb72d0f02011-04-12 05:54:46 +00002098 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002099
Greg Claytonb72d0f02011-04-12 05:54:46 +00002100 if (error.Success ())
2101 m_debugserver_pid = launch_info.GetProcessID();
2102 else
Chris Lattner24943d22010-06-08 16:52:24 +00002103 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2104
2105 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002106 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002107 }
2108 else
2109 {
2110 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2111 }
2112
2113 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2114 StartAsyncThread ();
2115 }
2116 return error;
2117}
2118
2119bool
2120ProcessGDBRemote::MonitorDebugserverProcess
2121(
2122 void *callback_baton,
2123 lldb::pid_t debugserver_pid,
2124 int signo, // Zero for no signal
2125 int exit_status // Exit value of process if signal is zero
2126)
2127{
2128 // We pass in the ProcessGDBRemote inferior process it and name it
2129 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2130 // pointer value itself, thus we need the double cast...
2131
2132 // "debugserver_pid" argument passed in is the process ID for
2133 // debugserver that we are tracking...
2134
Greg Clayton75ccf502010-08-21 02:22:51 +00002135 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002136
2137 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2138 if (log)
2139 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2140
Greg Clayton75ccf502010-08-21 02:22:51 +00002141 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002142 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002143 // Sleep for a half a second to make sure our inferior process has
2144 // time to set its exit status before we set it incorrectly when
2145 // both the debugserver and the inferior process shut down.
2146 usleep (500000);
2147 // If our process hasn't yet exited, debugserver might have died.
2148 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002149 const StateType state = process->GetState();
2150
2151 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2152 state != eStateInvalid &&
2153 state != eStateUnloaded &&
2154 state != eStateExited &&
2155 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002156 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002157 char error_str[1024];
2158 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002159 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002160 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2161 if (signal_cstr)
2162 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002163 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002164 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002165 }
2166 else
2167 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002168 ::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 +00002169 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002170
2171 process->SetExitStatus (-1, error_str);
2172 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002173 // Debugserver has exited we need to let our ProcessGDBRemote
2174 // know that it no longer has a debugserver instance
2175 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2176 // We are returning true to this function below, so we can
2177 // forget about the monitor handle.
2178 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002179 }
2180 return true;
2181}
2182
2183void
2184ProcessGDBRemote::KillDebugserverProcess ()
2185{
2186 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2187 {
2188 ::kill (m_debugserver_pid, SIGINT);
2189 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2190 }
2191}
2192
2193void
2194ProcessGDBRemote::Initialize()
2195{
2196 static bool g_initialized = false;
2197
2198 if (g_initialized == false)
2199 {
2200 g_initialized = true;
2201 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2202 GetPluginDescriptionStatic(),
2203 CreateInstance);
2204
2205 Log::Callbacks log_callbacks = {
2206 ProcessGDBRemoteLog::DisableLog,
2207 ProcessGDBRemoteLog::EnableLog,
2208 ProcessGDBRemoteLog::ListLogCategories
2209 };
2210
2211 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2212 }
2213}
2214
2215bool
Chris Lattner24943d22010-06-08 16:52:24 +00002216ProcessGDBRemote::StartAsyncThread ()
2217{
Greg Claytone005f2c2010-11-06 01:53:30 +00002218 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002219
2220 if (log)
2221 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2222
2223 // Create a thread that watches our internal state and controls which
2224 // events make it to clients (into the DCProcess event queue).
2225 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002226 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002227}
2228
2229void
2230ProcessGDBRemote::StopAsyncThread ()
2231{
Greg Claytone005f2c2010-11-06 01:53:30 +00002232 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002233
2234 if (log)
2235 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2236
2237 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2238
2239 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002240 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002241 {
2242 Host::ThreadJoin (m_async_thread, NULL, NULL);
2243 }
2244}
2245
2246
2247void *
2248ProcessGDBRemote::AsyncThread (void *arg)
2249{
2250 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2251
Greg Claytone005f2c2010-11-06 01:53:30 +00002252 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002253 if (log)
2254 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2255
2256 Listener listener ("ProcessGDBRemote::AsyncThread");
2257 EventSP event_sp;
2258 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2259 eBroadcastBitAsyncThreadShouldExit;
2260
2261 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2262 {
Greg Claytona2f74232011-02-24 22:24:29 +00002263 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2264
Chris Lattner24943d22010-06-08 16:52:24 +00002265 bool done = false;
2266 while (!done)
2267 {
2268 if (log)
2269 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2270 if (listener.WaitForEvent (NULL, event_sp))
2271 {
2272 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002273 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002274 {
Greg Claytona2f74232011-02-24 22:24:29 +00002275 if (log)
2276 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 +00002277
Greg Claytona2f74232011-02-24 22:24:29 +00002278 switch (event_type)
2279 {
2280 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002281 {
Greg Claytona2f74232011-02-24 22:24:29 +00002282 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002283
Greg Claytona2f74232011-02-24 22:24:29 +00002284 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002285 {
Greg Claytona2f74232011-02-24 22:24:29 +00002286 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2287 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2288 if (log)
2289 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002290
Greg Claytona2f74232011-02-24 22:24:29 +00002291 if (::strstr (continue_cstr, "vAttach") == NULL)
2292 process->SetPrivateState(eStateRunning);
2293 StringExtractorGDBRemote response;
2294 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002295
Greg Claytona2f74232011-02-24 22:24:29 +00002296 switch (stop_state)
2297 {
2298 case eStateStopped:
2299 case eStateCrashed:
2300 case eStateSuspended:
2301 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002302 process->SetPrivateState (stop_state);
2303 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002304
Greg Claytona2f74232011-02-24 22:24:29 +00002305 case eStateExited:
2306 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002307 response.SetFilePos(1);
2308 process->SetExitStatus(response.GetHexU8(), NULL);
2309 done = true;
2310 break;
2311
2312 case eStateInvalid:
2313 process->SetExitStatus(-1, "lost connection");
2314 break;
2315
2316 default:
2317 process->SetPrivateState (stop_state);
2318 break;
2319 }
Chris Lattner24943d22010-06-08 16:52:24 +00002320 }
2321 }
Greg Claytona2f74232011-02-24 22:24:29 +00002322 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002323
Greg Claytona2f74232011-02-24 22:24:29 +00002324 case eBroadcastBitAsyncThreadShouldExit:
2325 if (log)
2326 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2327 done = true;
2328 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002329
Greg Claytona2f74232011-02-24 22:24:29 +00002330 default:
2331 if (log)
2332 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2333 done = true;
2334 break;
2335 }
2336 }
2337 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2338 {
2339 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2340 {
2341 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002342 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002343 }
Chris Lattner24943d22010-06-08 16:52:24 +00002344 }
2345 }
2346 else
2347 {
2348 if (log)
2349 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2350 done = true;
2351 }
2352 }
2353 }
2354
2355 if (log)
2356 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2357
2358 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2359 return NULL;
2360}
2361
Chris Lattner24943d22010-06-08 16:52:24 +00002362const char *
2363ProcessGDBRemote::GetDispatchQueueNameForThread
2364(
2365 addr_t thread_dispatch_qaddr,
2366 std::string &dispatch_queue_name
2367)
2368{
2369 dispatch_queue_name.clear();
2370 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2371 {
2372 // Cache the dispatch_queue_offsets_addr value so we don't always have
2373 // to look it up
2374 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2375 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002376 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2377 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002378 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002379 if (module_sp)
2380 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2381
2382 if (dispatch_queue_offsets_symbol == NULL)
2383 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002384 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002385 if (module_sp)
2386 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2387 }
Chris Lattner24943d22010-06-08 16:52:24 +00002388 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002389 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002390
2391 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2392 return NULL;
2393 }
2394
2395 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002396 DataExtractor data (memory_buffer,
2397 sizeof(memory_buffer),
2398 m_target.GetArchitecture().GetByteOrder(),
2399 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002400
2401 // Excerpt from src/queue_private.h
2402 struct dispatch_queue_offsets_s
2403 {
2404 uint16_t dqo_version;
2405 uint16_t dqo_label;
2406 uint16_t dqo_label_size;
2407 } dispatch_queue_offsets;
2408
2409
2410 Error error;
2411 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2412 {
2413 uint32_t data_offset = 0;
2414 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2415 {
2416 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2417 {
2418 data_offset = 0;
2419 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2420 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2421 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2422 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2423 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2424 dispatch_queue_name.erase (bytes_read);
2425 }
2426 }
2427 }
2428 }
2429 if (dispatch_queue_name.empty())
2430 return NULL;
2431 return dispatch_queue_name.c_str();
2432}
2433
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002434//uint32_t
2435//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2436//{
2437// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2438// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2439// if (m_local_debugserver)
2440// {
2441// return Host::ListProcessesMatchingName (name, matches, pids);
2442// }
2443// else
2444// {
2445// // FIXME: Implement talking to the remote debugserver.
2446// return 0;
2447// }
2448//
2449//}
2450//
Jim Ingham55e01d82011-01-22 01:33:44 +00002451bool
2452ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2453 lldb_private::StoppointCallbackContext *context,
2454 lldb::user_id_t break_id,
2455 lldb::user_id_t break_loc_id)
2456{
2457 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2458 // run so I can stop it if that's what I want to do.
2459 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2460 if (log)
2461 log->Printf("Hit New Thread Notification breakpoint.");
2462 return false;
2463}
2464
2465
2466bool
2467ProcessGDBRemote::StartNoticingNewThreads()
2468{
2469 static const char *bp_names[] =
2470 {
2471 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002472 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002473 "_pthread_start",
2474 NULL
2475 };
2476
2477 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2478 size_t num_bps = m_thread_observation_bps.size();
2479 if (num_bps != 0)
2480 {
2481 for (int i = 0; i < num_bps; i++)
2482 {
2483 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2484 if (break_sp)
2485 {
2486 if (log)
2487 log->Printf("Enabled noticing new thread breakpoint.");
2488 break_sp->SetEnabled(true);
2489 }
2490 }
2491 }
2492 else
2493 {
2494 for (int i = 0; bp_names[i] != NULL; i++)
2495 {
2496 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2497 if (breakpoint)
2498 {
2499 if (log)
2500 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2501 m_thread_observation_bps.push_back(breakpoint->GetID());
2502 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2503 }
2504 else
2505 {
2506 if (log)
2507 log->Printf("Failed to create new thread notification breakpoint.");
2508 return false;
2509 }
2510 }
2511 }
2512
2513 return true;
2514}
2515
2516bool
2517ProcessGDBRemote::StopNoticingNewThreads()
2518{
Jim Inghamff276fe2011-02-08 05:19:01 +00002519 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2520 if (log)
2521 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002522 size_t num_bps = m_thread_observation_bps.size();
2523 if (num_bps != 0)
2524 {
2525 for (int i = 0; i < num_bps; i++)
2526 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002527
2528 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2529 if (break_sp)
2530 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002531 break_sp->SetEnabled(false);
2532 }
2533 }
2534 }
2535 return true;
2536}
2537
2538