blob: 7d22b9dca2640d8b7870dd8ede617a3b91349a9f [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>
12#include <mach/mach.h>
13#include <mach-o/dyld.h>
14#include <spawn.h>
15#include <sys/fcntl.h>
16#include <sys/types.h>
17#include <sys/ptrace.h>
18#include <sys/stat.h>
19#include <sys/sysctl.h>
20#include <unistd.h>
21
22// C++ Includes
23#include <algorithm>
24#include <map>
25
26// Other libraries and framework includes
27
28#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000029#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/ArchSpec.h"
31#include "lldb/Core/Debugger.h"
32#include "lldb/Core/ConnectionFileDescriptor.h"
33#include "lldb/Core/FileSpec.h"
34#include "lldb/Core/InputReader.h"
35#include "lldb/Core/Module.h"
36#include "lldb/Core/PluginManager.h"
37#include "lldb/Core/State.h"
38#include "lldb/Core/StreamString.h"
39#include "lldb/Core/Timer.h"
40#include "lldb/Host/TimeValue.h"
41#include "lldb/Symbol/ObjectFile.h"
42#include "lldb/Target/DynamicLoader.h"
43#include "lldb/Target/Target.h"
44#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000045#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046
47// Project includes
48#include "lldb/Host/Host.h"
49#include "StringExtractorGDBRemote.h"
50#include "GDBRemoteRegisterContext.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53#include "ThreadGDBRemote.h"
54#include "libunwind.h"
55#include "MacOSXLibunwindCallbacks.h"
56
57#if defined (__i386__) || defined (__x86_64__)
58#define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_I386_BPT
59#define MACH_EXC_DATA0_TRACE EXC_I386_SGL
60#elif defined (__powerpc__) || defined (__ppc__) || defined (__ppc64__)
61#define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_PPC_BREAKPOINT
62#elif defined (__arm__)
63#define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_ARM_BREAKPOINT
64#endif
65
66
67#define DEBUGSERVER_BASENAME "debugserver"
68using namespace lldb;
69using namespace lldb_private;
70
71static inline uint16_t
72get_random_port ()
73{
74 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u;
75}
76
77
78const char *
79ProcessGDBRemote::GetPluginNameStatic()
80{
81 return "process.gdb-remote";
82}
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();
110 return false;
111}
112
113//----------------------------------------------------------------------
114// ProcessGDBRemote constructor
115//----------------------------------------------------------------------
116ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
117 Process (target, listener),
118 m_dynamic_loader_ap (),
119 m_byte_order (eByteOrderHost),
120 m_flags (0),
121 m_stdio_communication ("gdb-remote.stdio"),
122 m_stdio_mutex (Mutex::eMutexTypeRecursive),
123 m_stdout_data (),
124 m_arch_spec (),
125 m_gdb_comm(),
126 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
127 m_debugserver_monitor (0),
128 m_register_info (),
129 m_curr_tid (LLDB_INVALID_THREAD_ID),
130 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
131 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
132 m_async_thread (LLDB_INVALID_HOST_THREAD),
133 m_z0_supported (1),
134 m_continue_packet(),
135 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
136 m_libunwind_target_type (UNW_TARGET_UNSPECIFIED),
137 m_libunwind_addr_space (NULL),
138 m_waiting_for_attach (false),
139 m_packet_timeout (1),
140 m_max_memory_size (512)
141{
142}
143
144//----------------------------------------------------------------------
145// Destructor
146//----------------------------------------------------------------------
147ProcessGDBRemote::~ProcessGDBRemote()
148{
149 // m_mach_process.UnregisterNotificationCallbacks (this);
150 Clear();
151}
152
153//----------------------------------------------------------------------
154// PluginInterface
155//----------------------------------------------------------------------
156const char *
157ProcessGDBRemote::GetPluginName()
158{
159 return "Process debugging plug-in that uses the GDB remote protocol";
160}
161
162const char *
163ProcessGDBRemote::GetShortPluginName()
164{
165 return GetPluginNameStatic();
166}
167
168uint32_t
169ProcessGDBRemote::GetPluginVersion()
170{
171 return 1;
172}
173
174void
175ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
176{
177 strm->Printf("TODO: fill this in\n");
178}
179
180Error
181ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
182{
183 Error error;
184 error.SetErrorString("No plug-in commands are currently supported.");
185 return error;
186}
187
188Log *
189ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
190{
191 return NULL;
192}
193
194void
195ProcessGDBRemote::BuildDynamicRegisterInfo ()
196{
197 char register_info_command[64];
198 m_register_info.Clear();
199 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
200 uint32_t reg_offset = 0;
201 uint32_t reg_num = 0;
202 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
203 {
204 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
205 StringExtractorGDBRemote response;
206 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
207 {
208 packet_type = response.GetType();
209 if (packet_type == StringExtractorGDBRemote::eResponse)
210 {
211 std::string name;
212 std::string value;
213 ConstString reg_name;
214 ConstString alt_name;
215 ConstString set_name;
216 RegisterInfo reg_info = { NULL, // Name
217 NULL, // Alt name
218 0, // byte size
219 reg_offset, // offset
220 eEncodingUint, // encoding
221 eFormatHex, // formate
222 reg_num, // native register number
223 {
224 LLDB_INVALID_REGNUM, // GCC reg num
225 LLDB_INVALID_REGNUM, // DWARF reg num
226 LLDB_INVALID_REGNUM, // generic reg num
227 reg_num // GDB reg num
228 }
229 };
230
231 while (response.GetNameColonValue(name, value))
232 {
233 if (name.compare("name") == 0)
234 {
235 reg_name.SetCString(value.c_str());
236 }
237 else if (name.compare("alt-name") == 0)
238 {
239 alt_name.SetCString(value.c_str());
240 }
241 else if (name.compare("bitsize") == 0)
242 {
243 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
244 }
245 else if (name.compare("offset") == 0)
246 {
247 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000248 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000249 {
250 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000251 }
252 }
253 else if (name.compare("encoding") == 0)
254 {
255 if (value.compare("uint") == 0)
256 reg_info.encoding = eEncodingUint;
257 else if (value.compare("sint") == 0)
258 reg_info.encoding = eEncodingSint;
259 else if (value.compare("ieee754") == 0)
260 reg_info.encoding = eEncodingIEEE754;
261 else if (value.compare("vector") == 0)
262 reg_info.encoding = eEncodingVector;
263 }
264 else if (name.compare("format") == 0)
265 {
266 if (value.compare("binary") == 0)
267 reg_info.format = eFormatBinary;
268 else if (value.compare("decimal") == 0)
269 reg_info.format = eFormatDecimal;
270 else if (value.compare("hex") == 0)
271 reg_info.format = eFormatHex;
272 else if (value.compare("float") == 0)
273 reg_info.format = eFormatFloat;
274 else if (value.compare("vector-sint8") == 0)
275 reg_info.format = eFormatVectorOfSInt8;
276 else if (value.compare("vector-uint8") == 0)
277 reg_info.format = eFormatVectorOfUInt8;
278 else if (value.compare("vector-sint16") == 0)
279 reg_info.format = eFormatVectorOfSInt16;
280 else if (value.compare("vector-uint16") == 0)
281 reg_info.format = eFormatVectorOfUInt16;
282 else if (value.compare("vector-sint32") == 0)
283 reg_info.format = eFormatVectorOfSInt32;
284 else if (value.compare("vector-uint32") == 0)
285 reg_info.format = eFormatVectorOfUInt32;
286 else if (value.compare("vector-float32") == 0)
287 reg_info.format = eFormatVectorOfFloat32;
288 else if (value.compare("vector-uint128") == 0)
289 reg_info.format = eFormatVectorOfUInt128;
290 }
291 else if (name.compare("set") == 0)
292 {
293 set_name.SetCString(value.c_str());
294 }
295 else if (name.compare("gcc") == 0)
296 {
297 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
298 }
299 else if (name.compare("dwarf") == 0)
300 {
301 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
302 }
303 else if (name.compare("generic") == 0)
304 {
305 if (value.compare("pc") == 0)
306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
307 else if (value.compare("sp") == 0)
308 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
309 else if (value.compare("fp") == 0)
310 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
311 else if (value.compare("ra") == 0)
312 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
313 else if (value.compare("flags") == 0)
314 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
315 }
316 }
317
Jason Molenda53d96862010-06-11 23:44:18 +0000318 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000319 assert (reg_info.byte_size != 0);
320 reg_offset += reg_info.byte_size;
321 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
322 }
323 }
324 else
325 {
326 packet_type = StringExtractorGDBRemote::eError;
327 }
328 }
329
330 if (reg_num == 0)
331 {
332 // We didn't get anything. See if we are debugging ARM and fill with
333 // a hard coded register set until we can get an updated debugserver
334 // down on the devices.
335 ArchSpec arm_arch ("arm");
336 if (GetTarget().GetArchitecture() == arm_arch)
337 m_register_info.HardcodeARMRegisters();
338 }
339 m_register_info.Finalize ();
340}
341
342Error
343ProcessGDBRemote::WillLaunch (Module* module)
344{
345 return WillLaunchOrAttach ();
346}
347
348Error
349ProcessGDBRemote::WillAttach (lldb::pid_t pid)
350{
351 return WillLaunchOrAttach ();
352}
353
354Error
355ProcessGDBRemote::WillAttach (const char *process_name, bool wait_for_launch)
356{
357 return WillLaunchOrAttach ();
358}
359
360Error
361ProcessGDBRemote::WillLaunchOrAttach ()
362{
363 Error error;
364 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
365 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
366
367 if (m_dynamic_loader_ap.get() == NULL)
368 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
369 m_stdio_communication.Clear ();
370
371 return error;
372}
373
374//----------------------------------------------------------------------
375// Process Control
376//----------------------------------------------------------------------
377Error
378ProcessGDBRemote::DoLaunch
379(
380 Module* module,
381 char const *argv[],
382 char const *envp[],
383 const char *stdin_path,
384 const char *stdout_path,
385 const char *stderr_path
386)
387{
388 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
389 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
390 // ::LogSetLogFile ("/dev/stdout");
391 Error error;
392
393 ObjectFile * object_file = module->GetObjectFile();
394 if (object_file)
395 {
396 ArchSpec inferior_arch(module->GetArchitecture());
397 char host_port[128];
398 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
399
400 bool start_debugserver_with_inferior_args = false;
401 if (start_debugserver_with_inferior_args)
402 {
403 // We want to launch debugserver with the inferior program and its
404 // arguments on the command line. We should only do this if we
405 // the GDB server we are talking to doesn't support the 'A' packet.
406 error = StartDebugserverProcess (host_port,
407 argv,
408 envp,
409 NULL, //stdin_path,
410 LLDB_INVALID_PROCESS_ID,
411 NULL, false,
412 inferior_arch);
413 if (error.Fail())
414 return error;
415
416 error = ConnectToDebugserver (host_port);
417 if (error.Success())
418 {
419 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
420 }
421 }
422 else
423 {
424 error = StartDebugserverProcess (host_port,
425 NULL,
426 NULL,
427 NULL, //stdin_path,
428 LLDB_INVALID_PROCESS_ID,
429 NULL, false,
430 inferior_arch);
431 if (error.Fail())
432 return error;
433
434 error = ConnectToDebugserver (host_port);
435 if (error.Success())
436 {
437 // Send the environment and the program + arguments after we connect
438 if (envp)
439 {
440 const char *env_entry;
441 for (int i=0; (env_entry = envp[i]); ++i)
442 {
443 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
444 break;
445 }
446 }
447
448 const uint32_t arg_timeout_seconds = 10;
449 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
450 if (arg_packet_err == 0)
451 {
452 std::string error_str;
453 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
454 {
455 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
456 }
457 else
458 {
459 error.SetErrorString (error_str.c_str());
460 }
461 }
462 else
463 {
464 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
465 }
466
467 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
468 }
469 }
470
471 if (GetID() == LLDB_INVALID_PROCESS_ID)
472 {
473 KillDebugserverProcess ();
474 return error;
475 }
476
477 StringExtractorGDBRemote response;
478 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
479 SetPrivateState (SetThreadStopInfo (response));
480
481 }
482 else
483 {
484 // Set our user ID to an invalid process ID.
485 SetID(LLDB_INVALID_PROCESS_ID);
486 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
487 }
488
489 // Return the process ID we have
490 return error;
491}
492
493
494Error
495ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
496{
497 Error error;
498 // Sleep and wait a bit for debugserver to start to listen...
499 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
500 if (conn_ap.get())
501 {
502 std::string connect_url("connect://");
503 connect_url.append (host_port);
504 const uint32_t max_retry_count = 50;
505 uint32_t retry_count = 0;
506 while (!m_gdb_comm.IsConnected())
507 {
508 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
509 {
510 m_gdb_comm.SetConnection (conn_ap.release());
511 break;
512 }
513 retry_count++;
514
515 if (retry_count >= max_retry_count)
516 break;
517
518 usleep (100000);
519 }
520 }
521
522 if (!m_gdb_comm.IsConnected())
523 {
524 if (error.Success())
525 error.SetErrorString("not connected to remote gdb server");
526 return error;
527 }
528
529 m_gdb_comm.SetAckMode (true);
530 if (m_gdb_comm.StartReadThread(&error))
531 {
532 // Send an initial ack
533 m_gdb_comm.SendAck('+');
534
535 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
536 m_debugserver_monitor = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
537 (void*)(intptr_t)GetID(), // Pass the inferior pid in the thread argument (which is a void *)
538 m_debugserver_pid,
539 false);
540
541 StringExtractorGDBRemote response;
542 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
543 {
544 if (response.IsOKPacket())
545 m_gdb_comm.SetAckMode (false);
546 }
547
548 BuildDynamicRegisterInfo ();
549 }
550 return error;
551}
552
553void
554ProcessGDBRemote::DidLaunchOrAttach ()
555{
556 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
557 if (GetID() == LLDB_INVALID_PROCESS_ID)
558 {
559 m_dynamic_loader_ap.reset();
560 }
561 else
562 {
563 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
564
565 Module * exe_module = GetTarget().GetExecutableModule ().get();
566 assert(exe_module);
567
568 m_arch_spec = exe_module->GetArchitecture();
569
570 ObjectFile *exe_objfile = exe_module->GetObjectFile();
571 assert(exe_objfile);
572
573 m_byte_order = exe_objfile->GetByteOrder();
574 assert (m_byte_order != eByteOrderInvalid);
575
576 StreamString strm;
577
578 ArchSpec inferior_arch;
579 // See if the GDB server supports the qHostInfo information
580 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
581 const char *os_type = m_gdb_comm.GetOSString().AsCString();
582
583 if (m_arch_spec.IsValid() && m_arch_spec == ArchSpec ("arm"))
584 {
585 // For ARM we can't trust the arch of the process as it could
586 // have an armv6 object file, but be running on armv7 kernel.
587 inferior_arch = m_gdb_comm.GetHostArchitecture();
588 }
589
590 if (!inferior_arch.IsValid())
591 inferior_arch = m_arch_spec;
592
593 if (vendor == NULL)
594 vendor = Host::GetVendorString().AsCString("apple");
595
596 if (os_type == NULL)
597 os_type = Host::GetOSString().AsCString("darwin");
598
599 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
600
601 std::transform (strm.GetString().begin(),
602 strm.GetString().end(),
603 strm.GetString().begin(),
604 ::tolower);
605
606 m_target_triple.SetCString(strm.GetString().c_str());
607 }
608}
609
610void
611ProcessGDBRemote::DidLaunch ()
612{
613 DidLaunchOrAttach ();
614 if (m_dynamic_loader_ap.get())
615 m_dynamic_loader_ap->DidLaunch();
616}
617
618Error
619ProcessGDBRemote::DoAttach (pid_t attach_pid)
620{
621 Error error;
622 // Clear out and clean up from any current state
623 Clear();
624 // HACK: require arch be set correctly at the target level until we can
625 // figure out a good way to determine the arch of what we are attaching to
626 m_arch_spec = m_target.GetArchitecture();
627
628 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
629 if (attach_pid != LLDB_INVALID_PROCESS_ID)
630 {
631 SetPrivateState (eStateAttaching);
632 char host_port[128];
633 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
634 error = StartDebugserverProcess (host_port,
635 NULL,
636 NULL,
637 NULL,
638 LLDB_INVALID_PROCESS_ID,
639 NULL, false,
640 m_arch_spec);
641
642 if (error.Fail())
643 {
644 const char *error_string = error.AsCString();
645 if (error_string == NULL)
646 error_string = "unable to launch " DEBUGSERVER_BASENAME;
647
648 SetExitStatus (-1, error_string);
649 }
650 else
651 {
652 error = ConnectToDebugserver (host_port);
653 if (error.Success())
654 {
655 char packet[64];
656 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
657 StringExtractorGDBRemote response;
658 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
659 packet,
660 packet_len,
661 response);
662 switch (stop_state)
663 {
664 case eStateStopped:
665 case eStateCrashed:
666 case eStateSuspended:
667 SetID (attach_pid);
668 m_last_stop_packet = response;
669 m_last_stop_packet.SetFilePos (0);
670 SetPrivateState (stop_state);
671 break;
672
673 case eStateExited:
674 m_last_stop_packet = response;
675 m_last_stop_packet.SetFilePos (0);
676 response.SetFilePos(1);
677 SetExitStatus(response.GetHexU8(), NULL);
678 break;
679
680 default:
681 SetExitStatus(-1, "unable to attach to process");
682 break;
683 }
684
685 }
686 }
687 }
688
689 lldb::pid_t pid = GetID();
690 if (pid == LLDB_INVALID_PROCESS_ID)
691 {
692 KillDebugserverProcess();
693 }
694 return error;
695}
696
697size_t
698ProcessGDBRemote::AttachInputReaderCallback
699(
700 void *baton,
701 InputReader *reader,
702 lldb::InputReaderAction notification,
703 const char *bytes,
704 size_t bytes_len
705)
706{
707 if (notification == eInputReaderGotToken)
708 {
709 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
710 if (gdb_process->m_waiting_for_attach)
711 gdb_process->m_waiting_for_attach = false;
712 reader->SetIsDone(true);
713 return 1;
714 }
715 return 0;
716}
717
718Error
719ProcessGDBRemote::DoAttach (const char *process_name, bool wait_for_launch)
720{
721 Error error;
722 // Clear out and clean up from any current state
723 Clear();
724 // HACK: require arch be set correctly at the target level until we can
725 // figure out a good way to determine the arch of what we are attaching to
726 m_arch_spec = m_target.GetArchitecture();
727
728 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
729 if (process_name && process_name[0])
730 {
731
732 SetPrivateState (eStateAttaching);
733 char host_port[128];
734 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
735 error = StartDebugserverProcess (host_port,
736 NULL,
737 NULL,
738 NULL,
739 LLDB_INVALID_PROCESS_ID,
740 NULL, false,
741 m_arch_spec);
742 if (error.Fail())
743 {
744 const char *error_string = error.AsCString();
745 if (error_string == NULL)
746 error_string = "unable to launch " DEBUGSERVER_BASENAME;
747
748 SetExitStatus (-1, error_string);
749 }
750 else
751 {
752 error = ConnectToDebugserver (host_port);
753 if (error.Success())
754 {
755 StreamString packet;
756
757 packet.PutCString("vAttach");
758 if (wait_for_launch)
759 packet.PutCString("Wait");
760 packet.PutChar(';');
761 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
762 StringExtractorGDBRemote response;
763 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
764 packet.GetData(),
765 packet.GetSize(),
766 response);
767 switch (stop_state)
768 {
769 case eStateStopped:
770 case eStateCrashed:
771 case eStateSuspended:
772 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
773 m_last_stop_packet = response;
774 m_last_stop_packet.SetFilePos (0);
775 SetPrivateState (stop_state);
776 break;
777
778 case eStateExited:
779 m_last_stop_packet = response;
780 m_last_stop_packet.SetFilePos (0);
781 response.SetFilePos(1);
782 SetExitStatus(response.GetHexU8(), NULL);
783 break;
784
785 default:
786 SetExitStatus(-1, "unable to attach to process");
787 break;
788 }
789 }
790 }
791 }
792
793 lldb::pid_t pid = GetID();
794 if (pid == LLDB_INVALID_PROCESS_ID)
795 {
796 KillDebugserverProcess();
797 }
798 return error;
799}
800
801//
802// if (wait_for_launch)
803// {
804// InputReaderSP reader_sp (new InputReader());
805// StreamString instructions;
806// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
807// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
808// this, // baton
809// eInputReaderGranularityByte,
810// NULL, // End token
811// false);
812//
813// StringExtractorGDBRemote response;
814// m_waiting_for_attach = true;
815// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
816// while (m_waiting_for_attach)
817// {
818// // Wait for one second for the stop reply packet
819// if (m_gdb_comm.WaitForPacket(response, 1))
820// {
821// // Got some sort of packet, see if it is the stop reply packet?
822// char ch = response.GetChar(0);
823// if (ch == 'T')
824// {
825// m_waiting_for_attach = false;
826// }
827// }
828// else
829// {
830// // Put a period character every second
831// fputc('.', reader_out_fh);
832// }
833// }
834// }
835// }
836// return GetID();
837//}
838
839void
840ProcessGDBRemote::DidAttach ()
841{
842 DidLaunchOrAttach ();
843 if (m_dynamic_loader_ap.get())
844 m_dynamic_loader_ap->DidAttach();
845}
846
847Error
848ProcessGDBRemote::WillResume ()
849{
850 m_continue_packet.Clear();
851 // Start the continue packet we will use to run the target. Each thread
852 // will append what it is supposed to be doing to this packet when the
853 // ThreadList::WillResume() is called. If a thread it supposed
854 // to stay stopped, then don't append anything to this string.
855 m_continue_packet.Printf("vCont");
856 return Error();
857}
858
859Error
860ProcessGDBRemote::DoResume ()
861{
862 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
863 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
864 return Error();
865}
866
867size_t
868ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
869{
870 const uint8_t *trap_opcode = NULL;
871 uint32_t trap_opcode_size = 0;
872
873 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
874 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
875 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
876 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
877
Greg Claytoncf015052010-06-11 03:25:34 +0000878 ArchSpec::CPU arch_cpu = m_arch_spec.GetGenericCPUType();
879 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000880 {
Greg Claytoncf015052010-06-11 03:25:34 +0000881 case ArchSpec::eCPU_i386:
882 case ArchSpec::eCPU_x86_64:
883 trap_opcode = g_i386_breakpoint_opcode;
884 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
885 break;
886
887 case ArchSpec::eCPU_arm:
888 // TODO: fill this in for ARM. We need to dig up the symbol for
889 // the address in the breakpoint locaiton and figure out if it is
890 // an ARM or Thumb breakpoint.
891 trap_opcode = g_arm_breakpoint_opcode;
892 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
893 break;
894
895 case ArchSpec::eCPU_ppc:
896 case ArchSpec::eCPU_ppc64:
897 trap_opcode = g_ppc_breakpoint_opcode;
898 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
899 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000900
Greg Claytoncf015052010-06-11 03:25:34 +0000901 default:
902 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
903 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000904 }
905
906 if (trap_opcode && trap_opcode_size)
907 {
908 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
909 return trap_opcode_size;
910 }
911 return 0;
912}
913
914uint32_t
915ProcessGDBRemote::UpdateThreadListIfNeeded ()
916{
917 // locker will keep a mutex locked until it goes out of scope
918 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD);
919 if (log && log->GetMask().IsSet(GDBR_LOG_VERBOSE))
920 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
921
922 const uint32_t stop_id = GetStopID();
923 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
924 {
925 // Update the thread list's stop id immediately so we don't recurse into this function.
926 ThreadList curr_thread_list (this);
927 curr_thread_list.SetStopID(stop_id);
928
929 Error err;
930 StringExtractorGDBRemote response;
931 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
932 response.IsNormalPacket();
933 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
934 {
935 char ch = response.GetChar();
936 if (ch == 'l')
937 break;
938 if (ch == 'm')
939 {
940 do
941 {
942 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
943
944 if (tid != LLDB_INVALID_THREAD_ID)
945 {
946 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
947 if (thread_sp)
948 thread_sp->GetRegisterContext()->Invalidate();
949 else
950 thread_sp.reset (new ThreadGDBRemote (*this, tid));
951 curr_thread_list.AddThread(thread_sp);
952 }
953
954 ch = response.GetChar();
955 } while (ch == ',');
956 }
957 }
958
959 m_thread_list = curr_thread_list;
960
961 SetThreadStopInfo (m_last_stop_packet);
962 }
963 return GetThreadList().GetSize(false);
964}
965
966
967StateType
968ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
969{
970 const char stop_type = stop_packet.GetChar();
971 switch (stop_type)
972 {
973 case 'T':
974 case 'S':
975 {
976 // Stop with signal and thread info
977 const uint8_t signo = stop_packet.GetHexU8();
978 std::string name;
979 std::string value;
980 std::string thread_name;
981 uint32_t exc_type = 0;
982 std::vector<uint64_t> exc_data;
983 uint32_t tid = LLDB_INVALID_THREAD_ID;
984 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
985 uint32_t exc_data_count = 0;
986 while (stop_packet.GetNameColonValue(name, value))
987 {
988 if (name.compare("metype") == 0)
989 {
990 // exception type in big endian hex
991 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
992 }
993 else if (name.compare("mecount") == 0)
994 {
995 // exception count in big endian hex
996 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
997 }
998 else if (name.compare("medata") == 0)
999 {
1000 // exception data in big endian hex
1001 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1002 }
1003 else if (name.compare("thread") == 0)
1004 {
1005 // thread in big endian hex
1006 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1007 }
1008 else if (name.compare("name") == 0)
1009 {
1010 thread_name.swap (value);
1011 }
1012 else if (name.compare("dispatchqaddr") == 0)
1013 {
1014 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1015 }
1016 }
1017 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1018
1019 if (thread_sp)
1020 {
1021 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1022
1023 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1024 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
1025 Thread::StopInfo& stop_info = gdb_thread->GetStopInfoRef();
1026 gdb_thread->SetStopInfoStopID (GetStopID());
1027 if (exc_type != 0)
1028 {
1029 if (exc_type == EXC_SOFTWARE && exc_data.size() == 2 && exc_data[0] == EXC_SOFT_SIGNAL)
1030 {
1031 stop_info.SetStopReasonWithSignal(exc_data[1]);
1032 }
1033#if defined (MACH_EXC_DATA0_SOFTWARE_BREAKPOINT)
1034 else if (exc_type == EXC_BREAKPOINT && exc_data[0] == MACH_EXC_DATA0_SOFTWARE_BREAKPOINT)
1035 {
1036 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Jim Ingham3c7b5b92010-06-16 02:00:15 +00001037 lldb::BreakpointSiteSP bp_site_sp = GetBreakpointSiteList().FindByAddress(pc);
1038 if (!bp_site_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001039 {
1040 //log->Printf("got EXC_BREAKPOINT at 0x%llx but didn't find a breakpoint site.\n", pc);
1041 stop_info.SetStopReasonWithException(exc_type, exc_data.size());
1042 for (uint32_t i=0; i<exc_data.size(); ++i)
1043 stop_info.SetExceptionDataAtIndex(i, exc_data[i]);
1044 }
1045 else
1046 {
Jim Ingham3c7b5b92010-06-16 02:00:15 +00001047 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1048 {
1049 stop_info.Clear ();
1050 stop_info.SetStopReasonWithBreakpointSiteID (bp_site_sp->GetID());
1051 }
1052 else
1053 {
1054 stop_info.Clear ();
1055 stop_info.SetStopReasonToNone();
1056 }
1057
Chris Lattner24943d22010-06-08 16:52:24 +00001058 }
1059 }
1060#endif
1061#if defined (MACH_EXC_DATA0_TRACE)
1062 else if (exc_type == EXC_BREAKPOINT && exc_data[0] == MACH_EXC_DATA0_TRACE)
1063 {
1064 stop_info.SetStopReasonToTrace ();
1065 }
1066#endif
1067 else
1068 {
1069 stop_info.SetStopReasonWithException(exc_type, exc_data.size());
1070 for (uint32_t i=0; i<exc_data.size(); ++i)
1071 stop_info.SetExceptionDataAtIndex(i, exc_data[i]);
1072 }
1073 }
1074 else if (signo)
1075 {
1076 stop_info.SetStopReasonWithSignal(signo);
1077 }
1078 else
1079 {
1080 stop_info.SetStopReasonToNone();
1081 }
1082 }
1083 return eStateStopped;
1084 }
1085 break;
1086
1087 case 'W':
1088 // process exited
1089 return eStateExited;
1090
1091 default:
1092 break;
1093 }
1094 return eStateInvalid;
1095}
1096
1097void
1098ProcessGDBRemote::RefreshStateAfterStop ()
1099{
1100 // We must be attaching if we don't already have a valid architecture
1101 if (!m_arch_spec.IsValid())
1102 {
1103 Module *exe_module = GetTarget().GetExecutableModule().get();
1104 if (exe_module)
1105 m_arch_spec = exe_module->GetArchitecture();
1106 }
1107 // Let all threads recover from stopping and do any clean up based
1108 // on the previous thread state (if any).
1109 m_thread_list.RefreshStateAfterStop();
1110
1111 // Discover new threads:
1112 UpdateThreadListIfNeeded ();
1113}
1114
1115Error
1116ProcessGDBRemote::DoHalt ()
1117{
1118 Error error;
1119 if (m_gdb_comm.IsRunning())
1120 {
1121 bool timed_out = false;
1122 if (!m_gdb_comm.SendInterrupt (2, &timed_out))
1123 {
1124 if (timed_out)
1125 error.SetErrorString("timed out sending interrupt packet");
1126 else
1127 error.SetErrorString("unknown error sending interrupt packet");
1128 }
1129 }
1130 return error;
1131}
1132
1133Error
1134ProcessGDBRemote::WillDetach ()
1135{
1136 Error error;
1137 const StateType state = m_private_state.GetValue();
1138
1139 if (IsRunning(state))
1140 error.SetErrorString("Process must be stopped in order to detach.");
1141
1142 return error;
1143}
1144
1145
1146Error
1147ProcessGDBRemote::DoDestroy ()
1148{
1149 Error error;
1150 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1151 if (log)
1152 log->Printf ("ProcessGDBRemote::DoDestroy()");
1153
1154 // Interrupt if our inferior is running...
1155 m_gdb_comm.SendInterrupt (1);
1156 DisableAllBreakpointSites ();
1157 SetExitStatus(-1, "process killed");
1158
1159 StringExtractorGDBRemote response;
1160 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1161 {
1162 if (log)
1163 {
1164 if (response.IsOKPacket())
1165 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1166 else
1167 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1168 }
1169 }
1170
1171 StopAsyncThread ();
1172 m_gdb_comm.StopReadThread();
1173 KillDebugserverProcess ();
1174 return error;
1175}
1176
1177ByteOrder
1178ProcessGDBRemote::GetByteOrder () const
1179{
1180 return m_byte_order;
1181}
1182
1183//------------------------------------------------------------------
1184// Process Queries
1185//------------------------------------------------------------------
1186
1187bool
1188ProcessGDBRemote::IsAlive ()
1189{
1190 return m_gdb_comm.IsConnected();
1191}
1192
1193addr_t
1194ProcessGDBRemote::GetImageInfoAddress()
1195{
1196 if (!m_gdb_comm.IsRunning())
1197 {
1198 StringExtractorGDBRemote response;
1199 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1200 {
1201 if (response.IsNormalPacket())
1202 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1203 }
1204 }
1205 return LLDB_INVALID_ADDRESS;
1206}
1207
1208DynamicLoader *
1209ProcessGDBRemote::GetDynamicLoader()
1210{
1211 return m_dynamic_loader_ap.get();
1212}
1213
1214//------------------------------------------------------------------
1215// Process Memory
1216//------------------------------------------------------------------
1217size_t
1218ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1219{
1220 if (size > m_max_memory_size)
1221 {
1222 // Keep memory read sizes down to a sane limit. This function will be
1223 // called multiple times in order to complete the task by
1224 // lldb_private::Process so it is ok to do this.
1225 size = m_max_memory_size;
1226 }
1227
1228 char packet[64];
1229 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1230 assert (packet_len + 1 < sizeof(packet));
1231 StringExtractorGDBRemote response;
1232 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1233 {
1234 if (response.IsNormalPacket())
1235 {
1236 error.Clear();
1237 return response.GetHexBytes(buf, size, '\xdd');
1238 }
1239 else if (response.IsErrorPacket())
1240 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1241 else if (response.IsUnsupportedPacket())
1242 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1243 else
1244 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1245 }
1246 else
1247 {
1248 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1249 }
1250 return 0;
1251}
1252
1253size_t
1254ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1255{
1256 StreamString packet;
1257 packet.Printf("M%llx,%zx:", addr, size);
1258 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1259 StringExtractorGDBRemote response;
1260 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1261 {
1262 if (response.IsOKPacket())
1263 {
1264 error.Clear();
1265 return size;
1266 }
1267 else if (response.IsErrorPacket())
1268 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1269 else if (response.IsUnsupportedPacket())
1270 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1271 else
1272 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1273 }
1274 else
1275 {
1276 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1277 }
1278 return 0;
1279}
1280
1281lldb::addr_t
1282ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1283{
1284 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1285 if (allocated_addr == LLDB_INVALID_ADDRESS)
1286 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1287 else
1288 error.Clear();
1289 return allocated_addr;
1290}
1291
1292Error
1293ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1294{
1295 Error error;
1296 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1297 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1298 return error;
1299}
1300
1301
1302//------------------------------------------------------------------
1303// Process STDIO
1304//------------------------------------------------------------------
1305
1306size_t
1307ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1308{
1309 Mutex::Locker locker(m_stdio_mutex);
1310 size_t bytes_available = m_stdout_data.size();
1311 if (bytes_available > 0)
1312 {
1313 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1314 if (bytes_available > buf_size)
1315 {
1316 memcpy(buf, m_stdout_data.data(), buf_size);
1317 m_stdout_data.erase(0, buf_size);
1318 bytes_available = buf_size;
1319 }
1320 else
1321 {
1322 memcpy(buf, m_stdout_data.data(), bytes_available);
1323 m_stdout_data.clear();
1324
1325 //ResetEventBits(eBroadcastBitSTDOUT);
1326 }
1327 }
1328 return bytes_available;
1329}
1330
1331size_t
1332ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1333{
1334 // Can we get STDERR through the remote protocol?
1335 return 0;
1336}
1337
1338size_t
1339ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1340{
1341 if (m_stdio_communication.IsConnected())
1342 {
1343 ConnectionStatus status;
1344 m_stdio_communication.Write(src, src_len, status, NULL);
1345 }
1346 return 0;
1347}
1348
1349Error
1350ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1351{
1352 Error error;
1353 assert (bp_site != NULL);
1354
1355 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1356 user_id_t site_id = bp_site->GetID();
1357 const addr_t addr = bp_site->GetLoadAddress();
1358 if (log)
1359 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1360
1361 if (bp_site->IsEnabled())
1362 {
1363 if (log)
1364 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1365 return error;
1366 }
1367 else
1368 {
1369 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1370
1371 if (bp_site->HardwarePreferred())
1372 {
1373 // Try and set hardware breakpoint, and if that fails, fall through
1374 // and set a software breakpoint?
1375 }
1376
1377 if (m_z0_supported)
1378 {
1379 char packet[64];
1380 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1381 assert (packet_len + 1 < sizeof(packet));
1382 StringExtractorGDBRemote response;
1383 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1384 {
1385 if (response.IsUnsupportedPacket())
1386 {
1387 // Disable z packet support and try again
1388 m_z0_supported = 0;
1389 return EnableBreakpoint (bp_site);
1390 }
1391 else if (response.IsOKPacket())
1392 {
1393 bp_site->SetEnabled(true);
1394 bp_site->SetType (BreakpointSite::eExternal);
1395 return error;
1396 }
1397 else
1398 {
1399 uint8_t error_byte = response.GetError();
1400 if (error_byte)
1401 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1402 }
1403 }
1404 }
1405 else
1406 {
1407 return EnableSoftwareBreakpoint (bp_site);
1408 }
1409 }
1410
1411 if (log)
1412 {
1413 const char *err_string = error.AsCString();
1414 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1415 bp_site->GetLoadAddress(),
1416 err_string ? err_string : "NULL");
1417 }
1418 // We shouldn't reach here on a successful breakpoint enable...
1419 if (error.Success())
1420 error.SetErrorToGenericError();
1421 return error;
1422}
1423
1424Error
1425ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1426{
1427 Error error;
1428 assert (bp_site != NULL);
1429 addr_t addr = bp_site->GetLoadAddress();
1430 user_id_t site_id = bp_site->GetID();
1431 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1432 if (log)
1433 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1434
1435 if (bp_site->IsEnabled())
1436 {
1437 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1438
1439 if (bp_site->IsHardware())
1440 {
1441 // TODO: disable hardware breakpoint...
1442 }
1443 else
1444 {
1445 if (m_z0_supported)
1446 {
1447 char packet[64];
1448 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1449 assert (packet_len + 1 < sizeof(packet));
1450 StringExtractorGDBRemote response;
1451 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1452 {
1453 if (response.IsUnsupportedPacket())
1454 {
1455 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1456 }
1457 else if (response.IsOKPacket())
1458 {
1459 if (log)
1460 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1461 bp_site->SetEnabled(false);
1462 return error;
1463 }
1464 else
1465 {
1466 uint8_t error_byte = response.GetError();
1467 if (error_byte)
1468 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1469 }
1470 }
1471 }
1472 else
1473 {
1474 return DisableSoftwareBreakpoint (bp_site);
1475 }
1476 }
1477 }
1478 else
1479 {
1480 if (log)
1481 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1482 return error;
1483 }
1484
1485 if (error.Success())
1486 error.SetErrorToGenericError();
1487 return error;
1488}
1489
1490Error
1491ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1492{
1493 Error error;
1494 if (wp)
1495 {
1496 user_id_t watchID = wp->GetID();
1497 addr_t addr = wp->GetLoadAddress();
1498 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1499 if (log)
1500 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1501 if (wp->IsEnabled())
1502 {
1503 if (log)
1504 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1505 return error;
1506 }
1507 else
1508 {
1509 // Pass down an appropriate z/Z packet...
1510 error.SetErrorString("watchpoints not supported");
1511 }
1512 }
1513 else
1514 {
1515 error.SetErrorString("Watchpoint location argument was NULL.");
1516 }
1517 if (error.Success())
1518 error.SetErrorToGenericError();
1519 return error;
1520}
1521
1522Error
1523ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1524{
1525 Error error;
1526 if (wp)
1527 {
1528 user_id_t watchID = wp->GetID();
1529
1530 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1531
1532 addr_t addr = wp->GetLoadAddress();
1533 if (log)
1534 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1535
1536 if (wp->IsHardware())
1537 {
1538 // Pass down an appropriate z/Z packet...
1539 error.SetErrorString("watchpoints not supported");
1540 }
1541 // TODO: clear software watchpoints if we implement them
1542 }
1543 else
1544 {
1545 error.SetErrorString("Watchpoint location argument was NULL.");
1546 }
1547 if (error.Success())
1548 error.SetErrorToGenericError();
1549 return error;
1550}
1551
1552void
1553ProcessGDBRemote::Clear()
1554{
1555 m_flags = 0;
1556 m_thread_list.Clear();
1557 {
1558 Mutex::Locker locker(m_stdio_mutex);
1559 m_stdout_data.clear();
1560 }
1561 DestoryLibUnwindAddressSpace();
1562}
1563
1564Error
1565ProcessGDBRemote::DoSignal (int signo)
1566{
1567 Error error;
1568 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1569 if (log)
1570 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1571
1572 if (!m_gdb_comm.SendAsyncSignal (signo))
1573 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1574 return error;
1575}
1576
1577
1578Error
1579ProcessGDBRemote::DoDetach()
1580{
1581 Error error;
1582 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1583 if (log)
1584 log->Printf ("ProcessGDBRemote::DoDetach()");
1585
1586 // if (DoSIGSTOP (true))
1587 // {
1588 // CloseChildFileDescriptors ();
1589 //
1590 // // Scope for "locker" so we can reply to all of our exceptions (the SIGSTOP
1591 // // exception).
1592 // {
1593 // Mutex::Locker locker(m_exception_messages_mutex);
1594 // ReplyToAllExceptions();
1595 // }
1596 //
1597 // // Shut down the exception thread and cleanup our exception remappings
1598 // Task().ShutDownExceptionThread();
1599 //
1600 // pid_t pid = GetID();
1601 //
1602 // // Detach from our process while we are stopped.
1603 // errno = 0;
1604 //
1605 // // Detach from our process
1606 // ::ptrace (PT_DETACH, pid, (caddr_t)1, 0);
1607 //
1608 // error.SetErrorToErrno();
1609 //
1610 // if (log || error.Fail())
1611 // error.PutToLog(log, "::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid);
1612 //
1613 // // Resume our task
1614 // Task().Resume();
1615 //
1616 // // NULL our task out as we have already retored all exception ports
1617 // Task().Clear();
1618 //
1619 // // Clear out any notion of the process we once were
1620 // Clear();
1621 //
1622 // SetPrivateState (eStateDetached);
1623 // return true;
1624 // }
1625 return error;
1626}
1627
1628void
1629ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1630{
1631 ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1632 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1633}
1634
1635void
1636ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1637{
1638 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1639 Mutex::Locker locker(m_stdio_mutex);
1640 m_stdout_data.append(s, len);
1641
1642 // FIXME: Make a real data object for this and put it out.
1643 BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1644}
1645
1646
1647Error
1648ProcessGDBRemote::StartDebugserverProcess
1649(
1650 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1651 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1652 char const *inferior_envp[], // Environment to pass along to the inferior program
1653 char const *stdio_path,
1654 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID then attach to this attach_pid
1655 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1656 bool wait_for_launch, // Wait for the process named "attach_name" to launch
1657 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1658)
1659{
1660 Error error;
1661 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1662 {
1663 // If we locate debugserver, keep that located version around
1664 static FileSpec g_debugserver_file_spec;
1665
1666 FileSpec debugserver_file_spec;
1667 char debugserver_path[PATH_MAX];
1668
1669 // Always check to see if we have an environment override for the path
1670 // to the debugserver to use and use it if we do.
1671 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1672 if (env_debugserver_path)
1673 debugserver_file_spec.SetFile (env_debugserver_path);
1674 else
1675 debugserver_file_spec = g_debugserver_file_spec;
1676 bool debugserver_exists = debugserver_file_spec.Exists();
1677 if (!debugserver_exists)
1678 {
1679 // The debugserver binary is in the LLDB.framework/Resources
1680 // directory.
1681 FileSpec framework_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)lldb_private::Initialize));
1682 const char *framework_dir = framework_file_spec.GetDirectory().AsCString();
1683 const char *lldb_framework = ::strstr (framework_dir, "/LLDB.framework");
1684
1685 if (lldb_framework)
1686 {
1687 int len = lldb_framework - framework_dir + strlen ("/LLDB.framework");
1688 ::snprintf (debugserver_path,
1689 sizeof(debugserver_path),
1690 "%.*s/Resources/%s",
1691 len,
1692 framework_dir,
1693 DEBUGSERVER_BASENAME);
1694 debugserver_file_spec.SetFile (debugserver_path);
1695 debugserver_exists = debugserver_file_spec.Exists();
1696 }
1697
1698 if (debugserver_exists)
1699 {
1700 g_debugserver_file_spec = debugserver_file_spec;
1701 }
1702 else
1703 {
1704 g_debugserver_file_spec.Clear();
1705 debugserver_file_spec.Clear();
1706 }
1707 }
1708
1709 if (debugserver_exists)
1710 {
1711 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1712
1713 m_stdio_communication.Clear();
1714 posix_spawnattr_t attr;
1715
1716 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
1717
1718 Error local_err; // Errors that don't affect the spawning.
1719 if (log)
1720 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1721 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1722 if (error.Fail() || log)
1723 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
1724 if (error.Fail())
1725 return error;;
1726
1727#if !defined (__arm__)
1728
1729 // We don't need to do this for ARM, and we really shouldn't now that we
1730 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1731 // to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001732 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001733 {
Greg Claytoncf015052010-06-11 03:25:34 +00001734 cpu_type_t cpu = inferior_arch.GetCPUType();
1735 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1736 {
1737 size_t ocount = 0;
1738 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1739 if (error.Fail() || log)
1740 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount);
Chris Lattner24943d22010-06-08 16:52:24 +00001741
Greg Claytoncf015052010-06-11 03:25:34 +00001742 if (error.Fail() != 0 || ocount != 1)
1743 return error;
1744 }
Chris Lattner24943d22010-06-08 16:52:24 +00001745 }
1746
1747#endif
1748
1749 Args debugserver_args;
1750 char arg_cstr[PATH_MAX];
1751 bool launch_process = true;
1752
1753 if (inferior_argv == NULL && attach_pid != LLDB_INVALID_PROCESS_ID)
1754 launch_process = false;
1755 else if (attach_name)
1756 launch_process = false; // Wait for a process whose basename matches that in inferior_argv[0]
1757
1758 bool pass_stdio_path_to_debugserver = true;
1759 lldb_utility::PseudoTerminal pty;
1760 if (stdio_path == NULL)
1761 {
1762 pass_stdio_path_to_debugserver = false;
1763 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
1764 {
1765 struct termios stdin_termios;
1766 if (::tcgetattr (pty.GetMasterFileDescriptor(), &stdin_termios) == 0)
1767 {
1768 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing
1769 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time
1770 ::tcsetattr (pty.GetMasterFileDescriptor(), TCSANOW, &stdin_termios);
1771 }
1772 stdio_path = pty.GetSlaveName (NULL, 0);
1773 }
1774 }
1775
1776 // Start args with "debugserver /file/path -r --"
1777 debugserver_args.AppendArgument(debugserver_path);
1778 debugserver_args.AppendArgument(debugserver_url);
1779 debugserver_args.AppendArgument("--native-regs"); // use native registers, not the GDB registers
1780 debugserver_args.AppendArgument("--setsid"); // make debugserver run in its own session so
1781 // signals generated by special terminal key
1782 // sequences (^C) don't affect debugserver
1783
1784 // Only set the inferior
1785 if (launch_process)
1786 {
1787 if (stdio_path && pass_stdio_path_to_debugserver)
1788 {
1789 debugserver_args.AppendArgument("-s"); // short for --stdio-path
1790 StreamString strm;
1791 strm.Printf("'%s'", stdio_path);
1792 debugserver_args.AppendArgument(strm.GetData()); // path to file to have inferior open as it's STDIO
1793 }
1794 }
1795
1796 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1797 if (env_debugserver_log_file)
1798 {
1799 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1800 debugserver_args.AppendArgument(arg_cstr);
1801 }
1802
1803 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1804 if (env_debugserver_log_flags)
1805 {
1806 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1807 debugserver_args.AppendArgument(arg_cstr);
1808 }
1809// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1810// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1811
1812 // Now append the program arguments
1813 if (launch_process)
1814 {
1815 if (inferior_argv)
1816 {
1817 // Terminate the debugserver args so we can now append the inferior args
1818 debugserver_args.AppendArgument("--");
1819
1820 for (int i = 0; inferior_argv[i] != NULL; ++i)
1821 debugserver_args.AppendArgument (inferior_argv[i]);
1822 }
1823 else
1824 {
1825 // Will send environment entries with the 'QEnvironment:' packet
1826 // Will send arguments with the 'A' packet
1827 }
1828 }
1829 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1830 {
1831 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1832 debugserver_args.AppendArgument (arg_cstr);
1833 }
1834 else if (attach_name && attach_name[0])
1835 {
1836 if (wait_for_launch)
1837 debugserver_args.AppendArgument ("--waitfor");
1838 else
1839 debugserver_args.AppendArgument ("--attach");
1840 debugserver_args.AppendArgument (attach_name);
1841 }
1842
1843 Error file_actions_err;
1844 posix_spawn_file_actions_t file_actions;
1845#if DONT_CLOSE_DEBUGSERVER_STDIO
1846 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1847#else
1848 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1849 if (file_actions_err.Success())
1850 {
1851 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1852 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1853 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1854 }
1855#endif
1856
1857 if (log)
1858 {
1859 StreamString strm;
1860 debugserver_args.Dump (&strm);
1861 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1862 }
1863
1864 error.SetError(::posix_spawnp (&m_debugserver_pid,
1865 debugserver_path,
1866 file_actions_err.Success() ? &file_actions : NULL,
1867 &attr,
1868 debugserver_args.GetArgumentVector(),
1869 (char * const*)inferior_envp),
1870 eErrorTypePOSIX);
1871
Greg Claytone9d0df42010-07-02 01:29:13 +00001872
1873 ::posix_spawnattr_destroy (&attr);
1874
Chris Lattner24943d22010-06-08 16:52:24 +00001875 if (file_actions_err.Success())
1876 ::posix_spawn_file_actions_destroy (&file_actions);
1877
1878 // We have seen some cases where posix_spawnp was returning a valid
1879 // looking pid even when an error was returned, so clear it out
1880 if (error.Fail())
1881 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1882
1883 if (error.Fail() || log)
1884 error.PutToLog(log, "::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);
1885
1886// if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1887// {
1888// std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true));
1889// if (conn_ap.get())
1890// {
1891// m_stdio_communication.SetConnection(conn_ap.release());
1892// if (m_stdio_communication.IsConnected())
1893// {
1894// m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1895// m_stdio_communication.StartReadThread();
1896// }
1897// }
1898// }
1899 }
1900 else
1901 {
1902 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1903 }
1904
1905 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1906 StartAsyncThread ();
1907 }
1908 return error;
1909}
1910
1911bool
1912ProcessGDBRemote::MonitorDebugserverProcess
1913(
1914 void *callback_baton,
1915 lldb::pid_t debugserver_pid,
1916 int signo, // Zero for no signal
1917 int exit_status // Exit value of process if signal is zero
1918)
1919{
1920 // We pass in the ProcessGDBRemote inferior process it and name it
1921 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1922 // pointer value itself, thus we need the double cast...
1923
1924 // "debugserver_pid" argument passed in is the process ID for
1925 // debugserver that we are tracking...
1926
1927 lldb::pid_t gdb_remote_pid = (lldb::pid_t)(intptr_t)callback_baton;
Greg Clayton63094e02010-06-23 01:19:29 +00001928 TargetSP target_sp(Debugger::FindTargetWithProcessID (gdb_remote_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001929 if (target_sp)
1930 {
1931 ProcessSP process_sp (target_sp->GetProcessSP());
1932 if (process_sp)
1933 {
1934 // Sleep for a half a second to make sure our inferior process has
1935 // time to set its exit status before we set it incorrectly when
1936 // both the debugserver and the inferior process shut down.
1937 usleep (500000);
1938 // If our process hasn't yet exited, debugserver might have died.
1939 // If the process did exit, the we are reaping it.
1940 if (process_sp->GetState() != eStateExited)
1941 {
1942 char error_str[1024];
1943 if (signo)
1944 {
1945 const char *signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1946 if (signal_cstr)
1947 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
1948 else
1949 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
1950 }
1951 else
1952 {
1953 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
1954 }
1955
1956 process_sp->SetExitStatus (-1, error_str);
1957 }
1958 else
1959 {
1960 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)process_sp.get();
1961 // Debugserver has exited we need to let our ProcessGDBRemote
1962 // know that it no longer has a debugserver instance
1963 gdb_process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1964 // We are returning true to this function below, so we can
1965 // forget about the monitor handle.
1966 gdb_process->m_debugserver_monitor = 0;
1967 }
1968 }
1969 }
1970 return true;
1971}
1972
1973void
1974ProcessGDBRemote::KillDebugserverProcess ()
1975{
1976 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1977 {
1978 ::kill (m_debugserver_pid, SIGINT);
1979 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1980 }
1981}
1982
1983void
1984ProcessGDBRemote::Initialize()
1985{
1986 static bool g_initialized = false;
1987
1988 if (g_initialized == false)
1989 {
1990 g_initialized = true;
1991 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1992 GetPluginDescriptionStatic(),
1993 CreateInstance);
1994
1995 Log::Callbacks log_callbacks = {
1996 ProcessGDBRemoteLog::DisableLog,
1997 ProcessGDBRemoteLog::EnableLog,
1998 ProcessGDBRemoteLog::ListLogCategories
1999 };
2000
2001 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2002 }
2003}
2004
2005bool
2006ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2007{
2008 if (m_curr_tid == tid)
2009 return true;
2010
2011 char packet[32];
2012 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2013 assert (packet_len + 1 < sizeof(packet));
2014 StringExtractorGDBRemote response;
2015 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2016 {
2017 if (response.IsOKPacket())
2018 {
2019 m_curr_tid = tid;
2020 return true;
2021 }
2022 }
2023 return false;
2024}
2025
2026bool
2027ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2028{
2029 if (m_curr_tid_run == tid)
2030 return true;
2031
2032 char packet[32];
2033 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2034 assert (packet_len + 1 < sizeof(packet));
2035 StringExtractorGDBRemote response;
2036 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2037 {
2038 if (response.IsOKPacket())
2039 {
2040 m_curr_tid_run = tid;
2041 return true;
2042 }
2043 }
2044 return false;
2045}
2046
2047void
2048ProcessGDBRemote::ResetGDBRemoteState ()
2049{
2050 // Reset and GDB remote state
2051 m_curr_tid = LLDB_INVALID_THREAD_ID;
2052 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2053 m_z0_supported = 1;
2054}
2055
2056
2057bool
2058ProcessGDBRemote::StartAsyncThread ()
2059{
2060 ResetGDBRemoteState ();
2061
2062 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2063
2064 if (log)
2065 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2066
2067 // Create a thread that watches our internal state and controls which
2068 // events make it to clients (into the DCProcess event queue).
2069 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2070 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2071}
2072
2073void
2074ProcessGDBRemote::StopAsyncThread ()
2075{
2076 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2077
2078 if (log)
2079 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2080
2081 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2082
2083 // Stop the stdio thread
2084 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2085 {
2086 Host::ThreadJoin (m_async_thread, NULL, NULL);
2087 }
2088}
2089
2090
2091void *
2092ProcessGDBRemote::AsyncThread (void *arg)
2093{
2094 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2095
2096 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
2097 if (log)
2098 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2099
2100 Listener listener ("ProcessGDBRemote::AsyncThread");
2101 EventSP event_sp;
2102 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2103 eBroadcastBitAsyncThreadShouldExit;
2104
2105 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2106 {
2107 bool done = false;
2108 while (!done)
2109 {
2110 if (log)
2111 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2112 if (listener.WaitForEvent (NULL, event_sp))
2113 {
2114 const uint32_t event_type = event_sp->GetType();
2115 switch (event_type)
2116 {
2117 case eBroadcastBitAsyncContinue:
2118 {
2119 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2120
2121 if (continue_packet)
2122 {
2123 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2124 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2125 if (log)
2126 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2127
2128 process->SetPrivateState(eStateRunning);
2129 StringExtractorGDBRemote response;
2130 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2131
2132 switch (stop_state)
2133 {
2134 case eStateStopped:
2135 case eStateCrashed:
2136 case eStateSuspended:
2137 process->m_last_stop_packet = response;
2138 process->m_last_stop_packet.SetFilePos (0);
2139 process->SetPrivateState (stop_state);
2140 break;
2141
2142 case eStateExited:
2143 process->m_last_stop_packet = response;
2144 process->m_last_stop_packet.SetFilePos (0);
2145 response.SetFilePos(1);
2146 process->SetExitStatus(response.GetHexU8(), NULL);
2147 done = true;
2148 break;
2149
2150 case eStateInvalid:
2151 break;
2152
2153 default:
2154 process->SetPrivateState (stop_state);
2155 break;
2156 }
2157 }
2158 }
2159 break;
2160
2161 case eBroadcastBitAsyncThreadShouldExit:
2162 if (log)
2163 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2164 done = true;
2165 break;
2166
2167 default:
2168 if (log)
2169 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2170 done = true;
2171 break;
2172 }
2173 }
2174 else
2175 {
2176 if (log)
2177 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2178 done = true;
2179 }
2180 }
2181 }
2182
2183 if (log)
2184 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2185
2186 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2187 return NULL;
2188}
2189
2190lldb_private::unw_addr_space_t
2191ProcessGDBRemote::GetLibUnwindAddressSpace ()
2192{
2193 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002194
2195 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2196 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002197 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002198 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002199 target_type = UNW_TARGET_X86_64;
2200
2201 if (m_libunwind_addr_space)
2202 {
2203 if (m_libunwind_target_type != target_type)
2204 DestoryLibUnwindAddressSpace();
2205 else
2206 return m_libunwind_addr_space;
2207 }
2208 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2209 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2210 if (m_libunwind_addr_space)
2211 m_libunwind_target_type = target_type;
2212 else
2213 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2214 return m_libunwind_addr_space;
2215}
2216
2217void
2218ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2219{
2220 if (m_libunwind_addr_space)
2221 {
2222 unw_destroy_addr_space (m_libunwind_addr_space);
2223 m_libunwind_addr_space = NULL;
2224 }
2225 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2226}
2227
2228
2229const char *
2230ProcessGDBRemote::GetDispatchQueueNameForThread
2231(
2232 addr_t thread_dispatch_qaddr,
2233 std::string &dispatch_queue_name
2234)
2235{
2236 dispatch_queue_name.clear();
2237 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2238 {
2239 // Cache the dispatch_queue_offsets_addr value so we don't always have
2240 // to look it up
2241 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2242 {
2243 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib")));
2244 if (module_sp.get() == NULL)
2245 return NULL;
2246
2247 const Symbol *dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (ConstString("dispatch_queue_offsets"), eSymbolTypeData);
2248 if (dispatch_queue_offsets_symbol)
2249 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(this);
2250
2251 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2252 return NULL;
2253 }
2254
2255 uint8_t memory_buffer[8];
2256 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2257
2258 // Excerpt from src/queue_private.h
2259 struct dispatch_queue_offsets_s
2260 {
2261 uint16_t dqo_version;
2262 uint16_t dqo_label;
2263 uint16_t dqo_label_size;
2264 } dispatch_queue_offsets;
2265
2266
2267 Error error;
2268 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2269 {
2270 uint32_t data_offset = 0;
2271 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2272 {
2273 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2274 {
2275 data_offset = 0;
2276 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2277 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2278 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2279 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2280 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2281 dispatch_queue_name.erase (bytes_read);
2282 }
2283 }
2284 }
2285 }
2286 if (dispatch_queue_name.empty())
2287 return NULL;
2288 return dispatch_queue_name.c_str();
2289}
2290