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