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