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