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