blob: 6a3b5487164bbd88aa4dfdda388b4f7942975696 [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
433 const uint32_t arg_timeout_seconds = 10;
434 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
435 if (arg_packet_err == 0)
436 {
437 std::string error_str;
438 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
439 {
440 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
441 }
442 else
443 {
444 error.SetErrorString (error_str.c_str());
445 }
446 }
447 else
448 {
449 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
450 }
451
452 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
453 }
454 }
455
456 if (GetID() == LLDB_INVALID_PROCESS_ID)
457 {
458 KillDebugserverProcess ();
459 return error;
460 }
461
462 StringExtractorGDBRemote response;
463 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
464 SetPrivateState (SetThreadStopInfo (response));
465
466 }
467 else
468 {
469 // Set our user ID to an invalid process ID.
470 SetID(LLDB_INVALID_PROCESS_ID);
471 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
472 }
473
474 // Return the process ID we have
475 return error;
476}
477
478
479Error
480ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
481{
482 Error error;
483 // Sleep and wait a bit for debugserver to start to listen...
484 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
485 if (conn_ap.get())
486 {
487 std::string connect_url("connect://");
488 connect_url.append (host_port);
489 const uint32_t max_retry_count = 50;
490 uint32_t retry_count = 0;
491 while (!m_gdb_comm.IsConnected())
492 {
493 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
494 {
495 m_gdb_comm.SetConnection (conn_ap.release());
496 break;
497 }
498 retry_count++;
499
500 if (retry_count >= max_retry_count)
501 break;
502
503 usleep (100000);
504 }
505 }
506
507 if (!m_gdb_comm.IsConnected())
508 {
509 if (error.Success())
510 error.SetErrorString("not connected to remote gdb server");
511 return error;
512 }
513
514 m_gdb_comm.SetAckMode (true);
515 if (m_gdb_comm.StartReadThread(&error))
516 {
517 // Send an initial ack
518 m_gdb_comm.SendAck('+');
519
520 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
521 m_debugserver_monitor = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
522 (void*)(intptr_t)GetID(), // Pass the inferior pid in the thread argument (which is a void *)
523 m_debugserver_pid,
524 false);
525
526 StringExtractorGDBRemote response;
527 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
528 {
529 if (response.IsOKPacket())
530 m_gdb_comm.SetAckMode (false);
531 }
532
533 BuildDynamicRegisterInfo ();
534 }
535 return error;
536}
537
538void
539ProcessGDBRemote::DidLaunchOrAttach ()
540{
541 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
542 if (GetID() == LLDB_INVALID_PROCESS_ID)
543 {
544 m_dynamic_loader_ap.reset();
545 }
546 else
547 {
548 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
549
550 Module * exe_module = GetTarget().GetExecutableModule ().get();
551 assert(exe_module);
552
553 m_arch_spec = exe_module->GetArchitecture();
554
555 ObjectFile *exe_objfile = exe_module->GetObjectFile();
556 assert(exe_objfile);
557
558 m_byte_order = exe_objfile->GetByteOrder();
559 assert (m_byte_order != eByteOrderInvalid);
560
561 StreamString strm;
562
563 ArchSpec inferior_arch;
564 // See if the GDB server supports the qHostInfo information
565 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
566 const char *os_type = m_gdb_comm.GetOSString().AsCString();
567
568 if (m_arch_spec.IsValid() && m_arch_spec == ArchSpec ("arm"))
569 {
570 // For ARM we can't trust the arch of the process as it could
571 // have an armv6 object file, but be running on armv7 kernel.
572 inferior_arch = m_gdb_comm.GetHostArchitecture();
573 }
574
575 if (!inferior_arch.IsValid())
576 inferior_arch = m_arch_spec;
577
578 if (vendor == NULL)
579 vendor = Host::GetVendorString().AsCString("apple");
580
581 if (os_type == NULL)
582 os_type = Host::GetOSString().AsCString("darwin");
583
584 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
585
586 std::transform (strm.GetString().begin(),
587 strm.GetString().end(),
588 strm.GetString().begin(),
589 ::tolower);
590
591 m_target_triple.SetCString(strm.GetString().c_str());
592 }
593}
594
595void
596ProcessGDBRemote::DidLaunch ()
597{
598 DidLaunchOrAttach ();
599 if (m_dynamic_loader_ap.get())
600 m_dynamic_loader_ap->DidLaunch();
601}
602
603Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000604ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000605{
606 Error error;
607 // Clear out and clean up from any current state
608 Clear();
609 // HACK: require arch be set correctly at the target level until we can
610 // figure out a good way to determine the arch of what we are attaching to
611 m_arch_spec = m_target.GetArchitecture();
612
613 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
614 if (attach_pid != LLDB_INVALID_PROCESS_ID)
615 {
616 SetPrivateState (eStateAttaching);
617 char host_port[128];
618 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
619 error = StartDebugserverProcess (host_port,
620 NULL,
621 NULL,
622 NULL,
623 LLDB_INVALID_PROCESS_ID,
624 NULL, false,
625 m_arch_spec);
626
627 if (error.Fail())
628 {
629 const char *error_string = error.AsCString();
630 if (error_string == NULL)
631 error_string = "unable to launch " DEBUGSERVER_BASENAME;
632
633 SetExitStatus (-1, error_string);
634 }
635 else
636 {
637 error = ConnectToDebugserver (host_port);
638 if (error.Success())
639 {
640 char packet[64];
641 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
642 StringExtractorGDBRemote response;
643 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
644 packet,
645 packet_len,
646 response);
647 switch (stop_state)
648 {
649 case eStateStopped:
650 case eStateCrashed:
651 case eStateSuspended:
652 SetID (attach_pid);
653 m_last_stop_packet = response;
654 m_last_stop_packet.SetFilePos (0);
655 SetPrivateState (stop_state);
656 break;
657
658 case eStateExited:
659 m_last_stop_packet = response;
660 m_last_stop_packet.SetFilePos (0);
661 response.SetFilePos(1);
662 SetExitStatus(response.GetHexU8(), NULL);
663 break;
664
665 default:
666 SetExitStatus(-1, "unable to attach to process");
667 break;
668 }
669
670 }
671 }
672 }
673
674 lldb::pid_t pid = GetID();
675 if (pid == LLDB_INVALID_PROCESS_ID)
676 {
677 KillDebugserverProcess();
678 }
679 return error;
680}
681
682size_t
683ProcessGDBRemote::AttachInputReaderCallback
684(
685 void *baton,
686 InputReader *reader,
687 lldb::InputReaderAction notification,
688 const char *bytes,
689 size_t bytes_len
690)
691{
692 if (notification == eInputReaderGotToken)
693 {
694 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
695 if (gdb_process->m_waiting_for_attach)
696 gdb_process->m_waiting_for_attach = false;
697 reader->SetIsDone(true);
698 return 1;
699 }
700 return 0;
701}
702
703Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000704ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000705{
706 Error error;
707 // Clear out and clean up from any current state
708 Clear();
709 // HACK: require arch be set correctly at the target level until we can
710 // figure out a good way to determine the arch of what we are attaching to
711 m_arch_spec = m_target.GetArchitecture();
712
713 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
714 if (process_name && process_name[0])
715 {
716
717 SetPrivateState (eStateAttaching);
718 char host_port[128];
719 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
720 error = StartDebugserverProcess (host_port,
721 NULL,
722 NULL,
723 NULL,
724 LLDB_INVALID_PROCESS_ID,
725 NULL, false,
726 m_arch_spec);
727 if (error.Fail())
728 {
729 const char *error_string = error.AsCString();
730 if (error_string == NULL)
731 error_string = "unable to launch " DEBUGSERVER_BASENAME;
732
733 SetExitStatus (-1, error_string);
734 }
735 else
736 {
737 error = ConnectToDebugserver (host_port);
738 if (error.Success())
739 {
740 StreamString packet;
741
742 packet.PutCString("vAttach");
743 if (wait_for_launch)
744 packet.PutCString("Wait");
745 packet.PutChar(';');
746 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
747 StringExtractorGDBRemote response;
748 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
749 packet.GetData(),
750 packet.GetSize(),
751 response);
752 switch (stop_state)
753 {
754 case eStateStopped:
755 case eStateCrashed:
756 case eStateSuspended:
757 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
758 m_last_stop_packet = response;
759 m_last_stop_packet.SetFilePos (0);
760 SetPrivateState (stop_state);
761 break;
762
763 case eStateExited:
764 m_last_stop_packet = response;
765 m_last_stop_packet.SetFilePos (0);
766 response.SetFilePos(1);
767 SetExitStatus(response.GetHexU8(), NULL);
768 break;
769
770 default:
771 SetExitStatus(-1, "unable to attach to process");
772 break;
773 }
774 }
775 }
776 }
777
778 lldb::pid_t pid = GetID();
779 if (pid == LLDB_INVALID_PROCESS_ID)
780 {
781 KillDebugserverProcess();
782 }
783 return error;
784}
785
786//
787// if (wait_for_launch)
788// {
789// InputReaderSP reader_sp (new InputReader());
790// StreamString instructions;
791// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
792// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
793// this, // baton
794// eInputReaderGranularityByte,
795// NULL, // End token
796// false);
797//
798// StringExtractorGDBRemote response;
799// m_waiting_for_attach = true;
800// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
801// while (m_waiting_for_attach)
802// {
803// // Wait for one second for the stop reply packet
804// if (m_gdb_comm.WaitForPacket(response, 1))
805// {
806// // Got some sort of packet, see if it is the stop reply packet?
807// char ch = response.GetChar(0);
808// if (ch == 'T')
809// {
810// m_waiting_for_attach = false;
811// }
812// }
813// else
814// {
815// // Put a period character every second
816// fputc('.', reader_out_fh);
817// }
818// }
819// }
820// }
821// return GetID();
822//}
823
824void
825ProcessGDBRemote::DidAttach ()
826{
827 DidLaunchOrAttach ();
828 if (m_dynamic_loader_ap.get())
829 m_dynamic_loader_ap->DidAttach();
830}
831
832Error
833ProcessGDBRemote::WillResume ()
834{
835 m_continue_packet.Clear();
836 // Start the continue packet we will use to run the target. Each thread
837 // will append what it is supposed to be doing to this packet when the
838 // ThreadList::WillResume() is called. If a thread it supposed
839 // to stay stopped, then don't append anything to this string.
840 m_continue_packet.Printf("vCont");
841 return Error();
842}
843
844Error
845ProcessGDBRemote::DoResume ()
846{
847 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
848 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
849 return Error();
850}
851
852size_t
853ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
854{
855 const uint8_t *trap_opcode = NULL;
856 uint32_t trap_opcode_size = 0;
857
858 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
859 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
860 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
861 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
862
Greg Claytoncf015052010-06-11 03:25:34 +0000863 ArchSpec::CPU arch_cpu = m_arch_spec.GetGenericCPUType();
864 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000865 {
Greg Claytoncf015052010-06-11 03:25:34 +0000866 case ArchSpec::eCPU_i386:
867 case ArchSpec::eCPU_x86_64:
868 trap_opcode = g_i386_breakpoint_opcode;
869 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
870 break;
871
872 case ArchSpec::eCPU_arm:
873 // TODO: fill this in for ARM. We need to dig up the symbol for
874 // the address in the breakpoint locaiton and figure out if it is
875 // an ARM or Thumb breakpoint.
876 trap_opcode = g_arm_breakpoint_opcode;
877 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
878 break;
879
880 case ArchSpec::eCPU_ppc:
881 case ArchSpec::eCPU_ppc64:
882 trap_opcode = g_ppc_breakpoint_opcode;
883 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
884 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000885
Greg Claytoncf015052010-06-11 03:25:34 +0000886 default:
887 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
888 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000889 }
890
891 if (trap_opcode && trap_opcode_size)
892 {
893 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
894 return trap_opcode_size;
895 }
896 return 0;
897}
898
899uint32_t
900ProcessGDBRemote::UpdateThreadListIfNeeded ()
901{
902 // locker will keep a mutex locked until it goes out of scope
903 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD);
904 if (log && log->GetMask().IsSet(GDBR_LOG_VERBOSE))
905 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
906
907 const uint32_t stop_id = GetStopID();
908 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
909 {
910 // Update the thread list's stop id immediately so we don't recurse into this function.
911 ThreadList curr_thread_list (this);
912 curr_thread_list.SetStopID(stop_id);
913
914 Error err;
915 StringExtractorGDBRemote response;
916 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
917 response.IsNormalPacket();
918 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
919 {
920 char ch = response.GetChar();
921 if (ch == 'l')
922 break;
923 if (ch == 'm')
924 {
925 do
926 {
927 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
928
929 if (tid != LLDB_INVALID_THREAD_ID)
930 {
931 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
932 if (thread_sp)
933 thread_sp->GetRegisterContext()->Invalidate();
934 else
935 thread_sp.reset (new ThreadGDBRemote (*this, tid));
936 curr_thread_list.AddThread(thread_sp);
937 }
938
939 ch = response.GetChar();
940 } while (ch == ',');
941 }
942 }
943
944 m_thread_list = curr_thread_list;
945
946 SetThreadStopInfo (m_last_stop_packet);
947 }
948 return GetThreadList().GetSize(false);
949}
950
951
952StateType
953ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
954{
955 const char stop_type = stop_packet.GetChar();
956 switch (stop_type)
957 {
958 case 'T':
959 case 'S':
960 {
961 // Stop with signal and thread info
962 const uint8_t signo = stop_packet.GetHexU8();
963 std::string name;
964 std::string value;
965 std::string thread_name;
966 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +0000967 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +0000968 uint32_t tid = LLDB_INVALID_THREAD_ID;
969 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
970 uint32_t exc_data_count = 0;
971 while (stop_packet.GetNameColonValue(name, value))
972 {
973 if (name.compare("metype") == 0)
974 {
975 // exception type in big endian hex
976 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
977 }
978 else if (name.compare("mecount") == 0)
979 {
980 // exception count in big endian hex
981 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
982 }
983 else if (name.compare("medata") == 0)
984 {
985 // exception data in big endian hex
986 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
987 }
988 else if (name.compare("thread") == 0)
989 {
990 // thread in big endian hex
991 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
992 }
993 else if (name.compare("name") == 0)
994 {
995 thread_name.swap (value);
996 }
997 else if (name.compare("dispatchqaddr") == 0)
998 {
999 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1000 }
1001 }
1002 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1003
1004 if (thread_sp)
1005 {
1006 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1007
1008 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1009 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
1010 Thread::StopInfo& stop_info = gdb_thread->GetStopInfoRef();
1011 gdb_thread->SetStopInfoStopID (GetStopID());
1012 if (exc_type != 0)
1013 {
Greg Clayton7661a982010-07-23 16:45:51 +00001014 stop_info.SetStopReasonWithMachException (exc_type,
1015 exc_data.size(),
1016 &exc_data[0]);
Chris Lattner24943d22010-06-08 16:52:24 +00001017 }
1018 else if (signo)
1019 {
Greg Clayton7661a982010-07-23 16:45:51 +00001020 stop_info.SetStopReasonWithSignal (signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001021 }
1022 else
1023 {
Greg Clayton7661a982010-07-23 16:45:51 +00001024 stop_info.SetStopReasonToNone ();
Chris Lattner24943d22010-06-08 16:52:24 +00001025 }
1026 }
1027 return eStateStopped;
1028 }
1029 break;
1030
1031 case 'W':
1032 // process exited
1033 return eStateExited;
1034
1035 default:
1036 break;
1037 }
1038 return eStateInvalid;
1039}
1040
1041void
1042ProcessGDBRemote::RefreshStateAfterStop ()
1043{
1044 // We must be attaching if we don't already have a valid architecture
1045 if (!m_arch_spec.IsValid())
1046 {
1047 Module *exe_module = GetTarget().GetExecutableModule().get();
1048 if (exe_module)
1049 m_arch_spec = exe_module->GetArchitecture();
1050 }
1051 // Let all threads recover from stopping and do any clean up based
1052 // on the previous thread state (if any).
1053 m_thread_list.RefreshStateAfterStop();
1054
1055 // Discover new threads:
1056 UpdateThreadListIfNeeded ();
1057}
1058
1059Error
1060ProcessGDBRemote::DoHalt ()
1061{
1062 Error error;
1063 if (m_gdb_comm.IsRunning())
1064 {
1065 bool timed_out = false;
1066 if (!m_gdb_comm.SendInterrupt (2, &timed_out))
1067 {
1068 if (timed_out)
1069 error.SetErrorString("timed out sending interrupt packet");
1070 else
1071 error.SetErrorString("unknown error sending interrupt packet");
1072 }
1073 }
1074 return error;
1075}
1076
1077Error
1078ProcessGDBRemote::WillDetach ()
1079{
1080 Error error;
1081 const StateType state = m_private_state.GetValue();
1082
1083 if (IsRunning(state))
1084 error.SetErrorString("Process must be stopped in order to detach.");
1085
1086 return error;
1087}
1088
1089
1090Error
1091ProcessGDBRemote::DoDestroy ()
1092{
1093 Error error;
1094 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1095 if (log)
1096 log->Printf ("ProcessGDBRemote::DoDestroy()");
1097
1098 // Interrupt if our inferior is running...
1099 m_gdb_comm.SendInterrupt (1);
1100 DisableAllBreakpointSites ();
1101 SetExitStatus(-1, "process killed");
1102
1103 StringExtractorGDBRemote response;
1104 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1105 {
1106 if (log)
1107 {
1108 if (response.IsOKPacket())
1109 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1110 else
1111 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1112 }
1113 }
1114
1115 StopAsyncThread ();
1116 m_gdb_comm.StopReadThread();
1117 KillDebugserverProcess ();
1118 return error;
1119}
1120
1121ByteOrder
1122ProcessGDBRemote::GetByteOrder () const
1123{
1124 return m_byte_order;
1125}
1126
1127//------------------------------------------------------------------
1128// Process Queries
1129//------------------------------------------------------------------
1130
1131bool
1132ProcessGDBRemote::IsAlive ()
1133{
1134 return m_gdb_comm.IsConnected();
1135}
1136
1137addr_t
1138ProcessGDBRemote::GetImageInfoAddress()
1139{
1140 if (!m_gdb_comm.IsRunning())
1141 {
1142 StringExtractorGDBRemote response;
1143 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1144 {
1145 if (response.IsNormalPacket())
1146 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1147 }
1148 }
1149 return LLDB_INVALID_ADDRESS;
1150}
1151
1152DynamicLoader *
1153ProcessGDBRemote::GetDynamicLoader()
1154{
1155 return m_dynamic_loader_ap.get();
1156}
1157
1158//------------------------------------------------------------------
1159// Process Memory
1160//------------------------------------------------------------------
1161size_t
1162ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1163{
1164 if (size > m_max_memory_size)
1165 {
1166 // Keep memory read sizes down to a sane limit. This function will be
1167 // called multiple times in order to complete the task by
1168 // lldb_private::Process so it is ok to do this.
1169 size = m_max_memory_size;
1170 }
1171
1172 char packet[64];
1173 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1174 assert (packet_len + 1 < sizeof(packet));
1175 StringExtractorGDBRemote response;
1176 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1177 {
1178 if (response.IsNormalPacket())
1179 {
1180 error.Clear();
1181 return response.GetHexBytes(buf, size, '\xdd');
1182 }
1183 else if (response.IsErrorPacket())
1184 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1185 else if (response.IsUnsupportedPacket())
1186 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1187 else
1188 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1189 }
1190 else
1191 {
1192 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1193 }
1194 return 0;
1195}
1196
1197size_t
1198ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1199{
1200 StreamString packet;
1201 packet.Printf("M%llx,%zx:", addr, size);
1202 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1203 StringExtractorGDBRemote response;
1204 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1205 {
1206 if (response.IsOKPacket())
1207 {
1208 error.Clear();
1209 return size;
1210 }
1211 else if (response.IsErrorPacket())
1212 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1213 else if (response.IsUnsupportedPacket())
1214 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1215 else
1216 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1217 }
1218 else
1219 {
1220 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1221 }
1222 return 0;
1223}
1224
1225lldb::addr_t
1226ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1227{
1228 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1229 if (allocated_addr == LLDB_INVALID_ADDRESS)
1230 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1231 else
1232 error.Clear();
1233 return allocated_addr;
1234}
1235
1236Error
1237ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1238{
1239 Error error;
1240 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1241 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1242 return error;
1243}
1244
1245
1246//------------------------------------------------------------------
1247// Process STDIO
1248//------------------------------------------------------------------
1249
1250size_t
1251ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1252{
1253 Mutex::Locker locker(m_stdio_mutex);
1254 size_t bytes_available = m_stdout_data.size();
1255 if (bytes_available > 0)
1256 {
1257 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1258 if (bytes_available > buf_size)
1259 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001260 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001261 m_stdout_data.erase(0, buf_size);
1262 bytes_available = buf_size;
1263 }
1264 else
1265 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001266 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001267 m_stdout_data.clear();
1268
1269 //ResetEventBits(eBroadcastBitSTDOUT);
1270 }
1271 }
1272 return bytes_available;
1273}
1274
1275size_t
1276ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1277{
1278 // Can we get STDERR through the remote protocol?
1279 return 0;
1280}
1281
1282size_t
1283ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1284{
1285 if (m_stdio_communication.IsConnected())
1286 {
1287 ConnectionStatus status;
1288 m_stdio_communication.Write(src, src_len, status, NULL);
1289 }
1290 return 0;
1291}
1292
1293Error
1294ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1295{
1296 Error error;
1297 assert (bp_site != NULL);
1298
1299 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1300 user_id_t site_id = bp_site->GetID();
1301 const addr_t addr = bp_site->GetLoadAddress();
1302 if (log)
1303 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1304
1305 if (bp_site->IsEnabled())
1306 {
1307 if (log)
1308 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1309 return error;
1310 }
1311 else
1312 {
1313 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1314
1315 if (bp_site->HardwarePreferred())
1316 {
1317 // Try and set hardware breakpoint, and if that fails, fall through
1318 // and set a software breakpoint?
1319 }
1320
1321 if (m_z0_supported)
1322 {
1323 char packet[64];
1324 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1325 assert (packet_len + 1 < sizeof(packet));
1326 StringExtractorGDBRemote response;
1327 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1328 {
1329 if (response.IsUnsupportedPacket())
1330 {
1331 // Disable z packet support and try again
1332 m_z0_supported = 0;
1333 return EnableBreakpoint (bp_site);
1334 }
1335 else if (response.IsOKPacket())
1336 {
1337 bp_site->SetEnabled(true);
1338 bp_site->SetType (BreakpointSite::eExternal);
1339 return error;
1340 }
1341 else
1342 {
1343 uint8_t error_byte = response.GetError();
1344 if (error_byte)
1345 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1346 }
1347 }
1348 }
1349 else
1350 {
1351 return EnableSoftwareBreakpoint (bp_site);
1352 }
1353 }
1354
1355 if (log)
1356 {
1357 const char *err_string = error.AsCString();
1358 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1359 bp_site->GetLoadAddress(),
1360 err_string ? err_string : "NULL");
1361 }
1362 // We shouldn't reach here on a successful breakpoint enable...
1363 if (error.Success())
1364 error.SetErrorToGenericError();
1365 return error;
1366}
1367
1368Error
1369ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1370{
1371 Error error;
1372 assert (bp_site != NULL);
1373 addr_t addr = bp_site->GetLoadAddress();
1374 user_id_t site_id = bp_site->GetID();
1375 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1376 if (log)
1377 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1378
1379 if (bp_site->IsEnabled())
1380 {
1381 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1382
1383 if (bp_site->IsHardware())
1384 {
1385 // TODO: disable hardware breakpoint...
1386 }
1387 else
1388 {
1389 if (m_z0_supported)
1390 {
1391 char packet[64];
1392 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1393 assert (packet_len + 1 < sizeof(packet));
1394 StringExtractorGDBRemote response;
1395 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1396 {
1397 if (response.IsUnsupportedPacket())
1398 {
1399 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1400 }
1401 else if (response.IsOKPacket())
1402 {
1403 if (log)
1404 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1405 bp_site->SetEnabled(false);
1406 return error;
1407 }
1408 else
1409 {
1410 uint8_t error_byte = response.GetError();
1411 if (error_byte)
1412 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1413 }
1414 }
1415 }
1416 else
1417 {
1418 return DisableSoftwareBreakpoint (bp_site);
1419 }
1420 }
1421 }
1422 else
1423 {
1424 if (log)
1425 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1426 return error;
1427 }
1428
1429 if (error.Success())
1430 error.SetErrorToGenericError();
1431 return error;
1432}
1433
1434Error
1435ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1436{
1437 Error error;
1438 if (wp)
1439 {
1440 user_id_t watchID = wp->GetID();
1441 addr_t addr = wp->GetLoadAddress();
1442 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1443 if (log)
1444 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1445 if (wp->IsEnabled())
1446 {
1447 if (log)
1448 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1449 return error;
1450 }
1451 else
1452 {
1453 // Pass down an appropriate z/Z packet...
1454 error.SetErrorString("watchpoints not supported");
1455 }
1456 }
1457 else
1458 {
1459 error.SetErrorString("Watchpoint location argument was NULL.");
1460 }
1461 if (error.Success())
1462 error.SetErrorToGenericError();
1463 return error;
1464}
1465
1466Error
1467ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1468{
1469 Error error;
1470 if (wp)
1471 {
1472 user_id_t watchID = wp->GetID();
1473
1474 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1475
1476 addr_t addr = wp->GetLoadAddress();
1477 if (log)
1478 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1479
1480 if (wp->IsHardware())
1481 {
1482 // Pass down an appropriate z/Z packet...
1483 error.SetErrorString("watchpoints not supported");
1484 }
1485 // TODO: clear software watchpoints if we implement them
1486 }
1487 else
1488 {
1489 error.SetErrorString("Watchpoint location argument was NULL.");
1490 }
1491 if (error.Success())
1492 error.SetErrorToGenericError();
1493 return error;
1494}
1495
1496void
1497ProcessGDBRemote::Clear()
1498{
1499 m_flags = 0;
1500 m_thread_list.Clear();
1501 {
1502 Mutex::Locker locker(m_stdio_mutex);
1503 m_stdout_data.clear();
1504 }
1505 DestoryLibUnwindAddressSpace();
1506}
1507
1508Error
1509ProcessGDBRemote::DoSignal (int signo)
1510{
1511 Error error;
1512 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1513 if (log)
1514 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1515
1516 if (!m_gdb_comm.SendAsyncSignal (signo))
1517 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1518 return error;
1519}
1520
1521
1522Error
1523ProcessGDBRemote::DoDetach()
1524{
1525 Error error;
1526 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1527 if (log)
1528 log->Printf ("ProcessGDBRemote::DoDetach()");
1529
1530 // if (DoSIGSTOP (true))
1531 // {
1532 // CloseChildFileDescriptors ();
1533 //
1534 // // Scope for "locker" so we can reply to all of our exceptions (the SIGSTOP
1535 // // exception).
1536 // {
1537 // Mutex::Locker locker(m_exception_messages_mutex);
1538 // ReplyToAllExceptions();
1539 // }
1540 //
1541 // // Shut down the exception thread and cleanup our exception remappings
1542 // Task().ShutDownExceptionThread();
1543 //
1544 // pid_t pid = GetID();
1545 //
1546 // // Detach from our process while we are stopped.
1547 // errno = 0;
1548 //
1549 // // Detach from our process
1550 // ::ptrace (PT_DETACH, pid, (caddr_t)1, 0);
1551 //
1552 // error.SetErrorToErrno();
1553 //
1554 // if (log || error.Fail())
1555 // error.PutToLog(log, "::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid);
1556 //
1557 // // Resume our task
1558 // Task().Resume();
1559 //
1560 // // NULL our task out as we have already retored all exception ports
1561 // Task().Clear();
1562 //
1563 // // Clear out any notion of the process we once were
1564 // Clear();
1565 //
1566 // SetPrivateState (eStateDetached);
1567 // return true;
1568 // }
1569 return error;
1570}
1571
1572void
1573ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1574{
1575 ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1576 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1577}
1578
1579void
1580ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1581{
1582 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1583 Mutex::Locker locker(m_stdio_mutex);
1584 m_stdout_data.append(s, len);
1585
1586 // FIXME: Make a real data object for this and put it out.
1587 BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1588}
1589
1590
1591Error
1592ProcessGDBRemote::StartDebugserverProcess
1593(
1594 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1595 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1596 char const *inferior_envp[], // Environment to pass along to the inferior program
1597 char const *stdio_path,
1598 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID then attach to this attach_pid
1599 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1600 bool wait_for_launch, // Wait for the process named "attach_name" to launch
1601 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1602)
1603{
1604 Error error;
1605 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1606 {
1607 // If we locate debugserver, keep that located version around
1608 static FileSpec g_debugserver_file_spec;
1609
1610 FileSpec debugserver_file_spec;
1611 char debugserver_path[PATH_MAX];
1612
1613 // Always check to see if we have an environment override for the path
1614 // to the debugserver to use and use it if we do.
1615 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1616 if (env_debugserver_path)
1617 debugserver_file_spec.SetFile (env_debugserver_path);
1618 else
1619 debugserver_file_spec = g_debugserver_file_spec;
1620 bool debugserver_exists = debugserver_file_spec.Exists();
1621 if (!debugserver_exists)
1622 {
1623 // The debugserver binary is in the LLDB.framework/Resources
1624 // directory.
1625 FileSpec framework_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)lldb_private::Initialize));
1626 const char *framework_dir = framework_file_spec.GetDirectory().AsCString();
1627 const char *lldb_framework = ::strstr (framework_dir, "/LLDB.framework");
1628
1629 if (lldb_framework)
1630 {
1631 int len = lldb_framework - framework_dir + strlen ("/LLDB.framework");
1632 ::snprintf (debugserver_path,
1633 sizeof(debugserver_path),
1634 "%.*s/Resources/%s",
1635 len,
1636 framework_dir,
1637 DEBUGSERVER_BASENAME);
1638 debugserver_file_spec.SetFile (debugserver_path);
1639 debugserver_exists = debugserver_file_spec.Exists();
1640 }
1641
1642 if (debugserver_exists)
1643 {
1644 g_debugserver_file_spec = debugserver_file_spec;
1645 }
1646 else
1647 {
1648 g_debugserver_file_spec.Clear();
1649 debugserver_file_spec.Clear();
1650 }
1651 }
1652
1653 if (debugserver_exists)
1654 {
1655 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1656
1657 m_stdio_communication.Clear();
1658 posix_spawnattr_t attr;
1659
1660 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
1661
1662 Error local_err; // Errors that don't affect the spawning.
1663 if (log)
1664 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1665 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1666 if (error.Fail() || log)
1667 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
1668 if (error.Fail())
1669 return error;;
1670
1671#if !defined (__arm__)
1672
1673 // We don't need to do this for ARM, and we really shouldn't now that we
1674 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1675 // to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001676 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001677 {
Greg Claytoncf015052010-06-11 03:25:34 +00001678 cpu_type_t cpu = inferior_arch.GetCPUType();
1679 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1680 {
1681 size_t ocount = 0;
1682 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1683 if (error.Fail() || log)
1684 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 +00001685
Greg Claytoncf015052010-06-11 03:25:34 +00001686 if (error.Fail() != 0 || ocount != 1)
1687 return error;
1688 }
Chris Lattner24943d22010-06-08 16:52:24 +00001689 }
1690
1691#endif
1692
1693 Args debugserver_args;
1694 char arg_cstr[PATH_MAX];
1695 bool launch_process = true;
1696
1697 if (inferior_argv == NULL && attach_pid != LLDB_INVALID_PROCESS_ID)
1698 launch_process = false;
1699 else if (attach_name)
1700 launch_process = false; // Wait for a process whose basename matches that in inferior_argv[0]
1701
1702 bool pass_stdio_path_to_debugserver = true;
1703 lldb_utility::PseudoTerminal pty;
1704 if (stdio_path == NULL)
1705 {
1706 pass_stdio_path_to_debugserver = false;
1707 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
1708 {
1709 struct termios stdin_termios;
1710 if (::tcgetattr (pty.GetMasterFileDescriptor(), &stdin_termios) == 0)
1711 {
1712 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing
1713 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time
1714 ::tcsetattr (pty.GetMasterFileDescriptor(), TCSANOW, &stdin_termios);
1715 }
1716 stdio_path = pty.GetSlaveName (NULL, 0);
1717 }
1718 }
1719
1720 // Start args with "debugserver /file/path -r --"
1721 debugserver_args.AppendArgument(debugserver_path);
1722 debugserver_args.AppendArgument(debugserver_url);
1723 debugserver_args.AppendArgument("--native-regs"); // use native registers, not the GDB registers
1724 debugserver_args.AppendArgument("--setsid"); // make debugserver run in its own session so
1725 // signals generated by special terminal key
1726 // sequences (^C) don't affect debugserver
1727
1728 // Only set the inferior
1729 if (launch_process)
1730 {
1731 if (stdio_path && pass_stdio_path_to_debugserver)
1732 {
1733 debugserver_args.AppendArgument("-s"); // short for --stdio-path
1734 StreamString strm;
1735 strm.Printf("'%s'", stdio_path);
1736 debugserver_args.AppendArgument(strm.GetData()); // path to file to have inferior open as it's STDIO
1737 }
1738 }
1739
1740 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1741 if (env_debugserver_log_file)
1742 {
1743 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1744 debugserver_args.AppendArgument(arg_cstr);
1745 }
1746
1747 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1748 if (env_debugserver_log_flags)
1749 {
1750 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1751 debugserver_args.AppendArgument(arg_cstr);
1752 }
1753// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1754// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1755
1756 // Now append the program arguments
1757 if (launch_process)
1758 {
1759 if (inferior_argv)
1760 {
1761 // Terminate the debugserver args so we can now append the inferior args
1762 debugserver_args.AppendArgument("--");
1763
1764 for (int i = 0; inferior_argv[i] != NULL; ++i)
1765 debugserver_args.AppendArgument (inferior_argv[i]);
1766 }
1767 else
1768 {
1769 // Will send environment entries with the 'QEnvironment:' packet
1770 // Will send arguments with the 'A' packet
1771 }
1772 }
1773 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1774 {
1775 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1776 debugserver_args.AppendArgument (arg_cstr);
1777 }
1778 else if (attach_name && attach_name[0])
1779 {
1780 if (wait_for_launch)
1781 debugserver_args.AppendArgument ("--waitfor");
1782 else
1783 debugserver_args.AppendArgument ("--attach");
1784 debugserver_args.AppendArgument (attach_name);
1785 }
1786
1787 Error file_actions_err;
1788 posix_spawn_file_actions_t file_actions;
1789#if DONT_CLOSE_DEBUGSERVER_STDIO
1790 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1791#else
1792 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1793 if (file_actions_err.Success())
1794 {
1795 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1796 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1797 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1798 }
1799#endif
1800
1801 if (log)
1802 {
1803 StreamString strm;
1804 debugserver_args.Dump (&strm);
1805 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1806 }
1807
1808 error.SetError(::posix_spawnp (&m_debugserver_pid,
1809 debugserver_path,
1810 file_actions_err.Success() ? &file_actions : NULL,
1811 &attr,
1812 debugserver_args.GetArgumentVector(),
1813 (char * const*)inferior_envp),
1814 eErrorTypePOSIX);
1815
Greg Claytone9d0df42010-07-02 01:29:13 +00001816
1817 ::posix_spawnattr_destroy (&attr);
1818
Chris Lattner24943d22010-06-08 16:52:24 +00001819 if (file_actions_err.Success())
1820 ::posix_spawn_file_actions_destroy (&file_actions);
1821
1822 // We have seen some cases where posix_spawnp was returning a valid
1823 // looking pid even when an error was returned, so clear it out
1824 if (error.Fail())
1825 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1826
1827 if (error.Fail() || log)
1828 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);
1829
1830// if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1831// {
1832// std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true));
1833// if (conn_ap.get())
1834// {
1835// m_stdio_communication.SetConnection(conn_ap.release());
1836// if (m_stdio_communication.IsConnected())
1837// {
1838// m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1839// m_stdio_communication.StartReadThread();
1840// }
1841// }
1842// }
1843 }
1844 else
1845 {
1846 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1847 }
1848
1849 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1850 StartAsyncThread ();
1851 }
1852 return error;
1853}
1854
1855bool
1856ProcessGDBRemote::MonitorDebugserverProcess
1857(
1858 void *callback_baton,
1859 lldb::pid_t debugserver_pid,
1860 int signo, // Zero for no signal
1861 int exit_status // Exit value of process if signal is zero
1862)
1863{
1864 // We pass in the ProcessGDBRemote inferior process it and name it
1865 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1866 // pointer value itself, thus we need the double cast...
1867
1868 // "debugserver_pid" argument passed in is the process ID for
1869 // debugserver that we are tracking...
1870
1871 lldb::pid_t gdb_remote_pid = (lldb::pid_t)(intptr_t)callback_baton;
Greg Clayton63094e02010-06-23 01:19:29 +00001872 TargetSP target_sp(Debugger::FindTargetWithProcessID (gdb_remote_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001873 if (target_sp)
1874 {
1875 ProcessSP process_sp (target_sp->GetProcessSP());
1876 if (process_sp)
1877 {
1878 // Sleep for a half a second to make sure our inferior process has
1879 // time to set its exit status before we set it incorrectly when
1880 // both the debugserver and the inferior process shut down.
1881 usleep (500000);
1882 // If our process hasn't yet exited, debugserver might have died.
1883 // If the process did exit, the we are reaping it.
1884 if (process_sp->GetState() != eStateExited)
1885 {
1886 char error_str[1024];
1887 if (signo)
1888 {
1889 const char *signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1890 if (signal_cstr)
1891 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
1892 else
1893 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
1894 }
1895 else
1896 {
1897 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
1898 }
1899
1900 process_sp->SetExitStatus (-1, error_str);
1901 }
1902 else
1903 {
1904 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)process_sp.get();
1905 // Debugserver has exited we need to let our ProcessGDBRemote
1906 // know that it no longer has a debugserver instance
1907 gdb_process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1908 // We are returning true to this function below, so we can
1909 // forget about the monitor handle.
1910 gdb_process->m_debugserver_monitor = 0;
1911 }
1912 }
1913 }
1914 return true;
1915}
1916
1917void
1918ProcessGDBRemote::KillDebugserverProcess ()
1919{
1920 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1921 {
1922 ::kill (m_debugserver_pid, SIGINT);
1923 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1924 }
1925}
1926
1927void
1928ProcessGDBRemote::Initialize()
1929{
1930 static bool g_initialized = false;
1931
1932 if (g_initialized == false)
1933 {
1934 g_initialized = true;
1935 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1936 GetPluginDescriptionStatic(),
1937 CreateInstance);
1938
1939 Log::Callbacks log_callbacks = {
1940 ProcessGDBRemoteLog::DisableLog,
1941 ProcessGDBRemoteLog::EnableLog,
1942 ProcessGDBRemoteLog::ListLogCategories
1943 };
1944
1945 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1946 }
1947}
1948
1949bool
1950ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1951{
1952 if (m_curr_tid == tid)
1953 return true;
1954
1955 char packet[32];
1956 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1957 assert (packet_len + 1 < sizeof(packet));
1958 StringExtractorGDBRemote response;
1959 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1960 {
1961 if (response.IsOKPacket())
1962 {
1963 m_curr_tid = tid;
1964 return true;
1965 }
1966 }
1967 return false;
1968}
1969
1970bool
1971ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
1972{
1973 if (m_curr_tid_run == tid)
1974 return true;
1975
1976 char packet[32];
1977 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1978 assert (packet_len + 1 < sizeof(packet));
1979 StringExtractorGDBRemote response;
1980 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1981 {
1982 if (response.IsOKPacket())
1983 {
1984 m_curr_tid_run = tid;
1985 return true;
1986 }
1987 }
1988 return false;
1989}
1990
1991void
1992ProcessGDBRemote::ResetGDBRemoteState ()
1993{
1994 // Reset and GDB remote state
1995 m_curr_tid = LLDB_INVALID_THREAD_ID;
1996 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
1997 m_z0_supported = 1;
1998}
1999
2000
2001bool
2002ProcessGDBRemote::StartAsyncThread ()
2003{
2004 ResetGDBRemoteState ();
2005
2006 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2007
2008 if (log)
2009 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2010
2011 // Create a thread that watches our internal state and controls which
2012 // events make it to clients (into the DCProcess event queue).
2013 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2014 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2015}
2016
2017void
2018ProcessGDBRemote::StopAsyncThread ()
2019{
2020 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2021
2022 if (log)
2023 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2024
2025 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2026
2027 // Stop the stdio thread
2028 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2029 {
2030 Host::ThreadJoin (m_async_thread, NULL, NULL);
2031 }
2032}
2033
2034
2035void *
2036ProcessGDBRemote::AsyncThread (void *arg)
2037{
2038 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2039
2040 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
2041 if (log)
2042 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2043
2044 Listener listener ("ProcessGDBRemote::AsyncThread");
2045 EventSP event_sp;
2046 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2047 eBroadcastBitAsyncThreadShouldExit;
2048
2049 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2050 {
2051 bool done = false;
2052 while (!done)
2053 {
2054 if (log)
2055 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2056 if (listener.WaitForEvent (NULL, event_sp))
2057 {
2058 const uint32_t event_type = event_sp->GetType();
2059 switch (event_type)
2060 {
2061 case eBroadcastBitAsyncContinue:
2062 {
2063 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2064
2065 if (continue_packet)
2066 {
2067 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2068 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2069 if (log)
2070 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2071
2072 process->SetPrivateState(eStateRunning);
2073 StringExtractorGDBRemote response;
2074 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2075
2076 switch (stop_state)
2077 {
2078 case eStateStopped:
2079 case eStateCrashed:
2080 case eStateSuspended:
2081 process->m_last_stop_packet = response;
2082 process->m_last_stop_packet.SetFilePos (0);
2083 process->SetPrivateState (stop_state);
2084 break;
2085
2086 case eStateExited:
2087 process->m_last_stop_packet = response;
2088 process->m_last_stop_packet.SetFilePos (0);
2089 response.SetFilePos(1);
2090 process->SetExitStatus(response.GetHexU8(), NULL);
2091 done = true;
2092 break;
2093
2094 case eStateInvalid:
2095 break;
2096
2097 default:
2098 process->SetPrivateState (stop_state);
2099 break;
2100 }
2101 }
2102 }
2103 break;
2104
2105 case eBroadcastBitAsyncThreadShouldExit:
2106 if (log)
2107 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2108 done = true;
2109 break;
2110
2111 default:
2112 if (log)
2113 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2114 done = true;
2115 break;
2116 }
2117 }
2118 else
2119 {
2120 if (log)
2121 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2122 done = true;
2123 }
2124 }
2125 }
2126
2127 if (log)
2128 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2129
2130 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2131 return NULL;
2132}
2133
2134lldb_private::unw_addr_space_t
2135ProcessGDBRemote::GetLibUnwindAddressSpace ()
2136{
2137 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002138
2139 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2140 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002141 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002142 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002143 target_type = UNW_TARGET_X86_64;
2144
2145 if (m_libunwind_addr_space)
2146 {
2147 if (m_libunwind_target_type != target_type)
2148 DestoryLibUnwindAddressSpace();
2149 else
2150 return m_libunwind_addr_space;
2151 }
2152 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2153 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2154 if (m_libunwind_addr_space)
2155 m_libunwind_target_type = target_type;
2156 else
2157 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2158 return m_libunwind_addr_space;
2159}
2160
2161void
2162ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2163{
2164 if (m_libunwind_addr_space)
2165 {
2166 unw_destroy_addr_space (m_libunwind_addr_space);
2167 m_libunwind_addr_space = NULL;
2168 }
2169 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2170}
2171
2172
2173const char *
2174ProcessGDBRemote::GetDispatchQueueNameForThread
2175(
2176 addr_t thread_dispatch_qaddr,
2177 std::string &dispatch_queue_name
2178)
2179{
2180 dispatch_queue_name.clear();
2181 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2182 {
2183 // Cache the dispatch_queue_offsets_addr value so we don't always have
2184 // to look it up
2185 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2186 {
2187 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib")));
2188 if (module_sp.get() == NULL)
2189 return NULL;
2190
2191 const Symbol *dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (ConstString("dispatch_queue_offsets"), eSymbolTypeData);
2192 if (dispatch_queue_offsets_symbol)
2193 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(this);
2194
2195 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2196 return NULL;
2197 }
2198
2199 uint8_t memory_buffer[8];
2200 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2201
2202 // Excerpt from src/queue_private.h
2203 struct dispatch_queue_offsets_s
2204 {
2205 uint16_t dqo_version;
2206 uint16_t dqo_label;
2207 uint16_t dqo_label_size;
2208 } dispatch_queue_offsets;
2209
2210
2211 Error error;
2212 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2213 {
2214 uint32_t data_offset = 0;
2215 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2216 {
2217 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2218 {
2219 data_offset = 0;
2220 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2221 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2222 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2223 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2224 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2225 dispatch_queue_name.erase (bytes_read);
2226 }
2227 }
2228 }
2229 }
2230 if (dispatch_queue_name.empty())
2231 return NULL;
2232 return dispatch_queue_name.c_str();
2233}
2234