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