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