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