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