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