blob: fe4e06820fcaef8d85a7ac3af7a99277ae49cfc2 [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>
Chris Lattner24943d22010-06-08 16:52:24 +000013#include <sys/types.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <sys/stat.h>
Chris Lattner24943d22010-06-08 16:52:24 +000015
16// C++ Includes
17#include <algorithm>
18#include <map>
19
20// Other libraries and framework includes
21
22#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000023#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/ArchSpec.h"
25#include "lldb/Core/Debugger.h"
26#include "lldb/Core/ConnectionFileDescriptor.h"
27#include "lldb/Core/FileSpec.h"
28#include "lldb/Core/InputReader.h"
29#include "lldb/Core/Module.h"
30#include "lldb/Core/PluginManager.h"
31#include "lldb/Core/State.h"
32#include "lldb/Core/StreamString.h"
33#include "lldb/Core/Timer.h"
34#include "lldb/Host/TimeValue.h"
35#include "lldb/Symbol/ObjectFile.h"
36#include "lldb/Target/DynamicLoader.h"
37#include "lldb/Target/Target.h"
38#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000039#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
41// Project includes
42#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000043#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "GDBRemoteRegisterContext.h"
45#include "ProcessGDBRemote.h"
46#include "ProcessGDBRemoteLog.h"
47#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000048#include "StopInfoMachException.h"
49
Chris Lattner24943d22010-06-08 16:52:24 +000050
Chris Lattner24943d22010-06-08 16:52:24 +000051
52#define DEBUGSERVER_BASENAME "debugserver"
53using namespace lldb;
54using namespace lldb_private;
55
56static inline uint16_t
57get_random_port ()
58{
59 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u;
60}
61
62
63const char *
64ProcessGDBRemote::GetPluginNameStatic()
65{
66 return "process.gdb-remote";
67}
68
69const char *
70ProcessGDBRemote::GetPluginDescriptionStatic()
71{
72 return "GDB Remote protocol based debugging plug-in.";
73}
74
75void
76ProcessGDBRemote::Terminate()
77{
78 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
79}
80
81
82Process*
83ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
84{
85 return new ProcessGDBRemote (target, listener);
86}
87
88bool
89ProcessGDBRemote::CanDebug(Target &target)
90{
91 // For now we are just making sure the file exists for a given module
92 ModuleSP exe_module_sp(target.GetExecutableModule());
93 if (exe_module_sp.get())
94 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +000095 // However, if there is no executable module, we return true since we might be preparing to attach.
96 return true;
Chris Lattner24943d22010-06-08 16:52:24 +000097}
98
99//----------------------------------------------------------------------
100// ProcessGDBRemote constructor
101//----------------------------------------------------------------------
102ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
103 Process (target, listener),
104 m_dynamic_loader_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000105 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000106 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000107 m_gdb_comm(),
108 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000109 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000110 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000111 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000112 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
113 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000114 m_curr_tid (LLDB_INVALID_THREAD_ID),
115 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000116 m_z0_supported (1),
117 m_continue_packet(),
118 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000119 m_packet_timeout (1),
120 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000121 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000122 m_local_debugserver (true),
123 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000124{
125}
126
127//----------------------------------------------------------------------
128// Destructor
129//----------------------------------------------------------------------
130ProcessGDBRemote::~ProcessGDBRemote()
131{
Greg Claytonff5cac22010-12-13 18:11:18 +0000132 m_dynamic_loader_ap.reset();
133
Greg Clayton75ccf502010-08-21 02:22:51 +0000134 if (m_debugserver_thread != LLDB_INVALID_HOST_THREAD)
135 {
136 Host::ThreadCancel (m_debugserver_thread, NULL);
137 thread_result_t thread_result;
138 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
139 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
140 }
Chris Lattner24943d22010-06-08 16:52:24 +0000141 // m_mach_process.UnregisterNotificationCallbacks (this);
142 Clear();
143}
144
145//----------------------------------------------------------------------
146// PluginInterface
147//----------------------------------------------------------------------
148const char *
149ProcessGDBRemote::GetPluginName()
150{
151 return "Process debugging plug-in that uses the GDB remote protocol";
152}
153
154const char *
155ProcessGDBRemote::GetShortPluginName()
156{
157 return GetPluginNameStatic();
158}
159
160uint32_t
161ProcessGDBRemote::GetPluginVersion()
162{
163 return 1;
164}
165
166void
167ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
168{
169 strm->Printf("TODO: fill this in\n");
170}
171
172Error
173ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
174{
175 Error error;
176 error.SetErrorString("No plug-in commands are currently supported.");
177 return error;
178}
179
180Log *
181ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
182{
183 return NULL;
184}
185
186void
187ProcessGDBRemote::BuildDynamicRegisterInfo ()
188{
189 char register_info_command[64];
190 m_register_info.Clear();
191 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
192 uint32_t reg_offset = 0;
193 uint32_t reg_num = 0;
194 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
195 {
196 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
197 StringExtractorGDBRemote response;
198 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
199 {
200 packet_type = response.GetType();
201 if (packet_type == StringExtractorGDBRemote::eResponse)
202 {
203 std::string name;
204 std::string value;
205 ConstString reg_name;
206 ConstString alt_name;
207 ConstString set_name;
208 RegisterInfo reg_info = { NULL, // Name
209 NULL, // Alt name
210 0, // byte size
211 reg_offset, // offset
212 eEncodingUint, // encoding
213 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000214 {
215 LLDB_INVALID_REGNUM, // GCC reg num
216 LLDB_INVALID_REGNUM, // DWARF reg num
217 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000218 reg_num, // GDB reg num
219 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000220 }
221 };
222
223 while (response.GetNameColonValue(name, value))
224 {
225 if (name.compare("name") == 0)
226 {
227 reg_name.SetCString(value.c_str());
228 }
229 else if (name.compare("alt-name") == 0)
230 {
231 alt_name.SetCString(value.c_str());
232 }
233 else if (name.compare("bitsize") == 0)
234 {
235 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
236 }
237 else if (name.compare("offset") == 0)
238 {
239 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000240 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000241 {
242 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000243 }
244 }
245 else if (name.compare("encoding") == 0)
246 {
247 if (value.compare("uint") == 0)
248 reg_info.encoding = eEncodingUint;
249 else if (value.compare("sint") == 0)
250 reg_info.encoding = eEncodingSint;
251 else if (value.compare("ieee754") == 0)
252 reg_info.encoding = eEncodingIEEE754;
253 else if (value.compare("vector") == 0)
254 reg_info.encoding = eEncodingVector;
255 }
256 else if (name.compare("format") == 0)
257 {
258 if (value.compare("binary") == 0)
259 reg_info.format = eFormatBinary;
260 else if (value.compare("decimal") == 0)
261 reg_info.format = eFormatDecimal;
262 else if (value.compare("hex") == 0)
263 reg_info.format = eFormatHex;
264 else if (value.compare("float") == 0)
265 reg_info.format = eFormatFloat;
266 else if (value.compare("vector-sint8") == 0)
267 reg_info.format = eFormatVectorOfSInt8;
268 else if (value.compare("vector-uint8") == 0)
269 reg_info.format = eFormatVectorOfUInt8;
270 else if (value.compare("vector-sint16") == 0)
271 reg_info.format = eFormatVectorOfSInt16;
272 else if (value.compare("vector-uint16") == 0)
273 reg_info.format = eFormatVectorOfUInt16;
274 else if (value.compare("vector-sint32") == 0)
275 reg_info.format = eFormatVectorOfSInt32;
276 else if (value.compare("vector-uint32") == 0)
277 reg_info.format = eFormatVectorOfUInt32;
278 else if (value.compare("vector-float32") == 0)
279 reg_info.format = eFormatVectorOfFloat32;
280 else if (value.compare("vector-uint128") == 0)
281 reg_info.format = eFormatVectorOfUInt128;
282 }
283 else if (name.compare("set") == 0)
284 {
285 set_name.SetCString(value.c_str());
286 }
287 else if (name.compare("gcc") == 0)
288 {
289 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
290 }
291 else if (name.compare("dwarf") == 0)
292 {
293 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
294 }
295 else if (name.compare("generic") == 0)
296 {
297 if (value.compare("pc") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
299 else if (value.compare("sp") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
301 else if (value.compare("fp") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
303 else if (value.compare("ra") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
305 else if (value.compare("flags") == 0)
306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
307 }
308 }
309
Jason Molenda53d96862010-06-11 23:44:18 +0000310 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000311 assert (reg_info.byte_size != 0);
312 reg_offset += reg_info.byte_size;
313 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
314 }
315 }
316 else
317 {
318 packet_type = StringExtractorGDBRemote::eError;
319 }
320 }
321
322 if (reg_num == 0)
323 {
324 // We didn't get anything. See if we are debugging ARM and fill with
325 // a hard coded register set until we can get an updated debugserver
326 // down on the devices.
327 ArchSpec arm_arch ("arm");
328 if (GetTarget().GetArchitecture() == arm_arch)
329 m_register_info.HardcodeARMRegisters();
330 }
331 m_register_info.Finalize ();
332}
333
334Error
335ProcessGDBRemote::WillLaunch (Module* module)
336{
337 return WillLaunchOrAttach ();
338}
339
340Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000341ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000342{
343 return WillLaunchOrAttach ();
344}
345
346Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000347ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000348{
349 return WillLaunchOrAttach ();
350}
351
352Error
353ProcessGDBRemote::WillLaunchOrAttach ()
354{
355 Error error;
356 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
357 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
358
359 if (m_dynamic_loader_ap.get() == NULL)
360 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
361 m_stdio_communication.Clear ();
362
363 return error;
364}
365
366//----------------------------------------------------------------------
367// Process Control
368//----------------------------------------------------------------------
369Error
370ProcessGDBRemote::DoLaunch
371(
372 Module* module,
373 char const *argv[],
374 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000375 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000376 const char *stdin_path,
377 const char *stdout_path,
378 const char *stderr_path
379)
380{
Greg Clayton4b407112010-09-30 21:49:03 +0000381 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000382 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
383 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
384 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000385
386 ObjectFile * object_file = module->GetObjectFile();
387 if (object_file)
388 {
389 ArchSpec inferior_arch(module->GetArchitecture());
390 char host_port[128];
391 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
392
Greg Clayton23cf0c72010-11-08 04:29:11 +0000393 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000394 bool start_debugserver_with_inferior_args = false;
395 if (start_debugserver_with_inferior_args)
396 {
397 // We want to launch debugserver with the inferior program and its
398 // arguments on the command line. We should only do this if we
399 // the GDB server we are talking to doesn't support the 'A' packet.
400 error = StartDebugserverProcess (host_port,
401 argv,
402 envp,
403 NULL, //stdin_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000404 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000405 LLDB_INVALID_PROCESS_ID,
406 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000407 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000408 inferior_arch);
409 if (error.Fail())
410 return error;
411
412 error = ConnectToDebugserver (host_port);
413 if (error.Success())
414 {
415 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
416 }
417 }
418 else
419 {
420 error = StartDebugserverProcess (host_port,
421 NULL,
422 NULL,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000423 NULL, //stdin_path
424 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000425 LLDB_INVALID_PROCESS_ID,
426 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000427 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000428 inferior_arch);
429 if (error.Fail())
430 return error;
431
432 error = ConnectToDebugserver (host_port);
433 if (error.Success())
434 {
435 // Send the environment and the program + arguments after we connect
436 if (envp)
437 {
438 const char *env_entry;
439 for (int i=0; (env_entry = envp[i]); ++i)
440 {
441 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
442 break;
443 }
444 }
445
Greg Clayton960d6a42010-08-03 00:35:52 +0000446 // FIXME: convert this to use the new set/show variables when they are available
447#if 0
448 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
449 {
450 const uint32_t attach_debugserver_secs = 10;
451 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
452 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
453 {
454 printf ("%i\n", attach_debugserver_secs - i);
455 sleep (1);
456 }
457 }
458#endif
459
Chris Lattner24943d22010-06-08 16:52:24 +0000460 const uint32_t arg_timeout_seconds = 10;
461 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
462 if (arg_packet_err == 0)
463 {
464 std::string error_str;
465 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
466 {
467 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
468 }
469 else
470 {
471 error.SetErrorString (error_str.c_str());
472 }
473 }
474 else
475 {
476 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
477 }
478
479 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
480 }
481 }
482
483 if (GetID() == LLDB_INVALID_PROCESS_ID)
484 {
485 KillDebugserverProcess ();
486 return error;
487 }
488
489 StringExtractorGDBRemote response;
490 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
491 SetPrivateState (SetThreadStopInfo (response));
492
493 }
494 else
495 {
496 // Set our user ID to an invalid process ID.
497 SetID(LLDB_INVALID_PROCESS_ID);
498 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
499 }
Chris Lattner24943d22010-06-08 16:52:24 +0000500 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000501
Chris Lattner24943d22010-06-08 16:52:24 +0000502}
503
504
505Error
506ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
507{
508 Error error;
509 // Sleep and wait a bit for debugserver to start to listen...
510 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
511 if (conn_ap.get())
512 {
513 std::string connect_url("connect://");
514 connect_url.append (host_port);
515 const uint32_t max_retry_count = 50;
516 uint32_t retry_count = 0;
517 while (!m_gdb_comm.IsConnected())
518 {
519 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
520 {
521 m_gdb_comm.SetConnection (conn_ap.release());
522 break;
523 }
524 retry_count++;
525
526 if (retry_count >= max_retry_count)
527 break;
528
529 usleep (100000);
530 }
531 }
532
533 if (!m_gdb_comm.IsConnected())
534 {
535 if (error.Success())
536 error.SetErrorString("not connected to remote gdb server");
537 return error;
538 }
539
540 m_gdb_comm.SetAckMode (true);
541 if (m_gdb_comm.StartReadThread(&error))
542 {
543 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000544 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000545
546 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000547 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
548 this,
549 m_debugserver_pid,
550 false);
551
Chris Lattner24943d22010-06-08 16:52:24 +0000552 StringExtractorGDBRemote response;
553 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
554 {
555 if (response.IsOKPacket())
556 m_gdb_comm.SetAckMode (false);
557 }
Greg Claytonc71899e2011-01-18 19:36:39 +0000558
559 if (m_gdb_comm.SendPacketAndWaitForResponse("QThreadSuffixSupported", response, 1, false))
560 {
561 if (response.IsOKPacket())
562 m_gdb_comm.SetThreadSuffixSupported (true);
563 }
564
Chris Lattner24943d22010-06-08 16:52:24 +0000565 }
566 return error;
567}
568
569void
570ProcessGDBRemote::DidLaunchOrAttach ()
571{
572 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
573 if (GetID() == LLDB_INVALID_PROCESS_ID)
574 {
575 m_dynamic_loader_ap.reset();
576 }
577 else
578 {
579 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
580
Greg Clayton20d338f2010-11-18 05:57:03 +0000581 BuildDynamicRegisterInfo ();
582
583 m_byte_order = m_gdb_comm.GetByteOrder();
584
Chris Lattner24943d22010-06-08 16:52:24 +0000585 StreamString strm;
586
587 ArchSpec inferior_arch;
588 // See if the GDB server supports the qHostInfo information
589 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
590 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Clayton20d338f2010-11-18 05:57:03 +0000591 ArchSpec arch_spec (GetTarget().GetArchitecture());
Chris Lattner24943d22010-06-08 16:52:24 +0000592
Jim Ingham7508e732010-08-09 23:31:02 +0000593 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000594 {
595 // For ARM we can't trust the arch of the process as it could
596 // have an armv6 object file, but be running on armv7 kernel.
597 inferior_arch = m_gdb_comm.GetHostArchitecture();
598 }
599
600 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000601 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000602
603 if (vendor == NULL)
604 vendor = Host::GetVendorString().AsCString("apple");
605
606 if (os_type == NULL)
607 os_type = Host::GetOSString().AsCString("darwin");
608
609 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
610
611 std::transform (strm.GetString().begin(),
612 strm.GetString().end(),
613 strm.GetString().begin(),
614 ::tolower);
615
616 m_target_triple.SetCString(strm.GetString().c_str());
617 }
618}
619
620void
621ProcessGDBRemote::DidLaunch ()
622{
623 DidLaunchOrAttach ();
624 if (m_dynamic_loader_ap.get())
625 m_dynamic_loader_ap->DidLaunch();
626}
627
628Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000629ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000630{
631 Error error;
632 // Clear out and clean up from any current state
633 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000634 ArchSpec arch_spec = GetTarget().GetArchitecture();
635
Greg Claytone005f2c2010-11-06 01:53:30 +0000636 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000637
638
Chris Lattner24943d22010-06-08 16:52:24 +0000639 if (attach_pid != LLDB_INVALID_PROCESS_ID)
640 {
Chris Lattner24943d22010-06-08 16:52:24 +0000641 char host_port[128];
642 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000643 error = StartDebugserverProcess (host_port, // debugserver_url
644 NULL, // inferior_argv
645 NULL, // inferior_envp
646 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000647 false, // launch_process == false (we are attaching)
648 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
649 NULL, // Don't send any attach by process name option to debugserver
650 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000651 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000652 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000653
654 if (error.Fail())
655 {
656 const char *error_string = error.AsCString();
657 if (error_string == NULL)
658 error_string = "unable to launch " DEBUGSERVER_BASENAME;
659
660 SetExitStatus (-1, error_string);
661 }
662 else
663 {
664 error = ConnectToDebugserver (host_port);
665 if (error.Success())
666 {
667 char packet[64];
668 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
669 StringExtractorGDBRemote response;
670 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
671 packet,
672 packet_len,
673 response);
674 switch (stop_state)
675 {
676 case eStateStopped:
677 case eStateCrashed:
678 case eStateSuspended:
679 SetID (attach_pid);
680 m_last_stop_packet = response;
681 m_last_stop_packet.SetFilePos (0);
682 SetPrivateState (stop_state);
683 break;
684
685 case eStateExited:
686 m_last_stop_packet = response;
687 m_last_stop_packet.SetFilePos (0);
688 response.SetFilePos(1);
689 SetExitStatus(response.GetHexU8(), NULL);
690 break;
691
692 default:
693 SetExitStatus(-1, "unable to attach to process");
694 break;
695 }
696
697 }
698 }
699 }
700
701 lldb::pid_t pid = GetID();
702 if (pid == LLDB_INVALID_PROCESS_ID)
703 {
704 KillDebugserverProcess();
705 }
706 return error;
707}
708
709size_t
710ProcessGDBRemote::AttachInputReaderCallback
711(
712 void *baton,
713 InputReader *reader,
714 lldb::InputReaderAction notification,
715 const char *bytes,
716 size_t bytes_len
717)
718{
719 if (notification == eInputReaderGotToken)
720 {
721 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
722 if (gdb_process->m_waiting_for_attach)
723 gdb_process->m_waiting_for_attach = false;
724 reader->SetIsDone(true);
725 return 1;
726 }
727 return 0;
728}
729
730Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000731ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000732{
733 Error error;
734 // Clear out and clean up from any current state
735 Clear();
736 // HACK: require arch be set correctly at the target level until we can
737 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000738
Greg Claytone005f2c2010-11-06 01:53:30 +0000739 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000740 if (process_name && process_name[0])
741 {
Chris Lattner24943d22010-06-08 16:52:24 +0000742 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000743 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000744 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000745 error = StartDebugserverProcess (host_port, // debugserver_url
746 NULL, // inferior_argv
747 NULL, // inferior_envp
748 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000749 false, // launch_process == false (we are attaching)
750 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
751 NULL, // Don't send any attach by process name option to debugserver
752 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000753 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000754 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000755 if (error.Fail())
756 {
757 const char *error_string = error.AsCString();
758 if (error_string == NULL)
759 error_string = "unable to launch " DEBUGSERVER_BASENAME;
760
761 SetExitStatus (-1, error_string);
762 }
763 else
764 {
765 error = ConnectToDebugserver (host_port);
766 if (error.Success())
767 {
768 StreamString packet;
769
Chris Lattner24943d22010-06-08 16:52:24 +0000770 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000771 packet.PutCString("vAttachWait");
772 else
773 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000774 packet.PutChar(';');
775 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
776 StringExtractorGDBRemote response;
777 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
778 packet.GetData(),
779 packet.GetSize(),
780 response);
781 switch (stop_state)
782 {
783 case eStateStopped:
784 case eStateCrashed:
785 case eStateSuspended:
786 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
787 m_last_stop_packet = response;
788 m_last_stop_packet.SetFilePos (0);
789 SetPrivateState (stop_state);
790 break;
791
792 case eStateExited:
793 m_last_stop_packet = response;
794 m_last_stop_packet.SetFilePos (0);
795 response.SetFilePos(1);
796 SetExitStatus(response.GetHexU8(), NULL);
797 break;
798
799 default:
800 SetExitStatus(-1, "unable to attach to process");
801 break;
802 }
803 }
804 }
805 }
806
807 lldb::pid_t pid = GetID();
808 if (pid == LLDB_INVALID_PROCESS_ID)
809 {
810 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000811
812 if (error.Success())
813 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000814 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000815
Chris Lattner24943d22010-06-08 16:52:24 +0000816 return error;
817}
818
819//
820// if (wait_for_launch)
821// {
822// InputReaderSP reader_sp (new InputReader());
823// StreamString instructions;
824// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
825// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
826// this, // baton
827// eInputReaderGranularityByte,
828// NULL, // End token
829// false);
830//
831// StringExtractorGDBRemote response;
832// m_waiting_for_attach = true;
833// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
834// while (m_waiting_for_attach)
835// {
836// // Wait for one second for the stop reply packet
837// if (m_gdb_comm.WaitForPacket(response, 1))
838// {
839// // Got some sort of packet, see if it is the stop reply packet?
840// char ch = response.GetChar(0);
841// if (ch == 'T')
842// {
843// m_waiting_for_attach = false;
844// }
845// }
846// else
847// {
848// // Put a period character every second
849// fputc('.', reader_out_fh);
850// }
851// }
852// }
853// }
854// return GetID();
855//}
856
857void
858ProcessGDBRemote::DidAttach ()
859{
Chris Lattner24943d22010-06-08 16:52:24 +0000860 if (m_dynamic_loader_ap.get())
861 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000862 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000863}
864
865Error
866ProcessGDBRemote::WillResume ()
867{
868 m_continue_packet.Clear();
869 // Start the continue packet we will use to run the target. Each thread
870 // will append what it is supposed to be doing to this packet when the
871 // ThreadList::WillResume() is called. If a thread it supposed
872 // to stay stopped, then don't append anything to this string.
873 m_continue_packet.Printf("vCont");
874 return Error();
875}
876
877Error
878ProcessGDBRemote::DoResume ()
879{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000880 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000881 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000882
883 Listener listener ("gdb-remote.resume-packet-sent");
884 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
885 {
886 EventSP event_sp;
887 TimeValue timeout;
888 timeout = TimeValue::Now();
889 timeout.OffsetWithSeconds (5);
890 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
891
892 if (listener.WaitForEvent (&timeout, event_sp) == false)
893 error.SetErrorString("Resume timed out.");
894 }
895
Jim Ingham3ae449a2010-11-17 02:32:00 +0000896 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000897}
898
899size_t
900ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
901{
902 const uint8_t *trap_opcode = NULL;
903 uint32_t trap_opcode_size = 0;
904
905 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
906 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
907 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
908 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
909
Jim Ingham7508e732010-08-09 23:31:02 +0000910 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000911 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000912 {
Greg Claytoncf015052010-06-11 03:25:34 +0000913 case ArchSpec::eCPU_i386:
914 case ArchSpec::eCPU_x86_64:
915 trap_opcode = g_i386_breakpoint_opcode;
916 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
917 break;
918
919 case ArchSpec::eCPU_arm:
920 // TODO: fill this in for ARM. We need to dig up the symbol for
921 // the address in the breakpoint locaiton and figure out if it is
922 // an ARM or Thumb breakpoint.
923 trap_opcode = g_arm_breakpoint_opcode;
924 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
925 break;
926
927 case ArchSpec::eCPU_ppc:
928 case ArchSpec::eCPU_ppc64:
929 trap_opcode = g_ppc_breakpoint_opcode;
930 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
931 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000932
Greg Claytoncf015052010-06-11 03:25:34 +0000933 default:
934 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
935 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000936 }
937
938 if (trap_opcode && trap_opcode_size)
939 {
940 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
941 return trap_opcode_size;
942 }
943 return 0;
944}
945
946uint32_t
947ProcessGDBRemote::UpdateThreadListIfNeeded ()
948{
949 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000950 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000951 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000952 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
953
Greg Clayton5205f0b2010-09-03 17:10:42 +0000954 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000955 const uint32_t stop_id = GetStopID();
956 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
957 {
958 // Update the thread list's stop id immediately so we don't recurse into this function.
959 ThreadList curr_thread_list (this);
960 curr_thread_list.SetStopID(stop_id);
961
962 Error err;
963 StringExtractorGDBRemote response;
964 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
965 response.IsNormalPacket();
966 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
967 {
968 char ch = response.GetChar();
969 if (ch == 'l')
970 break;
971 if (ch == 'm')
972 {
973 do
974 {
975 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
976
977 if (tid != LLDB_INVALID_THREAD_ID)
978 {
979 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +0000980 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000981 thread_sp.reset (new ThreadGDBRemote (*this, tid));
982 curr_thread_list.AddThread(thread_sp);
983 }
984
985 ch = response.GetChar();
986 } while (ch == ',');
987 }
988 }
989
990 m_thread_list = curr_thread_list;
991
992 SetThreadStopInfo (m_last_stop_packet);
993 }
994 return GetThreadList().GetSize(false);
995}
996
997
998StateType
999ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1000{
1001 const char stop_type = stop_packet.GetChar();
1002 switch (stop_type)
1003 {
1004 case 'T':
1005 case 'S':
1006 {
1007 // Stop with signal and thread info
1008 const uint8_t signo = stop_packet.GetHexU8();
1009 std::string name;
1010 std::string value;
1011 std::string thread_name;
1012 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001013 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001014 uint32_t tid = LLDB_INVALID_THREAD_ID;
1015 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1016 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001017 ThreadSP thread_sp;
1018
Chris Lattner24943d22010-06-08 16:52:24 +00001019 while (stop_packet.GetNameColonValue(name, value))
1020 {
1021 if (name.compare("metype") == 0)
1022 {
1023 // exception type in big endian hex
1024 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1025 }
1026 else if (name.compare("mecount") == 0)
1027 {
1028 // exception count in big endian hex
1029 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1030 }
1031 else if (name.compare("medata") == 0)
1032 {
1033 // exception data in big endian hex
1034 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1035 }
1036 else if (name.compare("thread") == 0)
1037 {
1038 // thread in big endian hex
1039 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytona875b642011-01-09 21:07:35 +00001040 thread_sp = m_thread_list.FindThreadByID(tid, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001041 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001042 else if (name.compare("hexname") == 0)
1043 {
1044 StringExtractor name_extractor;
1045 // Swap "value" over into "name_extractor"
1046 name_extractor.GetStringRef().swap(value);
1047 // Now convert the HEX bytes into a string value
1048 name_extractor.GetHexByteString (value);
1049 thread_name.swap (value);
1050 }
Chris Lattner24943d22010-06-08 16:52:24 +00001051 else if (name.compare("name") == 0)
1052 {
1053 thread_name.swap (value);
1054 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001055 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001056 {
1057 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1058 }
Greg Claytona875b642011-01-09 21:07:35 +00001059 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1060 {
1061 // We have a register number that contains an expedited
1062 // register value. Lets supply this register to our thread
1063 // so it won't have to go and read it.
1064 if (thread_sp)
1065 {
1066 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1067
1068 if (reg != UINT32_MAX)
1069 {
1070 StringExtractor reg_value_extractor;
1071 // Swap "value" over into "reg_value_extractor"
1072 reg_value_extractor.GetStringRef().swap(value);
1073 static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor);
1074 }
1075 }
1076 }
Chris Lattner24943d22010-06-08 16:52:24 +00001077 }
Chris Lattner24943d22010-06-08 16:52:24 +00001078
1079 if (thread_sp)
1080 {
1081 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1082
1083 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1084 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001085 if (exc_type != 0)
1086 {
Greg Clayton643ee732010-08-04 01:40:35 +00001087 const size_t exc_data_count = exc_data.size();
1088
1089 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1090 exc_type,
1091 exc_data_count,
1092 exc_data_count >= 1 ? exc_data[0] : 0,
1093 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001094 }
1095 else if (signo)
1096 {
Greg Clayton643ee732010-08-04 01:40:35 +00001097 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001098 }
1099 else
1100 {
Greg Clayton643ee732010-08-04 01:40:35 +00001101 StopInfoSP invalid_stop_info_sp;
1102 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001103 }
1104 }
1105 return eStateStopped;
1106 }
1107 break;
1108
1109 case 'W':
1110 // process exited
1111 return eStateExited;
1112
1113 default:
1114 break;
1115 }
1116 return eStateInvalid;
1117}
1118
1119void
1120ProcessGDBRemote::RefreshStateAfterStop ()
1121{
Jim Ingham7508e732010-08-09 23:31:02 +00001122 // FIXME - add a variable to tell that we're in the middle of attaching if we
1123 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001124 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001125// if (!GetTarget().GetArchitecture().IsValid())
1126// {
1127// Module *exe_module = GetTarget().GetExecutableModule().get();
1128// if (exe_module)
1129// m_arch_spec = exe_module->GetArchitecture();
1130// }
1131
Chris Lattner24943d22010-06-08 16:52:24 +00001132 // Let all threads recover from stopping and do any clean up based
1133 // on the previous thread state (if any).
1134 m_thread_list.RefreshStateAfterStop();
1135
1136 // Discover new threads:
1137 UpdateThreadListIfNeeded ();
1138}
1139
1140Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001141ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001142{
1143 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001144
Greg Claytona4881d02011-01-22 07:12:45 +00001145 bool timed_out = false;
1146 Mutex::Locker locker;
1147
1148 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
Greg Clayton20d338f2010-11-18 05:57:03 +00001149 {
Greg Claytona4881d02011-01-22 07:12:45 +00001150 if (timed_out)
1151 error.SetErrorString("timed out sending interrupt packet");
1152 else
1153 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton20d338f2010-11-18 05:57:03 +00001154 }
1155
Chris Lattner24943d22010-06-08 16:52:24 +00001156 return error;
1157}
1158
1159Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001160ProcessGDBRemote::InterruptIfRunning
1161(
1162 bool discard_thread_plans,
1163 bool catch_stop_event,
1164 bool resume_private_state_thread,
1165 EventSP &stop_event_sp
1166)
Chris Lattner24943d22010-06-08 16:52:24 +00001167{
1168 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001169
Greg Clayton4fb400f2010-09-27 21:07:38 +00001170 if (m_gdb_comm.IsRunning())
1171 {
1172 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001173 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001174 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001175
1176 if (catch_stop_event)
1177 PausePrivateStateThread();
1178
1179 if (discard_thread_plans)
1180 m_thread_list.DiscardThreadPlans();
1181
1182 //m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1183 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001184 {
1185 if (timed_out)
1186 error.SetErrorString("timed out sending interrupt packet");
1187 else
1188 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton72e1c782011-01-22 23:43:18 +00001189 if (catch_stop_event)
1190 ResumePrivateStateThread();
1191 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001192 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001193
1194
1195 if (catch_stop_event)
1196 {
1197 TimeValue timeout_time;
1198 timeout_time = TimeValue::Now();
1199 timeout_time.OffsetWithSeconds(1);
1200 StateType state = WaitForProcessStopPrivate (&timeout_time, stop_event_sp);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001201
Greg Clayton72e1c782011-01-22 23:43:18 +00001202 if (state == eStateInvalid)
1203 error.SetErrorString("unable to verify target stopped");
1204 }
1205
1206 if (catch_stop_event && resume_private_state_thread)
1207 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001208 }
Chris Lattner24943d22010-06-08 16:52:24 +00001209 return error;
1210}
1211
Greg Clayton4fb400f2010-09-27 21:07:38 +00001212Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001213ProcessGDBRemote::WillDetach ()
1214{
1215 bool discard_thread_plans = true;
1216 bool catch_stop_event = true;
1217 bool resume_private_state_thread = false; // DoDetach will resume the thread
1218 EventSP event_sp;
1219 return InterruptIfRunning (discard_thread_plans, catch_stop_event, resume_private_state_thread, event_sp);
1220}
1221
1222Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001223ProcessGDBRemote::DoDetach()
1224{
1225 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001226 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001227 if (log)
1228 log->Printf ("ProcessGDBRemote::DoDetach()");
1229
1230 DisableAllBreakpointSites ();
1231
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001232 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001233
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001234 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1235 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001236 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001237 if (response_size)
1238 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1239 else
1240 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001241 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001242 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001243 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001244
Greg Clayton4fb400f2010-09-27 21:07:38 +00001245 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001246 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001247
1248 SetPrivateState (eStateDetached);
1249 ResumePrivateStateThread();
1250
1251 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001252 return error;
1253}
Chris Lattner24943d22010-06-08 16:52:24 +00001254
1255Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001256ProcessGDBRemote::WillDestroy ()
1257{
1258 bool discard_thread_plans = true;
1259 bool catch_stop_event = true;
1260 bool resume_private_state_thread = true;
1261 EventSP event_sp;
1262 return InterruptIfRunning (discard_thread_plans, catch_stop_event, resume_private_state_thread, event_sp);
1263}
1264
1265Error
Chris Lattner24943d22010-06-08 16:52:24 +00001266ProcessGDBRemote::DoDestroy ()
1267{
1268 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001269 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001270 if (log)
1271 log->Printf ("ProcessGDBRemote::DoDestroy()");
1272
1273 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001274 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001275 {
Greg Clayton72e1c782011-01-22 23:43:18 +00001276 m_continue_packet.Clear();
1277 m_continue_packet.Printf("k");
1278 Listener listener ("gdb-remote.kill-packet-sent");
1279 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1280 {
1281 EventSP event_sp;
1282 TimeValue timeout;
1283 timeout = TimeValue::Now();
1284 timeout.OffsetWithSeconds (1);
1285 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
Chris Lattner24943d22010-06-08 16:52:24 +00001286
Greg Clayton72e1c782011-01-22 23:43:18 +00001287 // Wait for the async thread to send the "k" packet
1288 if (listener.WaitForEvent (&timeout, event_sp))
1289 {
1290 if (log)
1291 log->Printf ("ProcessGDBRemote::DoDestroy() got confirmation the \"k\" packet was sent");
1292 }
1293 else
1294 {
1295 if (log)
1296 log->Printf ("ProcessGDBRemote::DoDestroy() timed out waiting for \"k\" packet to be sent");
1297 error.SetErrorString("Resume timed out.");
1298 }
1299
1300 // Wait for the async thread to exit which will indicate we stopped.
1301 // Hopefully the stop will be a process exited state since we are
1302 // asking the process to go away.
1303 if (!m_gdb_comm.WaitForNotRunning (&timeout))
1304 {
1305 if (log)
1306 log->Printf ("ProcessGDBRemote::DoDestroy() timed out waiting for \"k\" stop reply packet");
1307 }
1308 }
1309 }
Chris Lattner24943d22010-06-08 16:52:24 +00001310 StopAsyncThread ();
1311 m_gdb_comm.StopReadThread();
1312 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001313 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001314 return error;
1315}
1316
Chris Lattner24943d22010-06-08 16:52:24 +00001317//------------------------------------------------------------------
1318// Process Queries
1319//------------------------------------------------------------------
1320
1321bool
1322ProcessGDBRemote::IsAlive ()
1323{
Greg Clayton58e844b2010-12-08 05:08:21 +00001324 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001325}
1326
1327addr_t
1328ProcessGDBRemote::GetImageInfoAddress()
1329{
1330 if (!m_gdb_comm.IsRunning())
1331 {
1332 StringExtractorGDBRemote response;
1333 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1334 {
1335 if (response.IsNormalPacket())
1336 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1337 }
1338 }
1339 return LLDB_INVALID_ADDRESS;
1340}
1341
1342DynamicLoader *
1343ProcessGDBRemote::GetDynamicLoader()
1344{
1345 return m_dynamic_loader_ap.get();
1346}
1347
1348//------------------------------------------------------------------
1349// Process Memory
1350//------------------------------------------------------------------
1351size_t
1352ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1353{
1354 if (size > m_max_memory_size)
1355 {
1356 // Keep memory read sizes down to a sane limit. This function will be
1357 // called multiple times in order to complete the task by
1358 // lldb_private::Process so it is ok to do this.
1359 size = m_max_memory_size;
1360 }
1361
1362 char packet[64];
1363 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1364 assert (packet_len + 1 < sizeof(packet));
1365 StringExtractorGDBRemote response;
1366 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1367 {
1368 if (response.IsNormalPacket())
1369 {
1370 error.Clear();
1371 return response.GetHexBytes(buf, size, '\xdd');
1372 }
1373 else if (response.IsErrorPacket())
1374 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1375 else if (response.IsUnsupportedPacket())
1376 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1377 else
1378 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1379 }
1380 else
1381 {
1382 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1383 }
1384 return 0;
1385}
1386
1387size_t
1388ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1389{
1390 StreamString packet;
1391 packet.Printf("M%llx,%zx:", addr, size);
1392 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1393 StringExtractorGDBRemote response;
1394 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1395 {
1396 if (response.IsOKPacket())
1397 {
1398 error.Clear();
1399 return size;
1400 }
1401 else if (response.IsErrorPacket())
1402 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1403 else if (response.IsUnsupportedPacket())
1404 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1405 else
1406 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1407 }
1408 else
1409 {
1410 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1411 }
1412 return 0;
1413}
1414
1415lldb::addr_t
1416ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1417{
1418 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1419 if (allocated_addr == LLDB_INVALID_ADDRESS)
1420 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1421 else
1422 error.Clear();
1423 return allocated_addr;
1424}
1425
1426Error
1427ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1428{
1429 Error error;
1430 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1431 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1432 return error;
1433}
1434
1435
1436//------------------------------------------------------------------
1437// Process STDIO
1438//------------------------------------------------------------------
1439
1440size_t
1441ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1442{
1443 Mutex::Locker locker(m_stdio_mutex);
1444 size_t bytes_available = m_stdout_data.size();
1445 if (bytes_available > 0)
1446 {
1447 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1448 if (bytes_available > buf_size)
1449 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001450 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001451 m_stdout_data.erase(0, buf_size);
1452 bytes_available = buf_size;
1453 }
1454 else
1455 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001456 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001457 m_stdout_data.clear();
1458
1459 //ResetEventBits(eBroadcastBitSTDOUT);
1460 }
1461 }
1462 return bytes_available;
1463}
1464
1465size_t
1466ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1467{
1468 // Can we get STDERR through the remote protocol?
1469 return 0;
1470}
1471
1472size_t
1473ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1474{
1475 if (m_stdio_communication.IsConnected())
1476 {
1477 ConnectionStatus status;
1478 m_stdio_communication.Write(src, src_len, status, NULL);
1479 }
1480 return 0;
1481}
1482
1483Error
1484ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1485{
1486 Error error;
1487 assert (bp_site != NULL);
1488
Greg Claytone005f2c2010-11-06 01:53:30 +00001489 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001490 user_id_t site_id = bp_site->GetID();
1491 const addr_t addr = bp_site->GetLoadAddress();
1492 if (log)
1493 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1494
1495 if (bp_site->IsEnabled())
1496 {
1497 if (log)
1498 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1499 return error;
1500 }
1501 else
1502 {
1503 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1504
1505 if (bp_site->HardwarePreferred())
1506 {
1507 // Try and set hardware breakpoint, and if that fails, fall through
1508 // and set a software breakpoint?
1509 }
1510
1511 if (m_z0_supported)
1512 {
1513 char packet[64];
1514 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1515 assert (packet_len + 1 < sizeof(packet));
1516 StringExtractorGDBRemote response;
1517 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1518 {
1519 if (response.IsUnsupportedPacket())
1520 {
1521 // Disable z packet support and try again
1522 m_z0_supported = 0;
1523 return EnableBreakpoint (bp_site);
1524 }
1525 else if (response.IsOKPacket())
1526 {
1527 bp_site->SetEnabled(true);
1528 bp_site->SetType (BreakpointSite::eExternal);
1529 return error;
1530 }
1531 else
1532 {
1533 uint8_t error_byte = response.GetError();
1534 if (error_byte)
1535 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1536 }
1537 }
1538 }
1539 else
1540 {
1541 return EnableSoftwareBreakpoint (bp_site);
1542 }
1543 }
1544
1545 if (log)
1546 {
1547 const char *err_string = error.AsCString();
1548 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1549 bp_site->GetLoadAddress(),
1550 err_string ? err_string : "NULL");
1551 }
1552 // We shouldn't reach here on a successful breakpoint enable...
1553 if (error.Success())
1554 error.SetErrorToGenericError();
1555 return error;
1556}
1557
1558Error
1559ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1560{
1561 Error error;
1562 assert (bp_site != NULL);
1563 addr_t addr = bp_site->GetLoadAddress();
1564 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001565 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001566 if (log)
1567 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1568
1569 if (bp_site->IsEnabled())
1570 {
1571 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1572
1573 if (bp_site->IsHardware())
1574 {
1575 // TODO: disable hardware breakpoint...
1576 }
1577 else
1578 {
1579 if (m_z0_supported)
1580 {
1581 char packet[64];
1582 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1583 assert (packet_len + 1 < sizeof(packet));
1584 StringExtractorGDBRemote response;
1585 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1586 {
1587 if (response.IsUnsupportedPacket())
1588 {
1589 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1590 }
1591 else if (response.IsOKPacket())
1592 {
1593 if (log)
1594 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1595 bp_site->SetEnabled(false);
1596 return error;
1597 }
1598 else
1599 {
1600 uint8_t error_byte = response.GetError();
1601 if (error_byte)
1602 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1603 }
1604 }
1605 }
1606 else
1607 {
1608 return DisableSoftwareBreakpoint (bp_site);
1609 }
1610 }
1611 }
1612 else
1613 {
1614 if (log)
1615 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1616 return error;
1617 }
1618
1619 if (error.Success())
1620 error.SetErrorToGenericError();
1621 return error;
1622}
1623
1624Error
1625ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1626{
1627 Error error;
1628 if (wp)
1629 {
1630 user_id_t watchID = wp->GetID();
1631 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001632 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001633 if (log)
1634 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1635 if (wp->IsEnabled())
1636 {
1637 if (log)
1638 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1639 return error;
1640 }
1641 else
1642 {
1643 // Pass down an appropriate z/Z packet...
1644 error.SetErrorString("watchpoints not supported");
1645 }
1646 }
1647 else
1648 {
1649 error.SetErrorString("Watchpoint location argument was NULL.");
1650 }
1651 if (error.Success())
1652 error.SetErrorToGenericError();
1653 return error;
1654}
1655
1656Error
1657ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1658{
1659 Error error;
1660 if (wp)
1661 {
1662 user_id_t watchID = wp->GetID();
1663
Greg Claytone005f2c2010-11-06 01:53:30 +00001664 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001665
1666 addr_t addr = wp->GetLoadAddress();
1667 if (log)
1668 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1669
1670 if (wp->IsHardware())
1671 {
1672 // Pass down an appropriate z/Z packet...
1673 error.SetErrorString("watchpoints not supported");
1674 }
1675 // TODO: clear software watchpoints if we implement them
1676 }
1677 else
1678 {
1679 error.SetErrorString("Watchpoint location argument was NULL.");
1680 }
1681 if (error.Success())
1682 error.SetErrorToGenericError();
1683 return error;
1684}
1685
1686void
1687ProcessGDBRemote::Clear()
1688{
1689 m_flags = 0;
1690 m_thread_list.Clear();
1691 {
1692 Mutex::Locker locker(m_stdio_mutex);
1693 m_stdout_data.clear();
1694 }
Chris Lattner24943d22010-06-08 16:52:24 +00001695}
1696
1697Error
1698ProcessGDBRemote::DoSignal (int signo)
1699{
1700 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001701 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001702 if (log)
1703 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1704
1705 if (!m_gdb_comm.SendAsyncSignal (signo))
1706 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1707 return error;
1708}
1709
Caroline Tice861efb32010-11-16 05:07:41 +00001710//void
1711//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1712//{
1713// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1714// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1715//}
Chris Lattner24943d22010-06-08 16:52:24 +00001716
Caroline Tice861efb32010-11-16 05:07:41 +00001717//void
1718//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1719//{
1720// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1721// Mutex::Locker locker(m_stdio_mutex);
1722// m_stdout_data.append(s, len);
1723//
1724// // FIXME: Make a real data object for this and put it out.
1725// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1726//}
Chris Lattner24943d22010-06-08 16:52:24 +00001727
1728
1729Error
1730ProcessGDBRemote::StartDebugserverProcess
1731(
1732 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1733 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1734 char const *inferior_envp[], // Environment to pass along to the inferior program
1735 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001736 bool launch_process, // Set to true if we are going to be launching a the process
1737 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID send this pid as an argument to debugserver
Chris Lattner24943d22010-06-08 16:52:24 +00001738 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1739 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001740 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001741 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1742)
1743{
1744 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001745 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1746 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001747 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1748 {
1749 // If we locate debugserver, keep that located version around
1750 static FileSpec g_debugserver_file_spec;
1751
1752 FileSpec debugserver_file_spec;
1753 char debugserver_path[PATH_MAX];
1754
1755 // Always check to see if we have an environment override for the path
1756 // to the debugserver to use and use it if we do.
1757 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1758 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001759 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001760 else
1761 debugserver_file_spec = g_debugserver_file_spec;
1762 bool debugserver_exists = debugserver_file_spec.Exists();
1763 if (!debugserver_exists)
1764 {
1765 // The debugserver binary is in the LLDB.framework/Resources
1766 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001767 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001768 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001769 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001770 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001771 if (debugserver_exists)
1772 {
1773 g_debugserver_file_spec = debugserver_file_spec;
1774 }
1775 else
1776 {
1777 g_debugserver_file_spec.Clear();
1778 debugserver_file_spec.Clear();
1779 }
Chris Lattner24943d22010-06-08 16:52:24 +00001780 }
1781 }
1782
1783 if (debugserver_exists)
1784 {
1785 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1786
1787 m_stdio_communication.Clear();
1788 posix_spawnattr_t attr;
1789
Greg Claytone005f2c2010-11-06 01:53:30 +00001790 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001791
1792 Error local_err; // Errors that don't affect the spawning.
1793 if (log)
1794 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1795 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1796 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001797 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001798 if (error.Fail())
1799 return error;;
1800
1801#if !defined (__arm__)
1802
Greg Clayton24b48ff2010-10-17 22:03:32 +00001803 // We don't need to do this for ARM, and we really shouldn't now
1804 // that we have multiple CPU subtypes and no posix_spawnattr call
1805 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001806 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001807 {
Greg Claytoncf015052010-06-11 03:25:34 +00001808 cpu_type_t cpu = inferior_arch.GetCPUType();
1809 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1810 {
1811 size_t ocount = 0;
1812 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1813 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001814 error.PutToLog(log.get(), "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount);
Chris Lattner24943d22010-06-08 16:52:24 +00001815
Greg Claytoncf015052010-06-11 03:25:34 +00001816 if (error.Fail() != 0 || ocount != 1)
1817 return error;
1818 }
Chris Lattner24943d22010-06-08 16:52:24 +00001819 }
1820
1821#endif
1822
1823 Args debugserver_args;
1824 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001825
Chris Lattner24943d22010-06-08 16:52:24 +00001826 lldb_utility::PseudoTerminal pty;
Caroline Ticebd666012010-12-03 18:46:09 +00001827 if (launch_process && stdio_path == NULL && m_local_debugserver && !no_stdio)
Chris Lattner24943d22010-06-08 16:52:24 +00001828 {
Chris Lattner24943d22010-06-08 16:52:24 +00001829 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001830 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001831 }
1832
1833 // Start args with "debugserver /file/path -r --"
1834 debugserver_args.AppendArgument(debugserver_path);
1835 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001836 // use native registers, not the GDB registers
1837 debugserver_args.AppendArgument("--native-regs");
1838 // make debugserver run in its own session so signals generated by
1839 // special terminal key sequences (^C) don't affect debugserver
1840 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001841
Greg Clayton452bf612010-08-31 18:35:14 +00001842 if (disable_aslr)
1843 debugserver_args.AppendArguments("--disable-aslr");
1844
Chris Lattner24943d22010-06-08 16:52:24 +00001845 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001846 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001847 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001848 debugserver_args.AppendArgument("--stdio-path");
1849 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001850 }
Caroline Ticebd666012010-12-03 18:46:09 +00001851 else if (launch_process && no_stdio)
1852 {
1853 debugserver_args.AppendArgument("--no-stdio");
1854 }
Chris Lattner24943d22010-06-08 16:52:24 +00001855
1856 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1857 if (env_debugserver_log_file)
1858 {
1859 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1860 debugserver_args.AppendArgument(arg_cstr);
1861 }
1862
1863 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1864 if (env_debugserver_log_flags)
1865 {
1866 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1867 debugserver_args.AppendArgument(arg_cstr);
1868 }
1869// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1870// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1871
1872 // Now append the program arguments
1873 if (launch_process)
1874 {
1875 if (inferior_argv)
1876 {
1877 // Terminate the debugserver args so we can now append the inferior args
1878 debugserver_args.AppendArgument("--");
1879
1880 for (int i = 0; inferior_argv[i] != NULL; ++i)
1881 debugserver_args.AppendArgument (inferior_argv[i]);
1882 }
1883 else
1884 {
1885 // Will send environment entries with the 'QEnvironment:' packet
1886 // Will send arguments with the 'A' packet
1887 }
1888 }
1889 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1890 {
1891 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1892 debugserver_args.AppendArgument (arg_cstr);
1893 }
1894 else if (attach_name && attach_name[0])
1895 {
1896 if (wait_for_launch)
1897 debugserver_args.AppendArgument ("--waitfor");
1898 else
1899 debugserver_args.AppendArgument ("--attach");
1900 debugserver_args.AppendArgument (attach_name);
1901 }
1902
1903 Error file_actions_err;
1904 posix_spawn_file_actions_t file_actions;
1905#if DONT_CLOSE_DEBUGSERVER_STDIO
1906 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1907#else
1908 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1909 if (file_actions_err.Success())
1910 {
1911 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1912 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1913 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1914 }
1915#endif
1916
1917 if (log)
1918 {
1919 StreamString strm;
1920 debugserver_args.Dump (&strm);
1921 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1922 }
1923
Greg Clayton72e1c782011-01-22 23:43:18 +00001924 error.SetError (::posix_spawnp (&m_debugserver_pid,
1925 debugserver_path,
1926 file_actions_err.Success() ? &file_actions : NULL,
1927 &attr,
1928 debugserver_args.GetArgumentVector(),
1929 (char * const*)inferior_envp),
1930 eErrorTypePOSIX);
1931
Greg Claytone9d0df42010-07-02 01:29:13 +00001932
1933 ::posix_spawnattr_destroy (&attr);
1934
Chris Lattner24943d22010-06-08 16:52:24 +00001935 if (file_actions_err.Success())
1936 ::posix_spawn_file_actions_destroy (&file_actions);
1937
1938 // We have seen some cases where posix_spawnp was returning a valid
1939 // looking pid even when an error was returned, so clear it out
1940 if (error.Fail())
1941 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1942
1943 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001944 error.PutToLog(log.get(), "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", m_debugserver_pid, debugserver_path, NULL, &attr, inferior_argv, inferior_envp);
Chris Lattner24943d22010-06-08 16:52:24 +00001945
Caroline Ticebd666012010-12-03 18:46:09 +00001946 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00001947 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001948 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001949 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001950 }
Chris Lattner24943d22010-06-08 16:52:24 +00001951 }
1952 else
1953 {
1954 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1955 }
1956
1957 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1958 StartAsyncThread ();
1959 }
1960 return error;
1961}
1962
1963bool
1964ProcessGDBRemote::MonitorDebugserverProcess
1965(
1966 void *callback_baton,
1967 lldb::pid_t debugserver_pid,
1968 int signo, // Zero for no signal
1969 int exit_status // Exit value of process if signal is zero
1970)
1971{
1972 // We pass in the ProcessGDBRemote inferior process it and name it
1973 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1974 // pointer value itself, thus we need the double cast...
1975
1976 // "debugserver_pid" argument passed in is the process ID for
1977 // debugserver that we are tracking...
1978
Greg Clayton75ccf502010-08-21 02:22:51 +00001979 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00001980
1981 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1982 if (log)
1983 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
1984
Greg Clayton75ccf502010-08-21 02:22:51 +00001985 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001986 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001987 // Sleep for a half a second to make sure our inferior process has
1988 // time to set its exit status before we set it incorrectly when
1989 // both the debugserver and the inferior process shut down.
1990 usleep (500000);
1991 // If our process hasn't yet exited, debugserver might have died.
1992 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001993 const StateType state = process->GetState();
1994
1995 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1996 state != eStateInvalid &&
1997 state != eStateUnloaded &&
1998 state != eStateExited &&
1999 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002000 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002001 char error_str[1024];
2002 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002003 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002004 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2005 if (signal_cstr)
2006 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002007 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002008 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002009 }
2010 else
2011 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002012 ::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 +00002013 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002014
2015 process->SetExitStatus (-1, error_str);
2016 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002017 // Debugserver has exited we need to let our ProcessGDBRemote
2018 // know that it no longer has a debugserver instance
2019 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2020 // We are returning true to this function below, so we can
2021 // forget about the monitor handle.
2022 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002023 }
2024 return true;
2025}
2026
2027void
2028ProcessGDBRemote::KillDebugserverProcess ()
2029{
2030 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2031 {
2032 ::kill (m_debugserver_pid, SIGINT);
2033 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2034 }
2035}
2036
2037void
2038ProcessGDBRemote::Initialize()
2039{
2040 static bool g_initialized = false;
2041
2042 if (g_initialized == false)
2043 {
2044 g_initialized = true;
2045 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2046 GetPluginDescriptionStatic(),
2047 CreateInstance);
2048
2049 Log::Callbacks log_callbacks = {
2050 ProcessGDBRemoteLog::DisableLog,
2051 ProcessGDBRemoteLog::EnableLog,
2052 ProcessGDBRemoteLog::ListLogCategories
2053 };
2054
2055 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2056 }
2057}
2058
2059bool
2060ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2061{
2062 if (m_curr_tid == tid)
2063 return true;
2064
2065 char packet[32];
2066 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2067 assert (packet_len + 1 < sizeof(packet));
2068 StringExtractorGDBRemote response;
2069 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2070 {
2071 if (response.IsOKPacket())
2072 {
2073 m_curr_tid = tid;
2074 return true;
2075 }
2076 }
2077 return false;
2078}
2079
2080bool
2081ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2082{
2083 if (m_curr_tid_run == tid)
2084 return true;
2085
2086 char packet[32];
Greg Claytonc71899e2011-01-18 19:36:39 +00002087 const int packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002088 assert (packet_len + 1 < sizeof(packet));
2089 StringExtractorGDBRemote response;
2090 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2091 {
2092 if (response.IsOKPacket())
2093 {
2094 m_curr_tid_run = tid;
2095 return true;
2096 }
2097 }
2098 return false;
2099}
2100
2101void
2102ProcessGDBRemote::ResetGDBRemoteState ()
2103{
2104 // Reset and GDB remote state
2105 m_curr_tid = LLDB_INVALID_THREAD_ID;
2106 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2107 m_z0_supported = 1;
2108}
2109
2110
2111bool
2112ProcessGDBRemote::StartAsyncThread ()
2113{
2114 ResetGDBRemoteState ();
2115
Greg Claytone005f2c2010-11-06 01:53:30 +00002116 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002117
2118 if (log)
2119 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2120
2121 // Create a thread that watches our internal state and controls which
2122 // events make it to clients (into the DCProcess event queue).
2123 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2124 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2125}
2126
2127void
2128ProcessGDBRemote::StopAsyncThread ()
2129{
Greg Claytone005f2c2010-11-06 01:53:30 +00002130 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002131
2132 if (log)
2133 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2134
2135 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2136
2137 // Stop the stdio thread
2138 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2139 {
2140 Host::ThreadJoin (m_async_thread, NULL, NULL);
2141 }
2142}
2143
2144
2145void *
2146ProcessGDBRemote::AsyncThread (void *arg)
2147{
2148 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2149
Greg Claytone005f2c2010-11-06 01:53:30 +00002150 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002151 if (log)
2152 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2153
2154 Listener listener ("ProcessGDBRemote::AsyncThread");
2155 EventSP event_sp;
2156 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2157 eBroadcastBitAsyncThreadShouldExit;
2158
2159 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2160 {
2161 bool done = false;
2162 while (!done)
2163 {
Caroline Tice926060e2010-10-29 21:48:37 +00002164 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002165 if (log)
2166 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2167 if (listener.WaitForEvent (NULL, event_sp))
2168 {
2169 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002170 if (log)
2171 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2172
Chris Lattner24943d22010-06-08 16:52:24 +00002173 switch (event_type)
2174 {
2175 case eBroadcastBitAsyncContinue:
2176 {
2177 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2178
2179 if (continue_packet)
2180 {
2181 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2182 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002183 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002184 if (log)
2185 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2186
2187 process->SetPrivateState(eStateRunning);
2188 StringExtractorGDBRemote response;
2189 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2190
2191 switch (stop_state)
2192 {
2193 case eStateStopped:
2194 case eStateCrashed:
2195 case eStateSuspended:
2196 process->m_last_stop_packet = response;
2197 process->m_last_stop_packet.SetFilePos (0);
2198 process->SetPrivateState (stop_state);
2199 break;
2200
2201 case eStateExited:
2202 process->m_last_stop_packet = response;
2203 process->m_last_stop_packet.SetFilePos (0);
2204 response.SetFilePos(1);
2205 process->SetExitStatus(response.GetHexU8(), NULL);
2206 done = true;
2207 break;
2208
2209 case eStateInvalid:
2210 break;
2211
2212 default:
2213 process->SetPrivateState (stop_state);
2214 break;
2215 }
2216 }
2217 }
2218 break;
2219
2220 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002221 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002222 if (log)
2223 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2224 done = true;
2225 break;
2226
2227 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002228 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002229 if (log)
2230 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2231 done = true;
2232 break;
2233 }
2234 }
2235 else
2236 {
Caroline Tice926060e2010-10-29 21:48:37 +00002237 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002238 if (log)
2239 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2240 done = true;
2241 }
2242 }
2243 }
2244
Caroline Tice926060e2010-10-29 21:48:37 +00002245 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002246 if (log)
2247 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2248
2249 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2250 return NULL;
2251}
2252
Chris Lattner24943d22010-06-08 16:52:24 +00002253const char *
2254ProcessGDBRemote::GetDispatchQueueNameForThread
2255(
2256 addr_t thread_dispatch_qaddr,
2257 std::string &dispatch_queue_name
2258)
2259{
2260 dispatch_queue_name.clear();
2261 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2262 {
2263 // Cache the dispatch_queue_offsets_addr value so we don't always have
2264 // to look it up
2265 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2266 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002267 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2268 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002269 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002270 if (module_sp)
2271 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2272
2273 if (dispatch_queue_offsets_symbol == NULL)
2274 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002275 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002276 if (module_sp)
2277 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2278 }
Chris Lattner24943d22010-06-08 16:52:24 +00002279 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002280 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002281
2282 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2283 return NULL;
2284 }
2285
2286 uint8_t memory_buffer[8];
2287 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2288
2289 // Excerpt from src/queue_private.h
2290 struct dispatch_queue_offsets_s
2291 {
2292 uint16_t dqo_version;
2293 uint16_t dqo_label;
2294 uint16_t dqo_label_size;
2295 } dispatch_queue_offsets;
2296
2297
2298 Error error;
2299 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2300 {
2301 uint32_t data_offset = 0;
2302 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2303 {
2304 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2305 {
2306 data_offset = 0;
2307 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2308 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2309 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2310 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2311 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2312 dispatch_queue_name.erase (bytes_read);
2313 }
2314 }
2315 }
2316 }
2317 if (dispatch_queue_name.empty())
2318 return NULL;
2319 return dispatch_queue_name.c_str();
2320}
2321
Jim Ingham7508e732010-08-09 23:31:02 +00002322uint32_t
2323ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2324{
2325 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2326 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2327 if (m_local_debugserver)
2328 {
2329 return Host::ListProcessesMatchingName (name, matches, pids);
2330 }
2331 else
2332 {
2333 // FIXME: Implement talking to the remote debugserver.
2334 return 0;
2335 }
2336
2337}
Jim Ingham55e01d82011-01-22 01:33:44 +00002338
2339bool
2340ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2341 lldb_private::StoppointCallbackContext *context,
2342 lldb::user_id_t break_id,
2343 lldb::user_id_t break_loc_id)
2344{
2345 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2346 // run so I can stop it if that's what I want to do.
2347 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2348 if (log)
2349 log->Printf("Hit New Thread Notification breakpoint.");
2350 return false;
2351}
2352
2353
2354bool
2355ProcessGDBRemote::StartNoticingNewThreads()
2356{
2357 static const char *bp_names[] =
2358 {
2359 "start_wqthread",
2360 "_pthread_start",
2361 NULL
2362 };
2363
2364 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2365 size_t num_bps = m_thread_observation_bps.size();
2366 if (num_bps != 0)
2367 {
2368 for (int i = 0; i < num_bps; i++)
2369 {
2370 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2371 if (break_sp)
2372 {
2373 if (log)
2374 log->Printf("Enabled noticing new thread breakpoint.");
2375 break_sp->SetEnabled(true);
2376 }
2377 }
2378 }
2379 else
2380 {
2381 for (int i = 0; bp_names[i] != NULL; i++)
2382 {
2383 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2384 if (breakpoint)
2385 {
2386 if (log)
2387 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2388 m_thread_observation_bps.push_back(breakpoint->GetID());
2389 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2390 }
2391 else
2392 {
2393 if (log)
2394 log->Printf("Failed to create new thread notification breakpoint.");
2395 return false;
2396 }
2397 }
2398 }
2399
2400 return true;
2401}
2402
2403bool
2404ProcessGDBRemote::StopNoticingNewThreads()
2405{
2406 size_t num_bps = m_thread_observation_bps.size();
2407 if (num_bps != 0)
2408 {
2409 for (int i = 0; i < num_bps; i++)
2410 {
2411 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2412
2413 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2414 if (break_sp)
2415 {
2416 if (log)
2417 log->Printf ("Disabling new thread notification breakpoint.");
2418 break_sp->SetEnabled(false);
2419 }
2420 }
2421 }
2422 return true;
2423}
2424
2425