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