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