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