blob: 7045f2ba050481d08ddafa02606a90538bfa0245 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Sean Callanan483d00a2012-07-19 18:07:36 +000014#include <netinet/in.h>
Greg Clayton989816b2011-05-14 01:50:35 +000015#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000017#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000018#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000019
20// C++ Includes
21#include <algorithm>
22#include <map>
23
24// Other libraries and framework includes
25
Johnny Chenecd4feb2011-10-14 00:42:25 +000026#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000027#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Core/ArchSpec.h"
29#include "lldb/Core/Debugger.h"
30#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000031#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "lldb/Core/InputReader.h"
33#include "lldb/Core/Module.h"
34#include "lldb/Core/PluginManager.h"
35#include "lldb/Core/State.h"
Greg Clayton33559462012-04-13 21:24:18 +000036#include "lldb/Core/StreamFile.h"
Chris Lattner24943d22010-06-08 16:52:24 +000037#include "lldb/Core/StreamString.h"
38#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000039#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040#include "lldb/Host/TimeValue.h"
41#include "lldb/Symbol/ObjectFile.h"
42#include "lldb/Target/DynamicLoader.h"
43#include "lldb/Target/Target.h"
44#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000045#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000046#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000047
48// Project includes
49#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000050#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molenda3aeb2862012-07-25 03:40:06 +000051#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham06b84492012-07-04 00:35:43 +000052#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000053#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000054#include "GDBRemoteRegisterContext.h"
55#include "ProcessGDBRemote.h"
56#include "ProcessGDBRemoteLog.h"
57#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000058
Greg Clayton451fa822012-04-09 22:46:21 +000059namespace lldb
60{
61 // Provide a function that can easily dump the packet history if we know a
62 // ProcessGDBRemote * value (which we can get from logs or from debugging).
63 // We need the function in the lldb namespace so it makes it into the final
64 // executable since the LLDB shared library only exports stuff in the lldb
65 // namespace. This allows you to attach with a debugger and call this
66 // function and get the packet history dumped to a file.
67 void
68 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
69 {
Greg Clayton33559462012-04-13 21:24:18 +000070 lldb_private::StreamFile strm;
71 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
72 if (error.Success())
73 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000074 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000075}
Chris Lattner24943d22010-06-08 16:52:24 +000076
Chris Lattner24943d22010-06-08 16:52:24 +000077
78#define DEBUGSERVER_BASENAME "debugserver"
79using namespace lldb;
80using namespace lldb_private;
81
Jim Inghamf9600482011-03-29 21:45:47 +000082static bool rand_initialized = false;
83
Sean Callanan483d00a2012-07-19 18:07:36 +000084// TODO Randomly assigning a port is unsafe. We should get an unused
85// ephemeral port from the kernel and make sure we reserve it before passing
86// it to debugserver.
87
88#if defined (__APPLE__)
89#define LOW_PORT (IPPORT_RESERVED)
90#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
91#else
92#define LOW_PORT (1024u)
93#define HIGH_PORT (49151u)
94#endif
95
Chris Lattner24943d22010-06-08 16:52:24 +000096static inline uint16_t
97get_random_port ()
98{
Jim Inghamf9600482011-03-29 21:45:47 +000099 if (!rand_initialized)
100 {
Stephen Wilson60f19d52011-03-30 00:12:40 +0000101 time_t seed = time(NULL);
102
Jim Inghamf9600482011-03-29 21:45:47 +0000103 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +0000104 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +0000105 }
Sean Callanan483d00a2012-07-19 18:07:36 +0000106 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner24943d22010-06-08 16:52:24 +0000107}
108
109
110const char *
111ProcessGDBRemote::GetPluginNameStatic()
112{
Greg Claytonb1888f22011-03-19 01:12:21 +0000113 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000114}
115
116const char *
117ProcessGDBRemote::GetPluginDescriptionStatic()
118{
119 return "GDB Remote protocol based debugging plug-in.";
120}
121
122void
123ProcessGDBRemote::Terminate()
124{
125 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
126}
127
128
Greg Clayton46c9a352012-02-09 06:16:32 +0000129lldb::ProcessSP
130ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000131{
Greg Clayton46c9a352012-02-09 06:16:32 +0000132 lldb::ProcessSP process_sp;
133 if (crash_file_path == NULL)
134 process_sp.reset (new ProcessGDBRemote (target, listener));
135 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000136}
137
138bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000139ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000140{
Greg Clayton61ddf562011-10-21 21:41:45 +0000141 if (plugin_specified_by_name)
142 return true;
143
Chris Lattner24943d22010-06-08 16:52:24 +0000144 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000145 Module *exe_module = target.GetExecutableModulePointer();
146 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000147 {
148 ObjectFile *exe_objfile = exe_module->GetObjectFile();
149 // We can't debug core files...
150 switch (exe_objfile->GetType())
151 {
152 case ObjectFile::eTypeInvalid:
153 case ObjectFile::eTypeCoreFile:
154 case ObjectFile::eTypeDebugInfo:
155 case ObjectFile::eTypeObjectFile:
156 case ObjectFile::eTypeSharedLibrary:
157 case ObjectFile::eTypeStubLibrary:
158 return false;
159 case ObjectFile::eTypeExecutable:
160 case ObjectFile::eTypeDynamicLinker:
161 case ObjectFile::eTypeUnknown:
162 break;
163 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000164 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000165 }
Jim Ingham7508e732010-08-09 23:31:02 +0000166 // However, if there is no executable module, we return true since we might be preparing to attach.
167 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000168}
169
170//----------------------------------------------------------------------
171// ProcessGDBRemote constructor
172//----------------------------------------------------------------------
173ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
174 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000175 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000176 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000177 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000178 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000179 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000180 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000181 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000182 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000183 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000184 m_continue_c_tids (),
185 m_continue_C_tids (),
186 m_continue_s_tids (),
187 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000188 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000189 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000190 m_addr_to_mmap_size (),
191 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000192 m_waiting_for_attach (false),
193 m_destroy_tried_resuming (false)
Chris Lattner24943d22010-06-08 16:52:24 +0000194{
Greg Claytonff39f742011-04-01 00:29:43 +0000195 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
196 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000197 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000198}
199
200//----------------------------------------------------------------------
201// Destructor
202//----------------------------------------------------------------------
203ProcessGDBRemote::~ProcessGDBRemote()
204{
205 // m_mach_process.UnregisterNotificationCallbacks (this);
206 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000207 // We need to call finalize on the process before destroying ourselves
208 // to make sure all of the broadcaster cleanup goes as planned. If we
209 // destruct this class, then Process::~Process() might have problems
210 // trying to fully destroy the broadcaster.
211 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000212}
213
214//----------------------------------------------------------------------
215// PluginInterface
216//----------------------------------------------------------------------
217const char *
218ProcessGDBRemote::GetPluginName()
219{
220 return "Process debugging plug-in that uses the GDB remote protocol";
221}
222
223const char *
224ProcessGDBRemote::GetShortPluginName()
225{
226 return GetPluginNameStatic();
227}
228
229uint32_t
230ProcessGDBRemote::GetPluginVersion()
231{
232 return 1;
233}
234
235void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000236ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000237{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000238 if (!force && m_register_info.GetNumRegisters() > 0)
239 return;
240
241 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000242 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000243 uint32_t reg_offset = 0;
244 uint32_t reg_num = 0;
Greg Clayton4a379b12012-07-17 03:23:13 +0000245 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton61d043b2011-03-22 04:00:09 +0000246 response_type == StringExtractorGDBRemote::eResponse;
247 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000248 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000249 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
250 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000251 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000252 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000253 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000254 response_type = response.GetResponseType();
255 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000256 {
257 std::string name;
258 std::string value;
259 ConstString reg_name;
260 ConstString alt_name;
261 ConstString set_name;
262 RegisterInfo reg_info = { NULL, // Name
263 NULL, // Alt name
264 0, // byte size
265 reg_offset, // offset
266 eEncodingUint, // encoding
267 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000268 {
269 LLDB_INVALID_REGNUM, // GCC reg num
270 LLDB_INVALID_REGNUM, // DWARF reg num
271 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000272 reg_num, // GDB reg num
273 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000274 },
275 NULL,
276 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000277 };
278
279 while (response.GetNameColonValue(name, value))
280 {
281 if (name.compare("name") == 0)
282 {
283 reg_name.SetCString(value.c_str());
284 }
285 else if (name.compare("alt-name") == 0)
286 {
287 alt_name.SetCString(value.c_str());
288 }
289 else if (name.compare("bitsize") == 0)
290 {
291 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
292 }
293 else if (name.compare("offset") == 0)
294 {
295 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000296 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000297 {
298 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000299 }
300 }
301 else if (name.compare("encoding") == 0)
302 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000303 const Encoding encoding = Args::StringToEncoding (value.c_str());
304 if (encoding != eEncodingInvalid)
305 reg_info.encoding = encoding;
Chris Lattner24943d22010-06-08 16:52:24 +0000306 }
307 else if (name.compare("format") == 0)
308 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000309 Format format = eFormatInvalid;
310 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
311 reg_info.format = format;
312 else if (value.compare("binary") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000313 reg_info.format = eFormatBinary;
314 else if (value.compare("decimal") == 0)
315 reg_info.format = eFormatDecimal;
316 else if (value.compare("hex") == 0)
317 reg_info.format = eFormatHex;
318 else if (value.compare("float") == 0)
319 reg_info.format = eFormatFloat;
320 else if (value.compare("vector-sint8") == 0)
321 reg_info.format = eFormatVectorOfSInt8;
322 else if (value.compare("vector-uint8") == 0)
323 reg_info.format = eFormatVectorOfUInt8;
324 else if (value.compare("vector-sint16") == 0)
325 reg_info.format = eFormatVectorOfSInt16;
326 else if (value.compare("vector-uint16") == 0)
327 reg_info.format = eFormatVectorOfUInt16;
328 else if (value.compare("vector-sint32") == 0)
329 reg_info.format = eFormatVectorOfSInt32;
330 else if (value.compare("vector-uint32") == 0)
331 reg_info.format = eFormatVectorOfUInt32;
332 else if (value.compare("vector-float32") == 0)
333 reg_info.format = eFormatVectorOfFloat32;
334 else if (value.compare("vector-uint128") == 0)
335 reg_info.format = eFormatVectorOfUInt128;
336 }
337 else if (name.compare("set") == 0)
338 {
339 set_name.SetCString(value.c_str());
340 }
341 else if (name.compare("gcc") == 0)
342 {
343 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
344 }
345 else if (name.compare("dwarf") == 0)
346 {
347 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
348 }
349 else if (name.compare("generic") == 0)
350 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000351 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000352 }
353 }
354
Jason Molenda53d96862010-06-11 23:44:18 +0000355 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000356 assert (reg_info.byte_size != 0);
357 reg_offset += reg_info.byte_size;
358 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
359 }
360 }
361 else
362 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000363 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000364 }
365 }
366
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000367 // We didn't get anything if the accumulated reg_num is zero. See if we are
368 // debugging ARM and fill with a hard coded register set until we can get an
369 // updated debugserver down on the devices.
370 // On the other hand, if the accumulated reg_num is positive, see if we can
371 // add composite registers to the existing primordial ones.
372 bool from_scratch = (reg_num == 0);
373
374 const ArchSpec &target_arch = GetTarget().GetArchitecture();
375 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
376 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000377 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000378 if (remote_arch.IsValid()
379 && remote_arch.GetMachine() == llvm::Triple::arm
380 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
381 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000382 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000383 else if (target_arch.GetMachine() == llvm::Triple::arm)
384 {
385 m_register_info.HardcodeARMRegisters(from_scratch);
386 }
387
Johnny Chend2e30662012-05-22 00:57:05 +0000388 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000389 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
390 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000391 m_register_info.Addx86_64ConvenienceRegisters();
392
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000393 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000394 m_register_info.Finalize ();
395}
396
397Error
398ProcessGDBRemote::WillLaunch (Module* module)
399{
400 return WillLaunchOrAttach ();
401}
402
403Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000404ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000405{
406 return WillLaunchOrAttach ();
407}
408
409Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000410ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000411{
412 return WillLaunchOrAttach ();
413}
414
415Error
Greg Claytone71e2582011-02-04 01:58:07 +0000416ProcessGDBRemote::DoConnectRemote (const char *remote_url)
417{
418 Error error (WillLaunchOrAttach ());
419
420 if (error.Fail())
421 return error;
422
Greg Clayton180546b2011-04-30 01:09:13 +0000423 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000424
425 if (error.Fail())
426 return error;
427 StartAsyncThread ();
428
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000429 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000430 if (pid == LLDB_INVALID_PROCESS_ID)
431 {
432 // We don't have a valid process ID, so note that we are connected
433 // and could now request to launch or attach, or get remote process
434 // listings...
435 SetPrivateState (eStateConnected);
436 }
437 else
438 {
439 // We have a valid process
440 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000441 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000442 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000443 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000444 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000445 if (state == eStateStopped)
446 {
447 SetPrivateState (state);
448 }
449 else
Greg Claytond9919d32011-12-01 23:28:38 +0000450 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytone71e2582011-02-04 01:58:07 +0000451 }
452 else
Greg Claytond9919d32011-12-01 23:28:38 +0000453 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000454 }
Jason Molendacb740b32012-05-03 22:37:30 +0000455
456 if (error.Success()
457 && !GetTarget().GetArchitecture().IsValid()
458 && m_gdb_comm.GetHostArchitecture().IsValid())
459 {
460 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
461 }
462
Greg Claytone71e2582011-02-04 01:58:07 +0000463 return error;
464}
465
466Error
Chris Lattner24943d22010-06-08 16:52:24 +0000467ProcessGDBRemote::WillLaunchOrAttach ()
468{
469 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000470 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000471 return error;
472}
473
474//----------------------------------------------------------------------
475// Process Control
476//----------------------------------------------------------------------
477Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000478ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000479{
Greg Clayton4b407112010-09-30 21:49:03 +0000480 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000481
482 uint32_t launch_flags = launch_info.GetFlags().Get();
483 const char *stdin_path = NULL;
484 const char *stdout_path = NULL;
485 const char *stderr_path = NULL;
486 const char *working_dir = launch_info.GetWorkingDirectory();
487
488 const ProcessLaunchInfo::FileAction *file_action;
489 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
490 if (file_action)
491 {
492 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
493 stdin_path = file_action->GetPath();
494 }
495 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
496 if (file_action)
497 {
498 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
499 stdout_path = file_action->GetPath();
500 }
501 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
502 if (file_action)
503 {
504 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
505 stderr_path = file_action->GetPath();
506 }
507
Chris Lattner24943d22010-06-08 16:52:24 +0000508 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
509 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
510 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000511 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000512
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000513 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000514 if (object_file)
515 {
Chris Lattner24943d22010-06-08 16:52:24 +0000516 char host_port[128];
517 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000518 char connect_url[128];
519 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000520
Greg Claytona2f74232011-02-24 22:24:29 +0000521 // Make sure we aren't already connected?
522 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000523 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000524 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000525 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000526 {
Johnny Chenc143d622011-08-09 18:56:45 +0000527 if (log)
528 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000529 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000530 }
Chris Lattner24943d22010-06-08 16:52:24 +0000531
Greg Claytone71e2582011-02-04 01:58:07 +0000532 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000533 }
534
535 if (error.Success())
536 {
537 lldb_utility::PseudoTerminal pty;
538 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000539
540 // If the debugserver is local and we aren't disabling STDIO, lets use
541 // a pseudo terminal to instead of relying on the 'O' packets for stdio
542 // since 'O' packets can really slow down debugging if the inferior
543 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000544 PlatformSP platform_sp (m_target.GetPlatform());
545 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000546 {
547 const char *slave_name = NULL;
548 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000549 {
Greg Claytona2f74232011-02-24 22:24:29 +0000550 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
551 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000552 }
Greg Claytona2f74232011-02-24 22:24:29 +0000553 if (stdin_path == NULL)
554 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000555
Greg Claytona2f74232011-02-24 22:24:29 +0000556 if (stdout_path == NULL)
557 stdout_path = slave_name;
558
559 if (stderr_path == NULL)
560 stderr_path = slave_name;
561 }
562
Greg Claytonafb81862011-03-02 21:34:46 +0000563 // Set STDIN to /dev/null if we want STDIO disabled or if either
564 // STDOUT or STDERR have been set to something and STDIN hasn't
565 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000566 stdin_path = "/dev/null";
567
Greg Claytonafb81862011-03-02 21:34:46 +0000568 // Set STDOUT to /dev/null if we want STDIO disabled or if either
569 // STDIN or STDERR have been set to something and STDOUT hasn't
570 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000571 stdout_path = "/dev/null";
572
Greg Claytonafb81862011-03-02 21:34:46 +0000573 // Set STDERR to /dev/null if we want STDIO disabled or if either
574 // STDIN or STDOUT have been set to something and STDERR hasn't
575 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000576 stderr_path = "/dev/null";
577
578 if (stdin_path)
579 m_gdb_comm.SetSTDIN (stdin_path);
580 if (stdout_path)
581 m_gdb_comm.SetSTDOUT (stdout_path);
582 if (stderr_path)
583 m_gdb_comm.SetSTDERR (stderr_path);
584
585 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
586
Greg Claytona4582402011-05-08 04:53:50 +0000587 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000588
589 if (working_dir && working_dir[0])
590 {
591 m_gdb_comm.SetWorkingDir (working_dir);
592 }
593
594 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000595 const Args &environment = launch_info.GetEnvironmentEntries();
596 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000597 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000598 size_t num_environment_entries = environment.GetArgumentCount();
599 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000600 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000601 const char *env_entry = environment.GetArgumentAtIndex(i);
602 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000603 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000604 }
Greg Claytona2f74232011-02-24 22:24:29 +0000605 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000606
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000607 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000608 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000609 if (arg_packet_err == 0)
610 {
611 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000612 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000613 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000614 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000615 }
616 else
617 {
Greg Claytona2f74232011-02-24 22:24:29 +0000618 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000619 }
Greg Claytona2f74232011-02-24 22:24:29 +0000620 }
621 else
622 {
Greg Clayton9c236732011-10-26 00:56:27 +0000623 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000624 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000625
626 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000627
Greg Claytona2f74232011-02-24 22:24:29 +0000628 if (GetID() == LLDB_INVALID_PROCESS_ID)
629 {
Johnny Chenc143d622011-08-09 18:56:45 +0000630 if (log)
631 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000632 KillDebugserverProcess ();
633 return error;
634 }
635
Greg Clayton261a18b2011-06-02 22:22:38 +0000636 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000637 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000638 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000639
640 if (!disable_stdio)
641 {
642 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000643 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000644 }
Chris Lattner24943d22010-06-08 16:52:24 +0000645 }
646 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000647 else
648 {
Johnny Chenc143d622011-08-09 18:56:45 +0000649 if (log)
650 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000651 }
Chris Lattner24943d22010-06-08 16:52:24 +0000652 }
653 else
654 {
655 // Set our user ID to an invalid process ID.
656 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000657 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
658 exe_module->GetFileSpec().GetFilename().AsCString(),
659 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000660 }
Chris Lattner24943d22010-06-08 16:52:24 +0000661 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000662
Chris Lattner24943d22010-06-08 16:52:24 +0000663}
664
665
666Error
Greg Claytone71e2582011-02-04 01:58:07 +0000667ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000668{
669 Error error;
670 // Sleep and wait a bit for debugserver to start to listen...
671 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
672 if (conn_ap.get())
673 {
Chris Lattner24943d22010-06-08 16:52:24 +0000674 const uint32_t max_retry_count = 50;
675 uint32_t retry_count = 0;
676 while (!m_gdb_comm.IsConnected())
677 {
Greg Claytone71e2582011-02-04 01:58:07 +0000678 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000679 {
680 m_gdb_comm.SetConnection (conn_ap.release());
681 break;
682 }
683 retry_count++;
684
685 if (retry_count >= max_retry_count)
686 break;
687
688 usleep (100000);
689 }
690 }
691
692 if (!m_gdb_comm.IsConnected())
693 {
694 if (error.Success())
695 error.SetErrorString("not connected to remote gdb server");
696 return error;
697 }
698
Greg Clayton24bc5d92011-03-30 18:16:51 +0000699 // We always seem to be able to open a connection to a local port
700 // so we need to make sure we can then send data to it. If we can't
701 // then we aren't actually connected to anything, so try and do the
702 // handshake with the remote GDB server and make sure that goes
703 // alright.
704 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000705 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000706 m_gdb_comm.Disconnect();
707 if (error.Success())
708 error.SetErrorString("not connected to remote gdb server");
709 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000710 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000711 m_gdb_comm.ResetDiscoverableSettings();
712 m_gdb_comm.QueryNoAckModeSupported ();
713 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000714 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000715 m_gdb_comm.GetHostInfo ();
716 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000717 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000718
719 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
720 for (size_t idx = 0; idx < num_cmds; idx++)
721 {
722 StringExtractorGDBRemote response;
723 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx));
724 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
725 }
Chris Lattner24943d22010-06-08 16:52:24 +0000726 return error;
727}
728
729void
730ProcessGDBRemote::DidLaunchOrAttach ()
731{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000732 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
733 if (log)
734 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000735 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000736 {
737 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
738
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000739 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000740
Chris Lattner24943d22010-06-08 16:52:24 +0000741 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000742
Greg Claytoncb8977d2011-03-23 00:09:55 +0000743 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
744 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000745 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000746 ArchSpec &target_arch = GetTarget().GetArchitecture();
747
748 if (target_arch.IsValid())
749 {
750 // If the remote host is ARM and we have apple as the vendor, then
751 // ARM executables and shared libraries can have mixed ARM architectures.
752 // You can have an armv6 executable, and if the host is armv7, then the
753 // system will load the best possible architecture for all shared libraries
754 // it has, so we really need to take the remote host architecture as our
755 // defacto architecture in this case.
756
757 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
758 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
759 {
760 target_arch = gdb_remote_arch;
761 }
762 else
763 {
764 // Fill in what is missing in the triple
765 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
766 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000767 if (target_triple.getVendorName().size() == 0)
768 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000769 target_triple.setVendor (remote_triple.getVendor());
770
Greg Clayton2f085c62011-05-15 01:25:55 +0000771 if (target_triple.getOSName().size() == 0)
772 {
773 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000774
Greg Clayton2f085c62011-05-15 01:25:55 +0000775 if (target_triple.getEnvironmentName().size() == 0)
776 target_triple.setEnvironment (remote_triple.getEnvironment());
777 }
778 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000779 }
780 }
781 else
782 {
783 // The target doesn't have a valid architecture yet, set it from
784 // the architecture we got from the remote GDB server
785 target_arch = gdb_remote_arch;
786 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000787 }
Chris Lattner24943d22010-06-08 16:52:24 +0000788 }
789}
790
791void
792ProcessGDBRemote::DidLaunch ()
793{
794 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000795}
796
797Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000798ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000799{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000800 ProcessAttachInfo attach_info;
801 return DoAttachToProcessWithID(attach_pid, attach_info);
802}
803
804Error
805ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
806{
Chris Lattner24943d22010-06-08 16:52:24 +0000807 Error error;
808 // Clear out and clean up from any current state
809 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000810 if (attach_pid != LLDB_INVALID_PROCESS_ID)
811 {
Greg Claytona2f74232011-02-24 22:24:29 +0000812 // Make sure we aren't already connected?
813 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000814 {
Greg Claytona2f74232011-02-24 22:24:29 +0000815 char host_port[128];
816 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
817 char connect_url[128];
818 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000819
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000820 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000821
822 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000823 {
Greg Claytona2f74232011-02-24 22:24:29 +0000824 const char *error_string = error.AsCString();
825 if (error_string == NULL)
826 error_string = "unable to launch " DEBUGSERVER_BASENAME;
827
828 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000829 }
Greg Claytona2f74232011-02-24 22:24:29 +0000830 else
831 {
832 error = ConnectToDebugserver (connect_url);
833 }
834 }
835
836 if (error.Success())
837 {
838 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000839 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000840 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000841 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000842 }
843 }
Chris Lattner24943d22010-06-08 16:52:24 +0000844 return error;
845}
846
847size_t
848ProcessGDBRemote::AttachInputReaderCallback
849(
850 void *baton,
851 InputReader *reader,
852 lldb::InputReaderAction notification,
853 const char *bytes,
854 size_t bytes_len
855)
856{
857 if (notification == eInputReaderGotToken)
858 {
859 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
860 if (gdb_process->m_waiting_for_attach)
861 gdb_process->m_waiting_for_attach = false;
862 reader->SetIsDone(true);
863 return 1;
864 }
865 return 0;
866}
867
868Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000869ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000870{
871 Error error;
872 // Clear out and clean up from any current state
873 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000874
Chris Lattner24943d22010-06-08 16:52:24 +0000875 if (process_name && process_name[0])
876 {
Greg Claytona2f74232011-02-24 22:24:29 +0000877 // Make sure we aren't already connected?
878 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000879 {
Greg Claytona2f74232011-02-24 22:24:29 +0000880 char host_port[128];
881 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
882 char connect_url[128];
883 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
884
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000885 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000886 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000887 {
Greg Claytona2f74232011-02-24 22:24:29 +0000888 const char *error_string = error.AsCString();
889 if (error_string == NULL)
890 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000891
Greg Claytona2f74232011-02-24 22:24:29 +0000892 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000893 }
Greg Claytona2f74232011-02-24 22:24:29 +0000894 else
895 {
896 error = ConnectToDebugserver (connect_url);
897 }
898 }
899
900 if (error.Success())
901 {
902 StreamString packet;
903
904 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +0000905 {
906 if (!m_gdb_comm.GetVAttachOrWaitSupported())
907 {
908 packet.PutCString ("vAttachWait");
909 }
910 else
911 {
912 if (attach_info.GetIgnoreExisting())
913 packet.PutCString("vAttachWait");
914 else
915 packet.PutCString ("vAttachOrWait");
916 }
917 }
Greg Claytona2f74232011-02-24 22:24:29 +0000918 else
919 packet.PutCString("vAttachName");
920 packet.PutChar(';');
921 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
922
923 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
924
Chris Lattner24943d22010-06-08 16:52:24 +0000925 }
926 }
Chris Lattner24943d22010-06-08 16:52:24 +0000927 return error;
928}
929
Chris Lattner24943d22010-06-08 16:52:24 +0000930
931void
932ProcessGDBRemote::DidAttach ()
933{
Greg Claytone71e2582011-02-04 01:58:07 +0000934 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000935}
936
937Error
938ProcessGDBRemote::WillResume ()
939{
Greg Claytonc1f45872011-02-12 06:28:37 +0000940 m_continue_c_tids.clear();
941 m_continue_C_tids.clear();
942 m_continue_s_tids.clear();
943 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000944 return Error();
945}
946
947Error
948ProcessGDBRemote::DoResume ()
949{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000950 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000951 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
952 if (log)
953 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000954
955 Listener listener ("gdb-remote.resume-packet-sent");
956 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
957 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000958 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
959
Greg Claytonc1f45872011-02-12 06:28:37 +0000960 StreamString continue_packet;
961 bool continue_packet_error = false;
962 if (m_gdb_comm.HasAnyVContSupport ())
963 {
964 continue_packet.PutCString ("vCont");
965
966 if (!m_continue_c_tids.empty())
967 {
968 if (m_gdb_comm.GetVContSupported ('c'))
969 {
970 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)
Greg Claytond9919d32011-12-01 23:28:38 +0000971 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000972 }
973 else
974 continue_packet_error = true;
975 }
976
977 if (!continue_packet_error && !m_continue_C_tids.empty())
978 {
979 if (m_gdb_comm.GetVContSupported ('C'))
980 {
981 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)
Greg Claytond9919d32011-12-01 23:28:38 +0000982 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000983 }
984 else
985 continue_packet_error = true;
986 }
Greg Claytonb749a262010-12-03 06:02:24 +0000987
Greg Claytonc1f45872011-02-12 06:28:37 +0000988 if (!continue_packet_error && !m_continue_s_tids.empty())
989 {
990 if (m_gdb_comm.GetVContSupported ('s'))
991 {
992 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)
Greg Claytond9919d32011-12-01 23:28:38 +0000993 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000994 }
995 else
996 continue_packet_error = true;
997 }
998
999 if (!continue_packet_error && !m_continue_S_tids.empty())
1000 {
1001 if (m_gdb_comm.GetVContSupported ('S'))
1002 {
1003 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)
Greg Claytond9919d32011-12-01 23:28:38 +00001004 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001005 }
1006 else
1007 continue_packet_error = true;
1008 }
1009
1010 if (continue_packet_error)
1011 continue_packet.GetString().clear();
1012 }
1013 else
1014 continue_packet_error = true;
1015
1016 if (continue_packet_error)
1017 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001018 // Either no vCont support, or we tried to use part of the vCont
1019 // packet that wasn't supported by the remote GDB server.
1020 // We need to try and make a simple packet that can do our continue
1021 const size_t num_threads = GetThreadList().GetSize();
1022 const size_t num_continue_c_tids = m_continue_c_tids.size();
1023 const size_t num_continue_C_tids = m_continue_C_tids.size();
1024 const size_t num_continue_s_tids = m_continue_s_tids.size();
1025 const size_t num_continue_S_tids = m_continue_S_tids.size();
1026 if (num_continue_c_tids > 0)
1027 {
1028 if (num_continue_c_tids == num_threads)
1029 {
1030 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001031 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001032 continue_packet.PutChar ('c');
1033 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001034 }
1035 else if (num_continue_c_tids == 1 &&
1036 num_continue_C_tids == 0 &&
1037 num_continue_s_tids == 0 &&
1038 num_continue_S_tids == 0 )
1039 {
1040 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001041 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001042 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001043 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001044 }
1045 }
1046
Greg Claytonde1dd812011-06-24 03:21:43 +00001047 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001048 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001049 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1050 num_continue_C_tids > 0 &&
1051 num_continue_s_tids == 0 &&
1052 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001053 {
1054 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001055 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001056 if (num_continue_C_tids > 1)
1057 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001058 // More that one thread with a signal, yet we don't have
1059 // vCont support and we are being asked to resume each
1060 // thread with a signal, we need to make sure they are
1061 // all the same signal, or we can't issue the continue
1062 // accurately with the current support...
1063 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001064 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001065 continue_packet_error = false;
1066 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1067 {
1068 if (m_continue_C_tids[i].second != continue_signo)
1069 continue_packet_error = true;
1070 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001071 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001072 if (!continue_packet_error)
1073 m_gdb_comm.SetCurrentThreadForRun (-1);
1074 }
1075 else
1076 {
1077 // Set the continue thread ID
1078 continue_packet_error = false;
1079 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001080 }
1081 if (!continue_packet_error)
1082 {
1083 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001084 continue_packet.Printf("C%2.2x", continue_signo);
1085 }
1086 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001087 }
1088
Greg Claytonde1dd812011-06-24 03:21:43 +00001089 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001090 {
1091 if (num_continue_s_tids == num_threads)
1092 {
1093 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001094 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001095 continue_packet.PutChar ('s');
1096 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001097 }
1098 else if (num_continue_c_tids == 0 &&
1099 num_continue_C_tids == 0 &&
1100 num_continue_s_tids == 1 &&
1101 num_continue_S_tids == 0 )
1102 {
1103 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001104 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001105 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001106 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001107 }
1108 }
1109
1110 if (!continue_packet_error && num_continue_S_tids > 0)
1111 {
1112 if (num_continue_S_tids == num_threads)
1113 {
1114 const int step_signo = m_continue_S_tids.front().second;
1115 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001116 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001117 if (num_continue_S_tids > 1)
1118 {
1119 for (size_t i=1; i<num_threads; ++i)
1120 {
1121 if (m_continue_S_tids[i].second != step_signo)
1122 continue_packet_error = true;
1123 }
1124 }
1125 if (!continue_packet_error)
1126 {
1127 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001128 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001129 continue_packet.Printf("S%2.2x", step_signo);
1130 }
1131 }
1132 else if (num_continue_c_tids == 0 &&
1133 num_continue_C_tids == 0 &&
1134 num_continue_s_tids == 0 &&
1135 num_continue_S_tids == 1 )
1136 {
1137 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001138 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001139 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001140 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001141 }
1142 }
1143 }
1144
1145 if (continue_packet_error)
1146 {
1147 error.SetErrorString ("can't make continue packet for this resume");
1148 }
1149 else
1150 {
1151 EventSP event_sp;
1152 TimeValue timeout;
1153 timeout = TimeValue::Now();
1154 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001155 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1156 {
1157 error.SetErrorString ("Trying to resume but the async thread is dead.");
1158 if (log)
1159 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1160 return error;
1161 }
1162
Greg Claytonc1f45872011-02-12 06:28:37 +00001163 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1164
1165 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001166 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001167 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001168 if (log)
1169 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1170 }
1171 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1172 {
1173 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1174 if (log)
1175 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1176 return error;
1177 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001178 }
Greg Claytonb749a262010-12-03 06:02:24 +00001179 }
1180
Jim Ingham3ae449a2010-11-17 02:32:00 +00001181 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001182}
1183
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001184void
1185ProcessGDBRemote::ClearThreadIDList ()
1186{
Greg Claytonff3448e2012-04-13 02:11:32 +00001187 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001188 m_thread_ids.clear();
1189}
1190
1191bool
1192ProcessGDBRemote::UpdateThreadIDList ()
1193{
Greg Claytonff3448e2012-04-13 02:11:32 +00001194 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001195 bool sequence_mutex_unavailable = false;
1196 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1197 if (sequence_mutex_unavailable)
1198 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001199 return false; // We just didn't get the list
1200 }
1201 return true;
1202}
1203
Greg Claytonae932352012-04-10 00:18:59 +00001204bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001205ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001206{
1207 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001208 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001209 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001210 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001211
1212 size_t num_thread_ids = m_thread_ids.size();
1213 // The "m_thread_ids" thread ID list should always be updated after each stop
1214 // reply packet, but in case it isn't, update it here.
1215 if (num_thread_ids == 0)
1216 {
1217 if (!UpdateThreadIDList ())
1218 return false;
1219 num_thread_ids = m_thread_ids.size();
1220 }
Chris Lattner24943d22010-06-08 16:52:24 +00001221
Greg Clayton37f962e2011-08-22 02:49:39 +00001222 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001223 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001224 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001225 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001226 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001227 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1228 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001229 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001230 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001231 }
Chris Lattner24943d22010-06-08 16:52:24 +00001232 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001233
Greg Claytonae932352012-04-10 00:18:59 +00001234 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001235}
1236
1237
1238StateType
1239ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1240{
Greg Clayton261a18b2011-06-02 22:22:38 +00001241 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001242 const char stop_type = stop_packet.GetChar();
1243 switch (stop_type)
1244 {
1245 case 'T':
1246 case 'S':
1247 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001248 if (GetStopID() == 0)
1249 {
1250 // Our first stop, make sure we have a process ID, and also make
1251 // sure we know about our registers
1252 if (GetID() == LLDB_INVALID_PROCESS_ID)
1253 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001254 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001255 if (pid != LLDB_INVALID_PROCESS_ID)
1256 SetID (pid);
1257 }
1258 BuildDynamicRegisterInfo (true);
1259 }
Chris Lattner24943d22010-06-08 16:52:24 +00001260 // Stop with signal and thread info
1261 const uint8_t signo = stop_packet.GetHexU8();
1262 std::string name;
1263 std::string value;
1264 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001265 std::string reason;
1266 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001267 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001268 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001269 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001270 ThreadSP thread_sp;
1271
Chris Lattner24943d22010-06-08 16:52:24 +00001272 while (stop_packet.GetNameColonValue(name, value))
1273 {
1274 if (name.compare("metype") == 0)
1275 {
1276 // exception type in big endian hex
1277 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1278 }
Chris Lattner24943d22010-06-08 16:52:24 +00001279 else if (name.compare("medata") == 0)
1280 {
1281 // exception data in big endian hex
1282 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1283 }
1284 else if (name.compare("thread") == 0)
1285 {
1286 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001287 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001288 // m_thread_list does have its own mutex, but we need to
1289 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1290 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001291 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001292 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001293 if (!thread_sp)
1294 {
1295 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001296 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001297 m_thread_list.AddThread(thread_sp);
1298 }
Chris Lattner24943d22010-06-08 16:52:24 +00001299 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001300 else if (name.compare("threads") == 0)
1301 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001302 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001303 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001304 // A comma separated list of all threads in the current
1305 // process that includes the thread for this stop reply
1306 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001307 size_t comma_pos;
1308 lldb::tid_t tid;
1309 while ((comma_pos = value.find(',')) != std::string::npos)
1310 {
1311 value[comma_pos] = '\0';
1312 // thread in big endian hex
1313 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1314 if (tid != LLDB_INVALID_THREAD_ID)
1315 m_thread_ids.push_back (tid);
1316 value.erase(0, comma_pos + 1);
1317
1318 }
1319 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1320 if (tid != LLDB_INVALID_THREAD_ID)
1321 m_thread_ids.push_back (tid);
1322 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001323 else if (name.compare("hexname") == 0)
1324 {
1325 StringExtractor name_extractor;
1326 // Swap "value" over into "name_extractor"
1327 name_extractor.GetStringRef().swap(value);
1328 // Now convert the HEX bytes into a string value
1329 name_extractor.GetHexByteString (value);
1330 thread_name.swap (value);
1331 }
Chris Lattner24943d22010-06-08 16:52:24 +00001332 else if (name.compare("name") == 0)
1333 {
1334 thread_name.swap (value);
1335 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001336 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001337 {
1338 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1339 }
Greg Clayton65611552011-06-04 01:26:29 +00001340 else if (name.compare("reason") == 0)
1341 {
1342 reason.swap(value);
1343 }
1344 else if (name.compare("description") == 0)
1345 {
1346 StringExtractor desc_extractor;
1347 // Swap "value" over into "name_extractor"
1348 desc_extractor.GetStringRef().swap(value);
1349 // Now convert the HEX bytes into a string value
1350 desc_extractor.GetHexByteString (thread_name);
1351 }
Greg Claytona875b642011-01-09 21:07:35 +00001352 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1353 {
1354 // We have a register number that contains an expedited
1355 // register value. Lets supply this register to our thread
1356 // so it won't have to go and read it.
1357 if (thread_sp)
1358 {
1359 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1360
1361 if (reg != UINT32_MAX)
1362 {
1363 StringExtractor reg_value_extractor;
1364 // Swap "value" over into "reg_value_extractor"
1365 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001366 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1367 {
1368 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1369 name.c_str(),
1370 reg,
1371 reg,
1372 reg_value_extractor.GetStringRef().c_str(),
1373 stop_packet.GetStringRef().c_str());
1374 }
Greg Claytona875b642011-01-09 21:07:35 +00001375 }
1376 }
1377 }
Chris Lattner24943d22010-06-08 16:52:24 +00001378 }
Chris Lattner24943d22010-06-08 16:52:24 +00001379
1380 if (thread_sp)
1381 {
1382 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1383
1384 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001385 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001386 if (exc_type != 0)
1387 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001388 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001389
1390 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1391 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001392 exc_data_size,
1393 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001394 exc_data_size >= 2 ? exc_data[1] : 0,
1395 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001396 }
Greg Clayton65611552011-06-04 01:26:29 +00001397 else
Chris Lattner24943d22010-06-08 16:52:24 +00001398 {
Greg Clayton65611552011-06-04 01:26:29 +00001399 bool handled = false;
1400 if (!reason.empty())
1401 {
1402 if (reason.compare("trace") == 0)
1403 {
1404 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1405 handled = true;
1406 }
1407 else if (reason.compare("breakpoint") == 0)
1408 {
1409 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001410 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001411 if (bp_site_sp)
1412 {
1413 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1414 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1415 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001416 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001417 if (bp_site_sp->ValidForThisThread (gdb_thread))
1418 {
1419 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001420 }
1421 else
1422 {
1423 StopInfoSP invalid_stop_info_sp;
1424 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001425 }
1426 }
1427
Greg Clayton65611552011-06-04 01:26:29 +00001428 }
1429 else if (reason.compare("trap") == 0)
1430 {
1431 // Let the trap just use the standard signal stop reason below...
1432 }
1433 else if (reason.compare("watchpoint") == 0)
1434 {
1435 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1436 // TODO: locate the watchpoint somehow...
1437 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1438 handled = true;
1439 }
1440 else if (reason.compare("exception") == 0)
1441 {
1442 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1443 handled = true;
1444 }
1445 }
1446
1447 if (signo)
1448 {
1449 if (signo == SIGTRAP)
1450 {
1451 // Currently we are going to assume SIGTRAP means we are either
1452 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001453 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001454 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001455 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001456
Greg Clayton65611552011-06-04 01:26:29 +00001457 if (bp_site_sp)
1458 {
1459 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1460 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1461 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1462 if (bp_site_sp->ValidForThisThread (gdb_thread))
1463 {
1464 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001465 }
1466 else
1467 {
1468 StopInfoSP invalid_stop_info_sp;
1469 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001470 }
1471 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001472 else
Greg Clayton65611552011-06-04 01:26:29 +00001473 {
1474 // TODO: check for breakpoint or trap opcode in case there is a hard
1475 // coded software trap
1476 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton65611552011-06-04 01:26:29 +00001477 }
1478 }
1479 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001480 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001481 }
1482 else
1483 {
Greg Clayton643ee732010-08-04 01:40:35 +00001484 StopInfoSP invalid_stop_info_sp;
1485 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001486 }
Greg Clayton65611552011-06-04 01:26:29 +00001487
1488 if (!description.empty())
1489 {
1490 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1491 if (stop_info_sp)
1492 {
1493 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001494 }
Greg Clayton65611552011-06-04 01:26:29 +00001495 else
1496 {
1497 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1498 }
1499 }
1500 }
Chris Lattner24943d22010-06-08 16:52:24 +00001501 }
1502 return eStateStopped;
1503 }
1504 break;
1505
1506 case 'W':
1507 // process exited
1508 return eStateExited;
1509
1510 default:
1511 break;
1512 }
1513 return eStateInvalid;
1514}
1515
1516void
1517ProcessGDBRemote::RefreshStateAfterStop ()
1518{
Greg Claytonff3448e2012-04-13 02:11:32 +00001519 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001520 m_thread_ids.clear();
1521 // Set the thread stop info. It might have a "threads" key whose value is
1522 // a list of all thread IDs in the current process, so m_thread_ids might
1523 // get set.
1524 SetThreadStopInfo (m_last_stop_packet);
1525 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1526 if (m_thread_ids.empty())
1527 {
1528 // No, we need to fetch the thread list manually
1529 UpdateThreadIDList();
1530 }
1531
Chris Lattner24943d22010-06-08 16:52:24 +00001532 // Let all threads recover from stopping and do any clean up based
1533 // on the previous thread state (if any).
1534 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001535
Chris Lattner24943d22010-06-08 16:52:24 +00001536}
1537
1538Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001539ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001540{
1541 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001542
Greg Claytona4881d02011-01-22 07:12:45 +00001543 bool timed_out = false;
1544 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001545
1546 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001547 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001548 // We are being asked to halt during an attach. We need to just close
1549 // our file handle and debugserver will go away, and we can be done...
1550 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001551 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001552 else
1553 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001554 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001555 {
1556 if (timed_out)
1557 error.SetErrorString("timed out sending interrupt packet");
1558 else
1559 error.SetErrorString("unknown error sending interrupt packet");
1560 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001561
1562 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001563 }
Chris Lattner24943d22010-06-08 16:52:24 +00001564 return error;
1565}
1566
1567Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001568ProcessGDBRemote::InterruptIfRunning
1569(
1570 bool discard_thread_plans,
1571 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001572 EventSP &stop_event_sp
1573)
Chris Lattner24943d22010-06-08 16:52:24 +00001574{
1575 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001576
Greg Clayton2860ba92011-01-23 19:58:49 +00001577 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1578
Greg Clayton68ca8232011-01-25 02:58:48 +00001579 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001580 const bool is_running = m_gdb_comm.IsRunning();
1581 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001582 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001583 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001584 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001585 is_running);
1586
Greg Clayton2860ba92011-01-23 19:58:49 +00001587 if (discard_thread_plans)
1588 {
1589 if (log)
1590 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1591 m_thread_list.DiscardThreadPlans();
1592 }
1593 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001594 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001595 if (catch_stop_event)
1596 {
1597 if (log)
1598 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1599 PausePrivateStateThread();
1600 paused_private_state_thread = true;
1601 }
1602
Greg Clayton4fb400f2010-09-27 21:07:38 +00001603 bool timed_out = false;
1604 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001605
Greg Clayton05e4d972012-03-29 01:55:41 +00001606 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001607 {
1608 if (timed_out)
1609 error.SetErrorString("timed out sending interrupt packet");
1610 else
1611 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001612 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001613 ResumePrivateStateThread();
1614 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001615 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001616
Greg Clayton72e1c782011-01-22 23:43:18 +00001617 if (catch_stop_event)
1618 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001619 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001620 TimeValue timeout_time;
1621 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001622 timeout_time.OffsetWithSeconds(5);
1623 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001624
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001625 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001626 if (log)
1627 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001628
Greg Clayton2860ba92011-01-23 19:58:49 +00001629 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001630 error.SetErrorString("unable to verify target stopped");
1631 }
1632
Greg Clayton68ca8232011-01-25 02:58:48 +00001633 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001634 {
1635 if (log)
1636 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001637 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001638 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001639 }
Chris Lattner24943d22010-06-08 16:52:24 +00001640 return error;
1641}
1642
Greg Clayton4fb400f2010-09-27 21:07:38 +00001643Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001644ProcessGDBRemote::WillDetach ()
1645{
Greg Clayton2860ba92011-01-23 19:58:49 +00001646 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1647 if (log)
1648 log->Printf ("ProcessGDBRemote::WillDetach()");
1649
Greg Clayton72e1c782011-01-22 23:43:18 +00001650 bool discard_thread_plans = true;
1651 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001652 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001653
1654 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1655 // needed. This shouldn't be a feature of a particular plugin.
1656
Greg Clayton68ca8232011-01-25 02:58:48 +00001657 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001658}
1659
1660Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001661ProcessGDBRemote::DoDetach()
1662{
1663 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001664 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001665 if (log)
1666 log->Printf ("ProcessGDBRemote::DoDetach()");
1667
1668 DisableAllBreakpointSites ();
1669
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001670 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001671
Greg Clayton516f0842012-04-11 00:24:49 +00001672 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001673 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001674 {
Greg Clayton516f0842012-04-11 00:24:49 +00001675 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001676 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1677 else
1678 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001679 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001680 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001681 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001682
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001683 SetPrivateState (eStateDetached);
1684 ResumePrivateStateThread();
1685
1686 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001687 return error;
1688}
Chris Lattner24943d22010-06-08 16:52:24 +00001689
Jim Ingham06b84492012-07-04 00:35:43 +00001690
Chris Lattner24943d22010-06-08 16:52:24 +00001691Error
1692ProcessGDBRemote::DoDestroy ()
1693{
1694 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001695 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001696 if (log)
1697 log->Printf ("ProcessGDBRemote::DoDestroy()");
1698
Jim Ingham06b84492012-07-04 00:35:43 +00001699 // There is a bug in older iOS debugservers where they don't shut down the process
1700 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1701 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1702 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1703 // destroy it again.
1704 //
1705 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1706 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1707 // the debugservers with this bug are equal. There really should be a better way to test this!
1708 //
1709 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1710 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1711 // just do the straight-forward kill.
1712 //
1713 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1714 // necessary (or helpful) to do any of this.
1715
1716 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1717 {
1718 PlatformSP platform_sp = GetTarget().GetPlatform();
1719
1720 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1721 if (platform_sp
1722 && platform_sp->GetName()
1723 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1724 {
1725 if (m_destroy_tried_resuming)
1726 {
1727 if (log)
1728 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1729 }
1730 else
1731 {
1732 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1733 // but we really need it to happen here and it doesn't matter if we do it twice.
1734 m_thread_list.DiscardThreadPlans();
1735 DisableAllBreakpointSites();
1736
1737 bool stop_looks_like_crash = false;
1738 ThreadList &threads = GetThreadList();
1739
1740 {
1741 Mutex::Locker(threads.GetMutex());
1742
1743 size_t num_threads = threads.GetSize();
1744 for (size_t i = 0; i < num_threads; i++)
1745 {
1746 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1747 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1748 StopReason reason = eStopReasonInvalid;
1749 if (stop_info_sp)
1750 reason = stop_info_sp->GetStopReason();
1751 if (reason == eStopReasonBreakpoint
1752 || reason == eStopReasonException)
1753 {
1754 if (log)
1755 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1756 thread_sp->GetID(),
1757 stop_info_sp->GetDescription());
1758 stop_looks_like_crash = true;
1759 break;
1760 }
1761 }
1762 }
1763
1764 if (stop_looks_like_crash)
1765 {
1766 if (log)
1767 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1768 m_destroy_tried_resuming = true;
1769
1770 // If we are going to run again before killing, it would be good to suspend all the threads
1771 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1772 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1773 // have to run the risk of letting those threads proceed a bit.
1774
1775 {
1776 Mutex::Locker(threads.GetMutex());
1777
1778 size_t num_threads = threads.GetSize();
1779 for (size_t i = 0; i < num_threads; i++)
1780 {
1781 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1782 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1783 StopReason reason = eStopReasonInvalid;
1784 if (stop_info_sp)
1785 reason = stop_info_sp->GetStopReason();
1786 if (reason != eStopReasonBreakpoint
1787 && reason != eStopReasonException)
1788 {
1789 if (log)
1790 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1791 thread_sp->GetID());
1792 thread_sp->SetResumeState(eStateSuspended);
1793 }
1794 }
1795 }
1796 Resume ();
1797 return Destroy();
1798 }
1799 }
1800 }
1801 }
1802
Chris Lattner24943d22010-06-08 16:52:24 +00001803 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001804 int exit_status = SIGABRT;
1805 std::string exit_string;
1806
Greg Claytona4881d02011-01-22 07:12:45 +00001807 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001808 {
Jim Ingham8226e942011-10-28 01:11:35 +00001809 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001810 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001811
1812 StringExtractorGDBRemote response;
1813 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001814 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1815
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001816 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001817 {
1818 char packet_cmd = response.GetChar(0);
1819
1820 if (packet_cmd == 'W' || packet_cmd == 'X')
1821 {
Greg Clayton06709002011-12-06 04:51:14 +00001822 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001823 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001824 exit_status = response.GetHexU8();
1825 }
1826 else
1827 {
1828 if (log)
1829 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1830 exit_string.assign("got unexpected response to k packet: ");
1831 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001832 }
1833 }
1834 else
1835 {
Jim Ingham8247e622012-06-06 00:32:39 +00001836 if (log)
1837 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1838 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001839 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001840
1841 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00001842 }
Jim Ingham8247e622012-06-06 00:32:39 +00001843 else
1844 {
1845 if (log)
1846 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00001847 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00001848 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001849 }
Jim Ingham8247e622012-06-06 00:32:39 +00001850 else
1851 {
1852 // If we missed setting the exit status on the way out, do it here.
1853 // NB set exit status can be called multiple times, the first one sets the status.
1854 exit_string.assign("destroying when not connected to debugserver");
1855 }
1856
1857 SetExitStatus(exit_status, exit_string.c_str());
1858
Chris Lattner24943d22010-06-08 16:52:24 +00001859 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001860 KillDebugserverProcess ();
1861 return error;
1862}
1863
Chris Lattner24943d22010-06-08 16:52:24 +00001864//------------------------------------------------------------------
1865// Process Queries
1866//------------------------------------------------------------------
1867
1868bool
1869ProcessGDBRemote::IsAlive ()
1870{
Greg Clayton58e844b2010-12-08 05:08:21 +00001871 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001872}
1873
1874addr_t
1875ProcessGDBRemote::GetImageInfoAddress()
1876{
Greg Clayton516f0842012-04-11 00:24:49 +00001877 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001878}
1879
Chris Lattner24943d22010-06-08 16:52:24 +00001880//------------------------------------------------------------------
1881// Process Memory
1882//------------------------------------------------------------------
1883size_t
1884ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1885{
1886 if (size > m_max_memory_size)
1887 {
1888 // Keep memory read sizes down to a sane limit. This function will be
1889 // called multiple times in order to complete the task by
1890 // lldb_private::Process so it is ok to do this.
1891 size = m_max_memory_size;
1892 }
1893
1894 char packet[64];
1895 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1896 assert (packet_len + 1 < sizeof(packet));
1897 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001898 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001899 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001900 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001901 {
1902 error.Clear();
1903 return response.GetHexBytes(buf, size, '\xdd');
1904 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001905 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001906 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001907 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001908 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1909 else
1910 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1911 }
1912 else
1913 {
1914 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1915 }
1916 return 0;
1917}
1918
1919size_t
1920ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1921{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001922 if (size > m_max_memory_size)
1923 {
1924 // Keep memory read sizes down to a sane limit. This function will be
1925 // called multiple times in order to complete the task by
1926 // lldb_private::Process so it is ok to do this.
1927 size = m_max_memory_size;
1928 }
1929
Chris Lattner24943d22010-06-08 16:52:24 +00001930 StreamString packet;
1931 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001932 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001933 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001934 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001935 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001936 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001937 {
1938 error.Clear();
1939 return size;
1940 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001941 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001942 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001943 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001944 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1945 else
1946 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1947 }
1948 else
1949 {
1950 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1951 }
1952 return 0;
1953}
1954
1955lldb::addr_t
1956ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1957{
Greg Clayton989816b2011-05-14 01:50:35 +00001958 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1959
Greg Clayton2f085c62011-05-15 01:25:55 +00001960 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001961 switch (supported)
1962 {
1963 case eLazyBoolCalculate:
1964 case eLazyBoolYes:
1965 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1966 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1967 return allocated_addr;
1968
1969 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001970 // Call mmap() to create memory in the inferior..
1971 unsigned prot = 0;
1972 if (permissions & lldb::ePermissionsReadable)
1973 prot |= eMmapProtRead;
1974 if (permissions & lldb::ePermissionsWritable)
1975 prot |= eMmapProtWrite;
1976 if (permissions & lldb::ePermissionsExecutable)
1977 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001978
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001979 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1980 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1981 m_addr_to_mmap_size[allocated_addr] = size;
1982 else
1983 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001984 break;
1985 }
1986
Chris Lattner24943d22010-06-08 16:52:24 +00001987 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001988 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001989 else
1990 error.Clear();
1991 return allocated_addr;
1992}
1993
1994Error
Greg Claytona9385532011-11-18 07:03:08 +00001995ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1996 MemoryRegionInfo &region_info)
1997{
1998
1999 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2000 return error;
2001}
2002
2003Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002004ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2005{
2006
2007 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2008 return error;
2009}
2010
2011Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002012ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2013{
2014 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2015 return error;
2016}
2017
2018Error
Chris Lattner24943d22010-06-08 16:52:24 +00002019ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2020{
2021 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002022 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2023
2024 switch (supported)
2025 {
2026 case eLazyBoolCalculate:
2027 // We should never be deallocating memory without allocating memory
2028 // first so we should never get eLazyBoolCalculate
2029 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2030 break;
2031
2032 case eLazyBoolYes:
2033 if (!m_gdb_comm.DeallocateMemory (addr))
2034 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2035 break;
2036
2037 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002038 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002039 {
2040 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002041 if (pos != m_addr_to_mmap_size.end() &&
2042 InferiorCallMunmap(this, addr, pos->second))
2043 m_addr_to_mmap_size.erase (pos);
2044 else
2045 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002046 }
2047 break;
2048 }
2049
Chris Lattner24943d22010-06-08 16:52:24 +00002050 return error;
2051}
2052
2053
2054//------------------------------------------------------------------
2055// Process STDIO
2056//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002057size_t
2058ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2059{
2060 if (m_stdio_communication.IsConnected())
2061 {
2062 ConnectionStatus status;
2063 m_stdio_communication.Write(src, src_len, status, NULL);
2064 }
2065 return 0;
2066}
2067
2068Error
2069ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2070{
2071 Error error;
2072 assert (bp_site != NULL);
2073
Greg Claytone005f2c2010-11-06 01:53:30 +00002074 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002075 user_id_t site_id = bp_site->GetID();
2076 const addr_t addr = bp_site->GetLoadAddress();
2077 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002078 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002079
2080 if (bp_site->IsEnabled())
2081 {
2082 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002083 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002084 return error;
2085 }
2086 else
2087 {
2088 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2089
2090 if (bp_site->HardwarePreferred())
2091 {
2092 // Try and set hardware breakpoint, and if that fails, fall through
2093 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002094 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002095 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002096 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002097 {
2098 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002099 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002100 return error;
2101 }
Chris Lattner24943d22010-06-08 16:52:24 +00002102 }
2103 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002104
2105 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002106 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002107 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2108 {
2109 bp_site->SetEnabled(true);
2110 bp_site->SetType (BreakpointSite::eExternal);
2111 return error;
2112 }
Chris Lattner24943d22010-06-08 16:52:24 +00002113 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002114
2115 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002116 }
2117
2118 if (log)
2119 {
2120 const char *err_string = error.AsCString();
2121 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2122 bp_site->GetLoadAddress(),
2123 err_string ? err_string : "NULL");
2124 }
2125 // We shouldn't reach here on a successful breakpoint enable...
2126 if (error.Success())
2127 error.SetErrorToGenericError();
2128 return error;
2129}
2130
2131Error
2132ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2133{
2134 Error error;
2135 assert (bp_site != NULL);
2136 addr_t addr = bp_site->GetLoadAddress();
2137 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002138 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002139 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002140 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002141
2142 if (bp_site->IsEnabled())
2143 {
2144 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2145
Greg Claytonb72d0f02011-04-12 05:54:46 +00002146 BreakpointSite::Type bp_type = bp_site->GetType();
2147 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002148 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002149 case BreakpointSite::eSoftware:
2150 error = DisableSoftwareBreakpoint (bp_site);
2151 break;
2152
2153 case BreakpointSite::eHardware:
2154 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2155 error.SetErrorToGenericError();
2156 break;
2157
2158 case BreakpointSite::eExternal:
2159 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2160 error.SetErrorToGenericError();
2161 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002162 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002163 if (error.Success())
2164 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002165 }
2166 else
2167 {
2168 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002169 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002170 return error;
2171 }
2172
2173 if (error.Success())
2174 error.SetErrorToGenericError();
2175 return error;
2176}
2177
Johnny Chen21900fb2011-09-06 22:38:36 +00002178// Pre-requisite: wp != NULL.
2179static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002180GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002181{
2182 assert(wp);
2183 bool watch_read = wp->WatchpointRead();
2184 bool watch_write = wp->WatchpointWrite();
2185
2186 // watch_read and watch_write cannot both be false.
2187 assert(watch_read || watch_write);
2188 if (watch_read && watch_write)
2189 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002190 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002191 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002192 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002193 return eWatchpointWrite;
2194}
2195
Chris Lattner24943d22010-06-08 16:52:24 +00002196Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002197ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002198{
2199 Error error;
2200 if (wp)
2201 {
2202 user_id_t watchID = wp->GetID();
2203 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002204 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002205 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002206 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002207 if (wp->IsEnabled())
2208 {
2209 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002210 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002211 return error;
2212 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002213
2214 GDBStoppointType type = GetGDBStoppointType(wp);
2215 // Pass down an appropriate z/Z packet...
2216 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002217 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002218 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2219 {
2220 wp->SetEnabled(true);
2221 return error;
2222 }
2223 else
2224 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002225 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002226 else
2227 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002228 }
2229 else
2230 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002231 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002232 }
2233 if (error.Success())
2234 error.SetErrorToGenericError();
2235 return error;
2236}
2237
2238Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002239ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002240{
2241 Error error;
2242 if (wp)
2243 {
2244 user_id_t watchID = wp->GetID();
2245
Greg Claytone005f2c2010-11-06 01:53:30 +00002246 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002247
2248 addr_t addr = wp->GetLoadAddress();
2249 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002250 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002251
Johnny Chen21900fb2011-09-06 22:38:36 +00002252 if (!wp->IsEnabled())
2253 {
2254 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002255 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002256 // See also 'class WatchpointSentry' within StopInfo.cpp.
2257 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2258 // the watchpoint object to intelligently process this action.
2259 wp->SetEnabled(false);
Johnny Chen21900fb2011-09-06 22:38:36 +00002260 return error;
2261 }
2262
Chris Lattner24943d22010-06-08 16:52:24 +00002263 if (wp->IsHardware())
2264 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002265 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002266 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002267 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2268 {
2269 wp->SetEnabled(false);
2270 return error;
2271 }
2272 else
2273 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002274 }
2275 // TODO: clear software watchpoints if we implement them
2276 }
2277 else
2278 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002279 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002280 }
2281 if (error.Success())
2282 error.SetErrorToGenericError();
2283 return error;
2284}
2285
2286void
2287ProcessGDBRemote::Clear()
2288{
2289 m_flags = 0;
2290 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002291}
2292
2293Error
2294ProcessGDBRemote::DoSignal (int signo)
2295{
2296 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002297 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002298 if (log)
2299 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2300
2301 if (!m_gdb_comm.SendAsyncSignal (signo))
2302 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2303 return error;
2304}
2305
Chris Lattner24943d22010-06-08 16:52:24 +00002306Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002307ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2308{
2309 ProcessLaunchInfo launch_info;
2310 return StartDebugserverProcess(debugserver_url, launch_info);
2311}
2312
2313Error
2314ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner24943d22010-06-08 16:52:24 +00002315{
2316 Error error;
2317 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2318 {
2319 // If we locate debugserver, keep that located version around
2320 static FileSpec g_debugserver_file_spec;
2321
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002322 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002323 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002324 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002325
2326 // Always check to see if we have an environment override for the path
2327 // to the debugserver to use and use it if we do.
2328 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2329 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002330 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002331 else
2332 debugserver_file_spec = g_debugserver_file_spec;
2333 bool debugserver_exists = debugserver_file_spec.Exists();
2334 if (!debugserver_exists)
2335 {
2336 // The debugserver binary is in the LLDB.framework/Resources
2337 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002338 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002339 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002340 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002341 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002342 if (debugserver_exists)
2343 {
2344 g_debugserver_file_spec = debugserver_file_spec;
2345 }
2346 else
2347 {
2348 g_debugserver_file_spec.Clear();
2349 debugserver_file_spec.Clear();
2350 }
Chris Lattner24943d22010-06-08 16:52:24 +00002351 }
2352 }
2353
2354 if (debugserver_exists)
2355 {
2356 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2357
2358 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002359
Greg Claytone005f2c2010-11-06 01:53:30 +00002360 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002361
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002362 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002363 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002364
Chris Lattner24943d22010-06-08 16:52:24 +00002365 // Start args with "debugserver /file/path -r --"
2366 debugserver_args.AppendArgument(debugserver_path);
2367 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002368 // use native registers, not the GDB registers
2369 debugserver_args.AppendArgument("--native-regs");
2370 // make debugserver run in its own session so signals generated by
2371 // special terminal key sequences (^C) don't affect debugserver
2372 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002373
Chris Lattner24943d22010-06-08 16:52:24 +00002374 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2375 if (env_debugserver_log_file)
2376 {
2377 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2378 debugserver_args.AppendArgument(arg_cstr);
2379 }
2380
2381 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2382 if (env_debugserver_log_flags)
2383 {
2384 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2385 debugserver_args.AppendArgument(arg_cstr);
2386 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00002387 debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2388 debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002389
Greg Claytonb72d0f02011-04-12 05:54:46 +00002390 // We currently send down all arguments, attach pids, or attach
2391 // process names in dedicated GDB server packets, so we don't need
2392 // to pass them as arguments. This is currently because of all the
2393 // things we need to setup prior to launching: the environment,
2394 // current working dir, file actions, etc.
2395#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002396 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002397 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002398 {
Greg Claytona2f74232011-02-24 22:24:29 +00002399 // Terminate the debugserver args so we can now append the inferior args
2400 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002401
Greg Claytona2f74232011-02-24 22:24:29 +00002402 for (int i = 0; inferior_argv[i] != NULL; ++i)
2403 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002404 }
2405 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2406 {
2407 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2408 debugserver_args.AppendArgument (arg_cstr);
2409 }
2410 else if (attach_name && attach_name[0])
2411 {
2412 if (wait_for_launch)
2413 debugserver_args.AppendArgument ("--waitfor");
2414 else
2415 debugserver_args.AppendArgument ("--attach");
2416 debugserver_args.AppendArgument (attach_name);
2417 }
Chris Lattner24943d22010-06-08 16:52:24 +00002418#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002419
2420 ProcessLaunchInfo::FileAction file_action;
2421
2422 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2423 // to "/dev/null" if we run into any problems.
2424 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002425 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002426 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002427 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002428 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002429 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002430
2431 if (log)
2432 {
2433 StreamString strm;
2434 debugserver_args.Dump (&strm);
2435 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2436 }
2437
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002438 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2439 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002440
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002441 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002442
Greg Claytonb72d0f02011-04-12 05:54:46 +00002443 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002444 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002445 else
Chris Lattner24943d22010-06-08 16:52:24 +00002446 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2447
2448 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002449 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002450 }
2451 else
2452 {
Greg Clayton9c236732011-10-26 00:56:27 +00002453 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002454 }
2455
2456 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2457 StartAsyncThread ();
2458 }
2459 return error;
2460}
2461
2462bool
2463ProcessGDBRemote::MonitorDebugserverProcess
2464(
2465 void *callback_baton,
2466 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002467 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002468 int signo, // Zero for no signal
2469 int exit_status // Exit value of process if signal is zero
2470)
2471{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002472 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2473 // and might not exist anymore, so we need to carefully try to get the
2474 // target for this process first since we have a race condition when
2475 // we are done running between getting the notice that the inferior
2476 // process has died and the debugserver that was debugging this process.
2477 // In our test suite, we are also continually running process after
2478 // process, so we must be very careful to make sure:
2479 // 1 - process object hasn't been deleted already
2480 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002481
2482 // "debugserver_pid" argument passed in is the process ID for
2483 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002484 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002485
Greg Clayton75ccf502010-08-21 02:22:51 +00002486 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002487
Greg Clayton1c4642c2011-11-16 05:37:56 +00002488 // Get a shared pointer to the target that has a matching process pointer.
2489 // This target could be gone, or the target could already have a new process
2490 // object inside of it
2491 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2492
Greg Clayton72e1c782011-01-22 23:43:18 +00002493 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002494 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%llu, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton72e1c782011-01-22 23:43:18 +00002495
Greg Clayton1c4642c2011-11-16 05:37:56 +00002496 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002497 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002498 // We found a process in a target that matches, but another thread
2499 // might be in the process of launching a new process that will
2500 // soon replace it, so get a shared pointer to the process so we
2501 // can keep it alive.
2502 ProcessSP process_sp (target_sp->GetProcessSP());
2503 // Now we have a shared pointer to the process that can't go away on us
2504 // so we now make sure it was the same as the one passed in, and also make
2505 // sure that our previous "process *" didn't get deleted and have a new
2506 // "process *" created in its place with the same pointer. To verify this
2507 // we make sure the process has our debugserver process ID. If we pass all
2508 // of these tests, then we are sure that this process is the one we were
2509 // looking for.
2510 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002511 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002512 // Sleep for a half a second to make sure our inferior process has
2513 // time to set its exit status before we set it incorrectly when
2514 // both the debugserver and the inferior process shut down.
2515 usleep (500000);
2516 // If our process hasn't yet exited, debugserver might have died.
2517 // If the process did exit, the we are reaping it.
2518 const StateType state = process->GetState();
2519
2520 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2521 state != eStateInvalid &&
2522 state != eStateUnloaded &&
2523 state != eStateExited &&
2524 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002525 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002526 char error_str[1024];
2527 if (signo)
2528 {
2529 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2530 if (signal_cstr)
2531 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2532 else
2533 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2534 }
Chris Lattner24943d22010-06-08 16:52:24 +00002535 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002536 {
2537 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2538 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002539
Greg Clayton1c4642c2011-11-16 05:37:56 +00002540 process->SetExitStatus (-1, error_str);
2541 }
2542 // Debugserver has exited we need to let our ProcessGDBRemote
2543 // know that it no longer has a debugserver instance
2544 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002545 }
Chris Lattner24943d22010-06-08 16:52:24 +00002546 }
2547 return true;
2548}
2549
2550void
2551ProcessGDBRemote::KillDebugserverProcess ()
2552{
2553 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2554 {
2555 ::kill (m_debugserver_pid, SIGINT);
2556 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2557 }
2558}
2559
2560void
2561ProcessGDBRemote::Initialize()
2562{
2563 static bool g_initialized = false;
2564
2565 if (g_initialized == false)
2566 {
2567 g_initialized = true;
2568 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2569 GetPluginDescriptionStatic(),
2570 CreateInstance);
2571
2572 Log::Callbacks log_callbacks = {
2573 ProcessGDBRemoteLog::DisableLog,
2574 ProcessGDBRemoteLog::EnableLog,
2575 ProcessGDBRemoteLog::ListLogCategories
2576 };
2577
2578 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2579 }
2580}
2581
2582bool
Chris Lattner24943d22010-06-08 16:52:24 +00002583ProcessGDBRemote::StartAsyncThread ()
2584{
Greg Claytone005f2c2010-11-06 01:53:30 +00002585 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002586
2587 if (log)
2588 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2589
2590 // Create a thread that watches our internal state and controls which
2591 // events make it to clients (into the DCProcess event queue).
2592 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002593 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002594}
2595
2596void
2597ProcessGDBRemote::StopAsyncThread ()
2598{
Greg Claytone005f2c2010-11-06 01:53:30 +00002599 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002600
2601 if (log)
2602 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2603
2604 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002605
2606 // This will shut down the async thread.
2607 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002608
2609 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002610 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002611 {
2612 Host::ThreadJoin (m_async_thread, NULL, NULL);
2613 }
2614}
2615
2616
2617void *
2618ProcessGDBRemote::AsyncThread (void *arg)
2619{
2620 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2621
Greg Claytone005f2c2010-11-06 01:53:30 +00002622 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002623 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002624 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002625
2626 Listener listener ("ProcessGDBRemote::AsyncThread");
2627 EventSP event_sp;
2628 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2629 eBroadcastBitAsyncThreadShouldExit;
2630
2631 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2632 {
Greg Claytona2f74232011-02-24 22:24:29 +00002633 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2634
Chris Lattner24943d22010-06-08 16:52:24 +00002635 bool done = false;
2636 while (!done)
2637 {
2638 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002639 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002640 if (listener.WaitForEvent (NULL, event_sp))
2641 {
2642 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002643 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002644 {
Greg Claytona2f74232011-02-24 22:24:29 +00002645 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002646 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002647
Greg Claytona2f74232011-02-24 22:24:29 +00002648 switch (event_type)
2649 {
2650 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002651 {
Greg Claytona2f74232011-02-24 22:24:29 +00002652 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002653
Greg Claytona2f74232011-02-24 22:24:29 +00002654 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002655 {
Greg Claytona2f74232011-02-24 22:24:29 +00002656 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2657 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2658 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002659 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002660
Greg Claytona2f74232011-02-24 22:24:29 +00002661 if (::strstr (continue_cstr, "vAttach") == NULL)
2662 process->SetPrivateState(eStateRunning);
2663 StringExtractorGDBRemote response;
2664 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002665
Greg Clayton67b402c2012-05-16 02:48:06 +00002666 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2667 // The thread ID list might be contained within the "response", or the stop reply packet that
2668 // caused the stop. So clear it now before we give the stop reply packet to the process
2669 // using the process->SetLastStopPacket()...
2670 process->ClearThreadIDList ();
2671
Greg Claytona2f74232011-02-24 22:24:29 +00002672 switch (stop_state)
2673 {
2674 case eStateStopped:
2675 case eStateCrashed:
2676 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002677 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002678 process->SetPrivateState (stop_state);
2679 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002680
Greg Claytona2f74232011-02-24 22:24:29 +00002681 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002682 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002683 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002684 response.SetFilePos(1);
2685 process->SetExitStatus(response.GetHexU8(), NULL);
2686 done = true;
2687 break;
2688
2689 case eStateInvalid:
2690 process->SetExitStatus(-1, "lost connection");
2691 break;
2692
2693 default:
2694 process->SetPrivateState (stop_state);
2695 break;
2696 }
Chris Lattner24943d22010-06-08 16:52:24 +00002697 }
2698 }
Greg Claytona2f74232011-02-24 22:24:29 +00002699 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002700
Greg Claytona2f74232011-02-24 22:24:29 +00002701 case eBroadcastBitAsyncThreadShouldExit:
2702 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002703 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002704 done = true;
2705 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002706
Greg Claytona2f74232011-02-24 22:24:29 +00002707 default:
2708 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002709 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Claytona2f74232011-02-24 22:24:29 +00002710 done = true;
2711 break;
2712 }
2713 }
2714 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2715 {
2716 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2717 {
2718 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002719 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002720 }
Chris Lattner24943d22010-06-08 16:52:24 +00002721 }
2722 }
2723 else
2724 {
2725 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002726 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002727 done = true;
2728 }
2729 }
2730 }
2731
2732 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002733 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002734
2735 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2736 return NULL;
2737}
2738
Chris Lattner24943d22010-06-08 16:52:24 +00002739const char *
2740ProcessGDBRemote::GetDispatchQueueNameForThread
2741(
2742 addr_t thread_dispatch_qaddr,
2743 std::string &dispatch_queue_name
2744)
2745{
2746 dispatch_queue_name.clear();
2747 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2748 {
2749 // Cache the dispatch_queue_offsets_addr value so we don't always have
2750 // to look it up
2751 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2752 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002753 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2754 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002755 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2756 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002757 if (module_sp)
2758 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2759
2760 if (dispatch_queue_offsets_symbol == NULL)
2761 {
Greg Clayton444fe992012-02-26 05:51:37 +00002762 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2763 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002764 if (module_sp)
2765 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2766 }
Chris Lattner24943d22010-06-08 16:52:24 +00002767 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002768 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002769
2770 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2771 return NULL;
2772 }
2773
2774 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002775 DataExtractor data (memory_buffer,
2776 sizeof(memory_buffer),
2777 m_target.GetArchitecture().GetByteOrder(),
2778 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002779
2780 // Excerpt from src/queue_private.h
2781 struct dispatch_queue_offsets_s
2782 {
2783 uint16_t dqo_version;
2784 uint16_t dqo_label;
2785 uint16_t dqo_label_size;
2786 } dispatch_queue_offsets;
2787
2788
2789 Error error;
2790 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2791 {
2792 uint32_t data_offset = 0;
2793 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2794 {
2795 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2796 {
2797 data_offset = 0;
2798 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2799 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2800 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2801 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2802 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2803 dispatch_queue_name.erase (bytes_read);
2804 }
2805 }
2806 }
2807 }
2808 if (dispatch_queue_name.empty())
2809 return NULL;
2810 return dispatch_queue_name.c_str();
2811}
2812
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002813//uint32_t
2814//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2815//{
2816// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2817// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2818// if (m_local_debugserver)
2819// {
2820// return Host::ListProcessesMatchingName (name, matches, pids);
2821// }
2822// else
2823// {
2824// // FIXME: Implement talking to the remote debugserver.
2825// return 0;
2826// }
2827//
2828//}
2829//
Jim Ingham55e01d82011-01-22 01:33:44 +00002830bool
2831ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2832 lldb_private::StoppointCallbackContext *context,
2833 lldb::user_id_t break_id,
2834 lldb::user_id_t break_loc_id)
2835{
2836 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2837 // run so I can stop it if that's what I want to do.
2838 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2839 if (log)
2840 log->Printf("Hit New Thread Notification breakpoint.");
2841 return false;
2842}
2843
2844
2845bool
2846ProcessGDBRemote::StartNoticingNewThreads()
2847{
Jim Ingham55e01d82011-01-22 01:33:44 +00002848 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002849 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002850 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002851 if (log && log->GetVerbose())
2852 log->Printf("Enabled noticing new thread breakpoint.");
2853 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002854 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002855 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002856 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002857 PlatformSP platform_sp (m_target.GetPlatform());
2858 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002859 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002860 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2861 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002862 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002863 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002864 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2865 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002866 }
2867 else
2868 {
2869 if (log)
2870 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002871 }
2872 }
2873 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002874 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002875}
2876
2877bool
2878ProcessGDBRemote::StopNoticingNewThreads()
2879{
Jim Inghamff276fe2011-02-08 05:19:01 +00002880 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002881 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002882 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002883
2884 if (m_thread_create_bp_sp)
2885 m_thread_create_bp_sp->SetEnabled(false);
2886
Jim Ingham55e01d82011-01-22 01:33:44 +00002887 return true;
2888}
2889
2890