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