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