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