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