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