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