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