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