blob: f29a1677874c800aa0a884572f29693def14d02f [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"
Greg Clayton49ce8962012-08-29 21:13:06 +000034#include "lldb/Core/ModuleSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/PluginManager.h"
36#include "lldb/Core/State.h"
Greg Clayton33559462012-04-13 21:24:18 +000037#include "lldb/Core/StreamFile.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Core/StreamString.h"
39#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000040#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041#include "lldb/Host/TimeValue.h"
42#include "lldb/Symbol/ObjectFile.h"
43#include "lldb/Target/DynamicLoader.h"
44#include "lldb/Target/Target.h"
45#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000046#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000047#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000048
49// Project includes
50#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000051#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molenda3aeb2862012-07-25 03:40:06 +000052#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham06b84492012-07-04 00:35:43 +000053#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000054#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000055#include "GDBRemoteRegisterContext.h"
56#include "ProcessGDBRemote.h"
57#include "ProcessGDBRemoteLog.h"
58#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000059
Greg Clayton451fa822012-04-09 22:46:21 +000060namespace lldb
61{
62 // Provide a function that can easily dump the packet history if we know a
63 // ProcessGDBRemote * value (which we can get from logs or from debugging).
64 // We need the function in the lldb namespace so it makes it into the final
65 // executable since the LLDB shared library only exports stuff in the lldb
66 // namespace. This allows you to attach with a debugger and call this
67 // function and get the packet history dumped to a file.
68 void
69 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
70 {
Greg Clayton33559462012-04-13 21:24:18 +000071 lldb_private::StreamFile strm;
72 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
73 if (error.Success())
74 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000075 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000076}
Chris Lattner24943d22010-06-08 16:52:24 +000077
Chris Lattner24943d22010-06-08 16:52:24 +000078
79#define DEBUGSERVER_BASENAME "debugserver"
80using namespace lldb;
81using namespace lldb_private;
82
Jim Inghamf9600482011-03-29 21:45:47 +000083static bool rand_initialized = false;
84
Sean Callanan483d00a2012-07-19 18:07:36 +000085// TODO Randomly assigning a port is unsafe. We should get an unused
86// ephemeral port from the kernel and make sure we reserve it before passing
87// it to debugserver.
88
89#if defined (__APPLE__)
90#define LOW_PORT (IPPORT_RESERVED)
91#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
92#else
93#define LOW_PORT (1024u)
94#define HIGH_PORT (49151u)
95#endif
96
Chris Lattner24943d22010-06-08 16:52:24 +000097static inline uint16_t
98get_random_port ()
99{
Jim Inghamf9600482011-03-29 21:45:47 +0000100 if (!rand_initialized)
101 {
Stephen Wilson60f19d52011-03-30 00:12:40 +0000102 time_t seed = time(NULL);
103
Jim Inghamf9600482011-03-29 21:45:47 +0000104 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +0000105 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +0000106 }
Sean Callanan483d00a2012-07-19 18:07:36 +0000107 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner24943d22010-06-08 16:52:24 +0000108}
109
110
111const char *
112ProcessGDBRemote::GetPluginNameStatic()
113{
Greg Claytonb1888f22011-03-19 01:12:21 +0000114 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000115}
116
117const char *
118ProcessGDBRemote::GetPluginDescriptionStatic()
119{
120 return "GDB Remote protocol based debugging plug-in.";
121}
122
123void
124ProcessGDBRemote::Terminate()
125{
126 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
127}
128
129
Greg Clayton46c9a352012-02-09 06:16:32 +0000130lldb::ProcessSP
131ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000132{
Greg Clayton46c9a352012-02-09 06:16:32 +0000133 lldb::ProcessSP process_sp;
134 if (crash_file_path == NULL)
135 process_sp.reset (new ProcessGDBRemote (target, listener));
136 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000137}
138
139bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000140ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000141{
Greg Clayton61ddf562011-10-21 21:41:45 +0000142 if (plugin_specified_by_name)
143 return true;
144
Chris Lattner24943d22010-06-08 16:52:24 +0000145 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000146 Module *exe_module = target.GetExecutableModulePointer();
147 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000148 {
149 ObjectFile *exe_objfile = exe_module->GetObjectFile();
150 // We can't debug core files...
151 switch (exe_objfile->GetType())
152 {
153 case ObjectFile::eTypeInvalid:
154 case ObjectFile::eTypeCoreFile:
155 case ObjectFile::eTypeDebugInfo:
156 case ObjectFile::eTypeObjectFile:
157 case ObjectFile::eTypeSharedLibrary:
158 case ObjectFile::eTypeStubLibrary:
159 return false;
160 case ObjectFile::eTypeExecutable:
161 case ObjectFile::eTypeDynamicLinker:
162 case ObjectFile::eTypeUnknown:
163 break;
164 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000165 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000166 }
Jim Ingham7508e732010-08-09 23:31:02 +0000167 // However, if there is no executable module, we return true since we might be preparing to attach.
168 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000169}
170
171//----------------------------------------------------------------------
172// ProcessGDBRemote constructor
173//----------------------------------------------------------------------
174ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
175 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000176 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000177 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000178 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000179 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000180 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000181 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000182 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000183 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000184 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000185 m_continue_c_tids (),
186 m_continue_C_tids (),
187 m_continue_s_tids (),
188 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000189 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000190 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000191 m_addr_to_mmap_size (),
192 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000193 m_waiting_for_attach (false),
194 m_destroy_tried_resuming (false)
Chris Lattner24943d22010-06-08 16:52:24 +0000195{
Greg Claytonff39f742011-04-01 00:29:43 +0000196 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
197 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000198 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000199}
200
201//----------------------------------------------------------------------
202// Destructor
203//----------------------------------------------------------------------
204ProcessGDBRemote::~ProcessGDBRemote()
205{
206 // m_mach_process.UnregisterNotificationCallbacks (this);
207 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000208 // We need to call finalize on the process before destroying ourselves
209 // to make sure all of the broadcaster cleanup goes as planned. If we
210 // destruct this class, then Process::~Process() might have problems
211 // trying to fully destroy the broadcaster.
212 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000213}
214
215//----------------------------------------------------------------------
216// PluginInterface
217//----------------------------------------------------------------------
218const char *
219ProcessGDBRemote::GetPluginName()
220{
221 return "Process debugging plug-in that uses the GDB remote protocol";
222}
223
224const char *
225ProcessGDBRemote::GetShortPluginName()
226{
227 return GetPluginNameStatic();
228}
229
230uint32_t
231ProcessGDBRemote::GetPluginVersion()
232{
233 return 1;
234}
235
236void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000237ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000238{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000239 if (!force && m_register_info.GetNumRegisters() > 0)
240 return;
241
242 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000243 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000244 uint32_t reg_offset = 0;
245 uint32_t reg_num = 0;
Greg Clayton4a379b12012-07-17 03:23:13 +0000246 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton61d043b2011-03-22 04:00:09 +0000247 response_type == StringExtractorGDBRemote::eResponse;
248 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000249 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000250 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
251 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000252 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000253 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000254 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000255 response_type = response.GetResponseType();
256 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000257 {
258 std::string name;
259 std::string value;
260 ConstString reg_name;
261 ConstString alt_name;
262 ConstString set_name;
263 RegisterInfo reg_info = { NULL, // Name
264 NULL, // Alt name
265 0, // byte size
266 reg_offset, // offset
267 eEncodingUint, // encoding
268 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000269 {
270 LLDB_INVALID_REGNUM, // GCC reg num
271 LLDB_INVALID_REGNUM, // DWARF reg num
272 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000273 reg_num, // GDB reg num
274 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000275 },
276 NULL,
277 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000278 };
279
280 while (response.GetNameColonValue(name, value))
281 {
282 if (name.compare("name") == 0)
283 {
284 reg_name.SetCString(value.c_str());
285 }
286 else if (name.compare("alt-name") == 0)
287 {
288 alt_name.SetCString(value.c_str());
289 }
290 else if (name.compare("bitsize") == 0)
291 {
292 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
293 }
294 else if (name.compare("offset") == 0)
295 {
296 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000297 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000298 {
299 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000300 }
301 }
302 else if (name.compare("encoding") == 0)
303 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000304 const Encoding encoding = Args::StringToEncoding (value.c_str());
305 if (encoding != eEncodingInvalid)
306 reg_info.encoding = encoding;
Chris Lattner24943d22010-06-08 16:52:24 +0000307 }
308 else if (name.compare("format") == 0)
309 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000310 Format format = eFormatInvalid;
311 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
312 reg_info.format = format;
313 else if (value.compare("binary") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000314 reg_info.format = eFormatBinary;
315 else if (value.compare("decimal") == 0)
316 reg_info.format = eFormatDecimal;
317 else if (value.compare("hex") == 0)
318 reg_info.format = eFormatHex;
319 else if (value.compare("float") == 0)
320 reg_info.format = eFormatFloat;
321 else if (value.compare("vector-sint8") == 0)
322 reg_info.format = eFormatVectorOfSInt8;
323 else if (value.compare("vector-uint8") == 0)
324 reg_info.format = eFormatVectorOfUInt8;
325 else if (value.compare("vector-sint16") == 0)
326 reg_info.format = eFormatVectorOfSInt16;
327 else if (value.compare("vector-uint16") == 0)
328 reg_info.format = eFormatVectorOfUInt16;
329 else if (value.compare("vector-sint32") == 0)
330 reg_info.format = eFormatVectorOfSInt32;
331 else if (value.compare("vector-uint32") == 0)
332 reg_info.format = eFormatVectorOfUInt32;
333 else if (value.compare("vector-float32") == 0)
334 reg_info.format = eFormatVectorOfFloat32;
335 else if (value.compare("vector-uint128") == 0)
336 reg_info.format = eFormatVectorOfUInt128;
337 }
338 else if (name.compare("set") == 0)
339 {
340 set_name.SetCString(value.c_str());
341 }
342 else if (name.compare("gcc") == 0)
343 {
344 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
345 }
346 else if (name.compare("dwarf") == 0)
347 {
348 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
349 }
350 else if (name.compare("generic") == 0)
351 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000352 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000353 }
354 }
355
Jason Molenda53d96862010-06-11 23:44:18 +0000356 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000357 assert (reg_info.byte_size != 0);
358 reg_offset += reg_info.byte_size;
359 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
360 }
361 }
362 else
363 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000364 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000365 }
366 }
367
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000368 // We didn't get anything if the accumulated reg_num is zero. See if we are
369 // debugging ARM and fill with a hard coded register set until we can get an
370 // updated debugserver down on the devices.
371 // On the other hand, if the accumulated reg_num is positive, see if we can
372 // add composite registers to the existing primordial ones.
373 bool from_scratch = (reg_num == 0);
374
375 const ArchSpec &target_arch = GetTarget().GetArchitecture();
376 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
377 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000378 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000379 if (remote_arch.IsValid()
380 && remote_arch.GetMachine() == llvm::Triple::arm
381 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
382 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000383 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000384 else if (target_arch.GetMachine() == llvm::Triple::arm)
385 {
386 m_register_info.HardcodeARMRegisters(from_scratch);
387 }
388
Johnny Chend2e30662012-05-22 00:57:05 +0000389 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000390 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
391 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000392 m_register_info.Addx86_64ConvenienceRegisters();
393
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000394 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000395 m_register_info.Finalize ();
396}
397
398Error
399ProcessGDBRemote::WillLaunch (Module* module)
400{
401 return WillLaunchOrAttach ();
402}
403
404Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000405ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000406{
407 return WillLaunchOrAttach ();
408}
409
410Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000411ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000412{
413 return WillLaunchOrAttach ();
414}
415
416Error
Jason Molendafac2e622012-09-29 04:02:01 +0000417ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +0000418{
419 Error error (WillLaunchOrAttach ());
420
421 if (error.Fail())
422 return error;
423
Greg Clayton180546b2011-04-30 01:09:13 +0000424 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000425
426 if (error.Fail())
427 return error;
428 StartAsyncThread ();
429
Jason Molendafac2e622012-09-29 04:02:01 +0000430 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
431 if (gdb_remote_arch.IsValid() && gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
432 {
433 Module *exe_module = GetTarget().GetExecutableModulePointer();
434
435 ObjectFile *exe_objfile = exe_module->GetObjectFile();
436
437 // If the remote system is an Apple device and we don't have an exec file
438 // OR we have an exec file and it is a kernel, look for the kernel's load address
439 // in memory and load/relocate the kernel symbols as appropriate.
440 if (exe_objfile == NULL
441 || (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
442 exe_objfile->GetStrata() == ObjectFile::eStrataKernel))
443 {
444
445
446 }
447 }
448
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000449 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000450 if (pid == LLDB_INVALID_PROCESS_ID)
451 {
452 // We don't have a valid process ID, so note that we are connected
453 // and could now request to launch or attach, or get remote process
454 // listings...
455 SetPrivateState (eStateConnected);
456 }
457 else
458 {
459 // We have a valid process
460 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000461 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000462 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000463 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000464 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000465 if (state == eStateStopped)
466 {
467 SetPrivateState (state);
468 }
469 else
Greg Claytond9919d32011-12-01 23:28:38 +0000470 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 +0000471 }
472 else
Greg Claytond9919d32011-12-01 23:28:38 +0000473 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 +0000474 }
Jason Molendacb740b32012-05-03 22:37:30 +0000475
476 if (error.Success()
477 && !GetTarget().GetArchitecture().IsValid()
478 && m_gdb_comm.GetHostArchitecture().IsValid())
479 {
480 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
481 }
482
Greg Claytone71e2582011-02-04 01:58:07 +0000483 return error;
484}
485
486Error
Chris Lattner24943d22010-06-08 16:52:24 +0000487ProcessGDBRemote::WillLaunchOrAttach ()
488{
489 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000490 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000491 return error;
492}
493
494//----------------------------------------------------------------------
495// Process Control
496//----------------------------------------------------------------------
497Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000498ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000499{
Greg Clayton4b407112010-09-30 21:49:03 +0000500 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000501
502 uint32_t launch_flags = launch_info.GetFlags().Get();
503 const char *stdin_path = NULL;
504 const char *stdout_path = NULL;
505 const char *stderr_path = NULL;
506 const char *working_dir = launch_info.GetWorkingDirectory();
507
508 const ProcessLaunchInfo::FileAction *file_action;
509 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
510 if (file_action)
511 {
512 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
513 stdin_path = file_action->GetPath();
514 }
515 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
516 if (file_action)
517 {
518 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
519 stdout_path = file_action->GetPath();
520 }
521 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
522 if (file_action)
523 {
524 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
525 stderr_path = file_action->GetPath();
526 }
527
Chris Lattner24943d22010-06-08 16:52:24 +0000528 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
529 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
530 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000531 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000532
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000533 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000534 if (object_file)
535 {
Chris Lattner24943d22010-06-08 16:52:24 +0000536 char host_port[128];
537 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000538 char connect_url[128];
539 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000540
Greg Claytona2f74232011-02-24 22:24:29 +0000541 // Make sure we aren't already connected?
542 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000543 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000544 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000545 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000546 {
Johnny Chenc143d622011-08-09 18:56:45 +0000547 if (log)
548 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000549 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000550 }
Chris Lattner24943d22010-06-08 16:52:24 +0000551
Greg Claytone71e2582011-02-04 01:58:07 +0000552 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000553 }
554
555 if (error.Success())
556 {
557 lldb_utility::PseudoTerminal pty;
558 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000559
560 // If the debugserver is local and we aren't disabling STDIO, lets use
561 // a pseudo terminal to instead of relying on the 'O' packets for stdio
562 // since 'O' packets can really slow down debugging if the inferior
563 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000564 PlatformSP platform_sp (m_target.GetPlatform());
565 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000566 {
567 const char *slave_name = NULL;
568 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000569 {
Greg Claytona2f74232011-02-24 22:24:29 +0000570 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
571 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000572 }
Greg Claytona2f74232011-02-24 22:24:29 +0000573 if (stdin_path == NULL)
574 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000575
Greg Claytona2f74232011-02-24 22:24:29 +0000576 if (stdout_path == NULL)
577 stdout_path = slave_name;
578
579 if (stderr_path == NULL)
580 stderr_path = slave_name;
581 }
582
Greg Claytonafb81862011-03-02 21:34:46 +0000583 // Set STDIN to /dev/null if we want STDIO disabled or if either
584 // STDOUT or STDERR have been set to something and STDIN hasn't
585 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000586 stdin_path = "/dev/null";
587
Greg Claytonafb81862011-03-02 21:34:46 +0000588 // Set STDOUT to /dev/null if we want STDIO disabled or if either
589 // STDIN or STDERR have been set to something and STDOUT hasn't
590 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000591 stdout_path = "/dev/null";
592
Greg Claytonafb81862011-03-02 21:34:46 +0000593 // Set STDERR to /dev/null if we want STDIO disabled or if either
594 // STDIN or STDOUT have been set to something and STDERR hasn't
595 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000596 stderr_path = "/dev/null";
597
598 if (stdin_path)
599 m_gdb_comm.SetSTDIN (stdin_path);
600 if (stdout_path)
601 m_gdb_comm.SetSTDOUT (stdout_path);
602 if (stderr_path)
603 m_gdb_comm.SetSTDERR (stderr_path);
604
605 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
606
Greg Claytona4582402011-05-08 04:53:50 +0000607 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000608
609 if (working_dir && working_dir[0])
610 {
611 m_gdb_comm.SetWorkingDir (working_dir);
612 }
613
614 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000615 const Args &environment = launch_info.GetEnvironmentEntries();
616 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000617 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000618 size_t num_environment_entries = environment.GetArgumentCount();
619 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000620 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000621 const char *env_entry = environment.GetArgumentAtIndex(i);
622 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000623 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000624 }
Greg Claytona2f74232011-02-24 22:24:29 +0000625 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000626
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000627 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000628 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000629 if (arg_packet_err == 0)
630 {
631 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000632 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000633 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000634 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000635 }
636 else
637 {
Greg Claytona2f74232011-02-24 22:24:29 +0000638 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000639 }
Greg Claytona2f74232011-02-24 22:24:29 +0000640 }
641 else
642 {
Greg Clayton9c236732011-10-26 00:56:27 +0000643 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000644 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000645
646 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000647
Greg Claytona2f74232011-02-24 22:24:29 +0000648 if (GetID() == LLDB_INVALID_PROCESS_ID)
649 {
Johnny Chenc143d622011-08-09 18:56:45 +0000650 if (log)
651 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000652 KillDebugserverProcess ();
653 return error;
654 }
655
Greg Clayton261a18b2011-06-02 22:22:38 +0000656 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000657 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000658 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000659
660 if (!disable_stdio)
661 {
662 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000663 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000664 }
Chris Lattner24943d22010-06-08 16:52:24 +0000665 }
666 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000667 else
668 {
Johnny Chenc143d622011-08-09 18:56:45 +0000669 if (log)
670 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000671 }
Chris Lattner24943d22010-06-08 16:52:24 +0000672 }
673 else
674 {
675 // Set our user ID to an invalid process ID.
676 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000677 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
678 exe_module->GetFileSpec().GetFilename().AsCString(),
679 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000680 }
Chris Lattner24943d22010-06-08 16:52:24 +0000681 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000682
Chris Lattner24943d22010-06-08 16:52:24 +0000683}
684
685
686Error
Greg Claytone71e2582011-02-04 01:58:07 +0000687ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000688{
689 Error error;
690 // Sleep and wait a bit for debugserver to start to listen...
691 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
692 if (conn_ap.get())
693 {
Chris Lattner24943d22010-06-08 16:52:24 +0000694 const uint32_t max_retry_count = 50;
695 uint32_t retry_count = 0;
696 while (!m_gdb_comm.IsConnected())
697 {
Greg Claytone71e2582011-02-04 01:58:07 +0000698 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000699 {
700 m_gdb_comm.SetConnection (conn_ap.release());
701 break;
702 }
703 retry_count++;
704
705 if (retry_count >= max_retry_count)
706 break;
707
708 usleep (100000);
709 }
710 }
711
712 if (!m_gdb_comm.IsConnected())
713 {
714 if (error.Success())
715 error.SetErrorString("not connected to remote gdb server");
716 return error;
717 }
718
Greg Clayton24bc5d92011-03-30 18:16:51 +0000719 // We always seem to be able to open a connection to a local port
720 // so we need to make sure we can then send data to it. If we can't
721 // then we aren't actually connected to anything, so try and do the
722 // handshake with the remote GDB server and make sure that goes
723 // alright.
724 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000725 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000726 m_gdb_comm.Disconnect();
727 if (error.Success())
728 error.SetErrorString("not connected to remote gdb server");
729 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000730 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000731 m_gdb_comm.ResetDiscoverableSettings();
732 m_gdb_comm.QueryNoAckModeSupported ();
733 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000734 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000735 m_gdb_comm.GetHostInfo ();
736 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000737 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000738
739 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
740 for (size_t idx = 0; idx < num_cmds; idx++)
741 {
742 StringExtractorGDBRemote response;
743 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx));
744 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
745 }
Chris Lattner24943d22010-06-08 16:52:24 +0000746 return error;
747}
748
749void
750ProcessGDBRemote::DidLaunchOrAttach ()
751{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000752 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
753 if (log)
754 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000755 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000756 {
757 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
758
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000759 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000760
Chris Lattner24943d22010-06-08 16:52:24 +0000761 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000762
Greg Claytoncb8977d2011-03-23 00:09:55 +0000763 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
764 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000765 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000766 ArchSpec &target_arch = GetTarget().GetArchitecture();
767
768 if (target_arch.IsValid())
769 {
770 // If the remote host is ARM and we have apple as the vendor, then
771 // ARM executables and shared libraries can have mixed ARM architectures.
772 // You can have an armv6 executable, and if the host is armv7, then the
773 // system will load the best possible architecture for all shared libraries
774 // it has, so we really need to take the remote host architecture as our
775 // defacto architecture in this case.
776
777 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
778 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
779 {
780 target_arch = gdb_remote_arch;
781 }
782 else
783 {
784 // Fill in what is missing in the triple
785 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
786 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000787 if (target_triple.getVendorName().size() == 0)
788 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000789 target_triple.setVendor (remote_triple.getVendor());
790
Greg Clayton2f085c62011-05-15 01:25:55 +0000791 if (target_triple.getOSName().size() == 0)
792 {
793 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000794
Greg Clayton2f085c62011-05-15 01:25:55 +0000795 if (target_triple.getEnvironmentName().size() == 0)
796 target_triple.setEnvironment (remote_triple.getEnvironment());
797 }
798 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000799 }
800 }
801 else
802 {
803 // The target doesn't have a valid architecture yet, set it from
804 // the architecture we got from the remote GDB server
805 target_arch = gdb_remote_arch;
806 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000807 }
Chris Lattner24943d22010-06-08 16:52:24 +0000808 }
809}
810
811void
812ProcessGDBRemote::DidLaunch ()
813{
814 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000815}
816
817Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000818ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000819{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000820 ProcessAttachInfo attach_info;
821 return DoAttachToProcessWithID(attach_pid, attach_info);
822}
823
824Error
825ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
826{
Chris Lattner24943d22010-06-08 16:52:24 +0000827 Error error;
828 // Clear out and clean up from any current state
829 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000830 if (attach_pid != LLDB_INVALID_PROCESS_ID)
831 {
Greg Claytona2f74232011-02-24 22:24:29 +0000832 // Make sure we aren't already connected?
833 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000834 {
Greg Claytona2f74232011-02-24 22:24:29 +0000835 char host_port[128];
836 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
837 char connect_url[128];
838 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000839
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000840 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000841
842 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000843 {
Greg Claytona2f74232011-02-24 22:24:29 +0000844 const char *error_string = error.AsCString();
845 if (error_string == NULL)
846 error_string = "unable to launch " DEBUGSERVER_BASENAME;
847
848 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000849 }
Greg Claytona2f74232011-02-24 22:24:29 +0000850 else
851 {
852 error = ConnectToDebugserver (connect_url);
853 }
854 }
855
856 if (error.Success())
857 {
858 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000859 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000860 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000861 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000862 }
863 }
Chris Lattner24943d22010-06-08 16:52:24 +0000864 return error;
865}
866
867size_t
868ProcessGDBRemote::AttachInputReaderCallback
869(
870 void *baton,
871 InputReader *reader,
872 lldb::InputReaderAction notification,
873 const char *bytes,
874 size_t bytes_len
875)
876{
877 if (notification == eInputReaderGotToken)
878 {
879 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
880 if (gdb_process->m_waiting_for_attach)
881 gdb_process->m_waiting_for_attach = false;
882 reader->SetIsDone(true);
883 return 1;
884 }
885 return 0;
886}
887
888Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000889ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000890{
891 Error error;
892 // Clear out and clean up from any current state
893 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000894
Chris Lattner24943d22010-06-08 16:52:24 +0000895 if (process_name && process_name[0])
896 {
Greg Claytona2f74232011-02-24 22:24:29 +0000897 // Make sure we aren't already connected?
898 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000899 {
Greg Claytona2f74232011-02-24 22:24:29 +0000900 char host_port[128];
901 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
902 char connect_url[128];
903 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
904
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000905 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000906 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000907 {
Greg Claytona2f74232011-02-24 22:24:29 +0000908 const char *error_string = error.AsCString();
909 if (error_string == NULL)
910 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000911
Greg Claytona2f74232011-02-24 22:24:29 +0000912 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000913 }
Greg Claytona2f74232011-02-24 22:24:29 +0000914 else
915 {
916 error = ConnectToDebugserver (connect_url);
917 }
918 }
919
920 if (error.Success())
921 {
922 StreamString packet;
923
924 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +0000925 {
926 if (!m_gdb_comm.GetVAttachOrWaitSupported())
927 {
928 packet.PutCString ("vAttachWait");
929 }
930 else
931 {
932 if (attach_info.GetIgnoreExisting())
933 packet.PutCString("vAttachWait");
934 else
935 packet.PutCString ("vAttachOrWait");
936 }
937 }
Greg Claytona2f74232011-02-24 22:24:29 +0000938 else
939 packet.PutCString("vAttachName");
940 packet.PutChar(';');
941 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
942
943 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
944
Chris Lattner24943d22010-06-08 16:52:24 +0000945 }
946 }
Chris Lattner24943d22010-06-08 16:52:24 +0000947 return error;
948}
949
Chris Lattner24943d22010-06-08 16:52:24 +0000950
951void
952ProcessGDBRemote::DidAttach ()
953{
Greg Claytone71e2582011-02-04 01:58:07 +0000954 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000955}
956
957Error
958ProcessGDBRemote::WillResume ()
959{
Greg Claytonc1f45872011-02-12 06:28:37 +0000960 m_continue_c_tids.clear();
961 m_continue_C_tids.clear();
962 m_continue_s_tids.clear();
963 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000964 return Error();
965}
966
967Error
968ProcessGDBRemote::DoResume ()
969{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000970 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000971 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
972 if (log)
973 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000974
975 Listener listener ("gdb-remote.resume-packet-sent");
976 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
977 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000978 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
979
Greg Claytonc1f45872011-02-12 06:28:37 +0000980 StreamString continue_packet;
981 bool continue_packet_error = false;
982 if (m_gdb_comm.HasAnyVContSupport ())
983 {
984 continue_packet.PutCString ("vCont");
985
986 if (!m_continue_c_tids.empty())
987 {
988 if (m_gdb_comm.GetVContSupported ('c'))
989 {
990 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 +0000991 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000992 }
993 else
994 continue_packet_error = true;
995 }
996
997 if (!continue_packet_error && !m_continue_C_tids.empty())
998 {
999 if (m_gdb_comm.GetVContSupported ('C'))
1000 {
1001 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 +00001002 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001003 }
1004 else
1005 continue_packet_error = true;
1006 }
Greg Claytonb749a262010-12-03 06:02:24 +00001007
Greg Claytonc1f45872011-02-12 06:28:37 +00001008 if (!continue_packet_error && !m_continue_s_tids.empty())
1009 {
1010 if (m_gdb_comm.GetVContSupported ('s'))
1011 {
1012 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 +00001013 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001014 }
1015 else
1016 continue_packet_error = true;
1017 }
1018
1019 if (!continue_packet_error && !m_continue_S_tids.empty())
1020 {
1021 if (m_gdb_comm.GetVContSupported ('S'))
1022 {
1023 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 +00001024 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001025 }
1026 else
1027 continue_packet_error = true;
1028 }
1029
1030 if (continue_packet_error)
1031 continue_packet.GetString().clear();
1032 }
1033 else
1034 continue_packet_error = true;
1035
1036 if (continue_packet_error)
1037 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001038 // Either no vCont support, or we tried to use part of the vCont
1039 // packet that wasn't supported by the remote GDB server.
1040 // We need to try and make a simple packet that can do our continue
1041 const size_t num_threads = GetThreadList().GetSize();
1042 const size_t num_continue_c_tids = m_continue_c_tids.size();
1043 const size_t num_continue_C_tids = m_continue_C_tids.size();
1044 const size_t num_continue_s_tids = m_continue_s_tids.size();
1045 const size_t num_continue_S_tids = m_continue_S_tids.size();
1046 if (num_continue_c_tids > 0)
1047 {
1048 if (num_continue_c_tids == num_threads)
1049 {
1050 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001051 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001052 continue_packet.PutChar ('c');
1053 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001054 }
1055 else if (num_continue_c_tids == 1 &&
1056 num_continue_C_tids == 0 &&
1057 num_continue_s_tids == 0 &&
1058 num_continue_S_tids == 0 )
1059 {
1060 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001061 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001062 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001063 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001064 }
1065 }
1066
Greg Claytonde1dd812011-06-24 03:21:43 +00001067 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001068 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001069 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1070 num_continue_C_tids > 0 &&
1071 num_continue_s_tids == 0 &&
1072 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001073 {
1074 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001075 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001076 if (num_continue_C_tids > 1)
1077 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001078 // More that one thread with a signal, yet we don't have
1079 // vCont support and we are being asked to resume each
1080 // thread with a signal, we need to make sure they are
1081 // all the same signal, or we can't issue the continue
1082 // accurately with the current support...
1083 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001084 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001085 continue_packet_error = false;
1086 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1087 {
1088 if (m_continue_C_tids[i].second != continue_signo)
1089 continue_packet_error = true;
1090 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001091 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001092 if (!continue_packet_error)
1093 m_gdb_comm.SetCurrentThreadForRun (-1);
1094 }
1095 else
1096 {
1097 // Set the continue thread ID
1098 continue_packet_error = false;
1099 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001100 }
1101 if (!continue_packet_error)
1102 {
1103 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001104 continue_packet.Printf("C%2.2x", continue_signo);
1105 }
1106 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001107 }
1108
Greg Claytonde1dd812011-06-24 03:21:43 +00001109 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001110 {
1111 if (num_continue_s_tids == num_threads)
1112 {
1113 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001114 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001115 continue_packet.PutChar ('s');
1116 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001117 }
1118 else if (num_continue_c_tids == 0 &&
1119 num_continue_C_tids == 0 &&
1120 num_continue_s_tids == 1 &&
1121 num_continue_S_tids == 0 )
1122 {
1123 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001124 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001125 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001126 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001127 }
1128 }
1129
1130 if (!continue_packet_error && num_continue_S_tids > 0)
1131 {
1132 if (num_continue_S_tids == num_threads)
1133 {
1134 const int step_signo = m_continue_S_tids.front().second;
1135 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001136 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001137 if (num_continue_S_tids > 1)
1138 {
1139 for (size_t i=1; i<num_threads; ++i)
1140 {
1141 if (m_continue_S_tids[i].second != step_signo)
1142 continue_packet_error = true;
1143 }
1144 }
1145 if (!continue_packet_error)
1146 {
1147 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001148 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001149 continue_packet.Printf("S%2.2x", step_signo);
1150 }
1151 }
1152 else if (num_continue_c_tids == 0 &&
1153 num_continue_C_tids == 0 &&
1154 num_continue_s_tids == 0 &&
1155 num_continue_S_tids == 1 )
1156 {
1157 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001158 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001159 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001160 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001161 }
1162 }
1163 }
1164
1165 if (continue_packet_error)
1166 {
1167 error.SetErrorString ("can't make continue packet for this resume");
1168 }
1169 else
1170 {
1171 EventSP event_sp;
1172 TimeValue timeout;
1173 timeout = TimeValue::Now();
1174 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001175 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1176 {
1177 error.SetErrorString ("Trying to resume but the async thread is dead.");
1178 if (log)
1179 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1180 return error;
1181 }
1182
Greg Claytonc1f45872011-02-12 06:28:37 +00001183 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1184
1185 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001186 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001187 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001188 if (log)
1189 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1190 }
1191 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1192 {
1193 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1194 if (log)
1195 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1196 return error;
1197 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001198 }
Greg Claytonb749a262010-12-03 06:02:24 +00001199 }
1200
Jim Ingham3ae449a2010-11-17 02:32:00 +00001201 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001202}
1203
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001204void
1205ProcessGDBRemote::ClearThreadIDList ()
1206{
Greg Claytonff3448e2012-04-13 02:11:32 +00001207 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001208 m_thread_ids.clear();
1209}
1210
1211bool
1212ProcessGDBRemote::UpdateThreadIDList ()
1213{
Greg Claytonff3448e2012-04-13 02:11:32 +00001214 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001215 bool sequence_mutex_unavailable = false;
1216 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1217 if (sequence_mutex_unavailable)
1218 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001219 return false; // We just didn't get the list
1220 }
1221 return true;
1222}
1223
Greg Claytonae932352012-04-10 00:18:59 +00001224bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001225ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001226{
1227 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001228 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001229 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001230 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001231
1232 size_t num_thread_ids = m_thread_ids.size();
1233 // The "m_thread_ids" thread ID list should always be updated after each stop
1234 // reply packet, but in case it isn't, update it here.
1235 if (num_thread_ids == 0)
1236 {
1237 if (!UpdateThreadIDList ())
1238 return false;
1239 num_thread_ids = m_thread_ids.size();
1240 }
Chris Lattner24943d22010-06-08 16:52:24 +00001241
Greg Clayton37f962e2011-08-22 02:49:39 +00001242 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001243 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001244 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001245 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001246 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001247 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1248 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001249 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001250 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001251 }
Chris Lattner24943d22010-06-08 16:52:24 +00001252 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001253
Greg Claytonae932352012-04-10 00:18:59 +00001254 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001255}
1256
1257
1258StateType
1259ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1260{
Greg Clayton261a18b2011-06-02 22:22:38 +00001261 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001262 const char stop_type = stop_packet.GetChar();
1263 switch (stop_type)
1264 {
1265 case 'T':
1266 case 'S':
1267 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001268 if (GetStopID() == 0)
1269 {
1270 // Our first stop, make sure we have a process ID, and also make
1271 // sure we know about our registers
1272 if (GetID() == LLDB_INVALID_PROCESS_ID)
1273 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001274 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001275 if (pid != LLDB_INVALID_PROCESS_ID)
1276 SetID (pid);
1277 }
1278 BuildDynamicRegisterInfo (true);
1279 }
Chris Lattner24943d22010-06-08 16:52:24 +00001280 // Stop with signal and thread info
1281 const uint8_t signo = stop_packet.GetHexU8();
1282 std::string name;
1283 std::string value;
1284 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001285 std::string reason;
1286 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001287 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001288 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001289 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001290 ThreadSP thread_sp;
1291
Chris Lattner24943d22010-06-08 16:52:24 +00001292 while (stop_packet.GetNameColonValue(name, value))
1293 {
1294 if (name.compare("metype") == 0)
1295 {
1296 // exception type in big endian hex
1297 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1298 }
Chris Lattner24943d22010-06-08 16:52:24 +00001299 else if (name.compare("medata") == 0)
1300 {
1301 // exception data in big endian hex
1302 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1303 }
1304 else if (name.compare("thread") == 0)
1305 {
1306 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001307 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001308 // m_thread_list does have its own mutex, but we need to
1309 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1310 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001311 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001312 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001313 if (!thread_sp)
1314 {
1315 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001316 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001317 m_thread_list.AddThread(thread_sp);
1318 }
Chris Lattner24943d22010-06-08 16:52:24 +00001319 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001320 else if (name.compare("threads") == 0)
1321 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001322 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001323 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001324 // A comma separated list of all threads in the current
1325 // process that includes the thread for this stop reply
1326 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001327 size_t comma_pos;
1328 lldb::tid_t tid;
1329 while ((comma_pos = value.find(',')) != std::string::npos)
1330 {
1331 value[comma_pos] = '\0';
1332 // thread in big endian hex
1333 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1334 if (tid != LLDB_INVALID_THREAD_ID)
1335 m_thread_ids.push_back (tid);
1336 value.erase(0, comma_pos + 1);
1337
1338 }
1339 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1340 if (tid != LLDB_INVALID_THREAD_ID)
1341 m_thread_ids.push_back (tid);
1342 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001343 else if (name.compare("hexname") == 0)
1344 {
1345 StringExtractor name_extractor;
1346 // Swap "value" over into "name_extractor"
1347 name_extractor.GetStringRef().swap(value);
1348 // Now convert the HEX bytes into a string value
1349 name_extractor.GetHexByteString (value);
1350 thread_name.swap (value);
1351 }
Chris Lattner24943d22010-06-08 16:52:24 +00001352 else if (name.compare("name") == 0)
1353 {
1354 thread_name.swap (value);
1355 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001356 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001357 {
1358 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1359 }
Greg Clayton65611552011-06-04 01:26:29 +00001360 else if (name.compare("reason") == 0)
1361 {
1362 reason.swap(value);
1363 }
1364 else if (name.compare("description") == 0)
1365 {
1366 StringExtractor desc_extractor;
1367 // Swap "value" over into "name_extractor"
1368 desc_extractor.GetStringRef().swap(value);
1369 // Now convert the HEX bytes into a string value
1370 desc_extractor.GetHexByteString (thread_name);
1371 }
Greg Claytona875b642011-01-09 21:07:35 +00001372 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1373 {
1374 // We have a register number that contains an expedited
1375 // register value. Lets supply this register to our thread
1376 // so it won't have to go and read it.
1377 if (thread_sp)
1378 {
1379 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1380
1381 if (reg != UINT32_MAX)
1382 {
1383 StringExtractor reg_value_extractor;
1384 // Swap "value" over into "reg_value_extractor"
1385 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001386 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1387 {
1388 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1389 name.c_str(),
1390 reg,
1391 reg,
1392 reg_value_extractor.GetStringRef().c_str(),
1393 stop_packet.GetStringRef().c_str());
1394 }
Greg Claytona875b642011-01-09 21:07:35 +00001395 }
1396 }
1397 }
Chris Lattner24943d22010-06-08 16:52:24 +00001398 }
Chris Lattner24943d22010-06-08 16:52:24 +00001399
1400 if (thread_sp)
1401 {
1402 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1403
1404 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001405 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001406 if (exc_type != 0)
1407 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001408 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001409
1410 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1411 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001412 exc_data_size,
1413 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001414 exc_data_size >= 2 ? exc_data[1] : 0,
1415 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001416 }
Greg Clayton65611552011-06-04 01:26:29 +00001417 else
Chris Lattner24943d22010-06-08 16:52:24 +00001418 {
Greg Clayton65611552011-06-04 01:26:29 +00001419 bool handled = false;
1420 if (!reason.empty())
1421 {
1422 if (reason.compare("trace") == 0)
1423 {
1424 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1425 handled = true;
1426 }
1427 else if (reason.compare("breakpoint") == 0)
1428 {
1429 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001430 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001431 if (bp_site_sp)
1432 {
1433 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1434 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1435 // 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 +00001436 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001437 if (bp_site_sp->ValidForThisThread (gdb_thread))
1438 {
1439 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001440 }
1441 else
1442 {
1443 StopInfoSP invalid_stop_info_sp;
1444 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001445 }
1446 }
1447
Greg Clayton65611552011-06-04 01:26:29 +00001448 }
1449 else if (reason.compare("trap") == 0)
1450 {
1451 // Let the trap just use the standard signal stop reason below...
1452 }
1453 else if (reason.compare("watchpoint") == 0)
1454 {
1455 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1456 // TODO: locate the watchpoint somehow...
1457 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1458 handled = true;
1459 }
1460 else if (reason.compare("exception") == 0)
1461 {
1462 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1463 handled = true;
1464 }
1465 }
1466
1467 if (signo)
1468 {
1469 if (signo == SIGTRAP)
1470 {
1471 // Currently we are going to assume SIGTRAP means we are either
1472 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001473 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001474 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001475 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001476
Greg Clayton65611552011-06-04 01:26:29 +00001477 if (bp_site_sp)
1478 {
1479 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1480 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1481 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1482 if (bp_site_sp->ValidForThisThread (gdb_thread))
1483 {
1484 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001485 }
1486 else
1487 {
1488 StopInfoSP invalid_stop_info_sp;
1489 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001490 }
1491 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001492 else
Greg Clayton65611552011-06-04 01:26:29 +00001493 {
1494 // TODO: check for breakpoint or trap opcode in case there is a hard
1495 // coded software trap
1496 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton65611552011-06-04 01:26:29 +00001497 }
1498 }
1499 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001500 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001501 }
1502 else
1503 {
Greg Clayton643ee732010-08-04 01:40:35 +00001504 StopInfoSP invalid_stop_info_sp;
1505 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001506 }
Greg Clayton65611552011-06-04 01:26:29 +00001507
1508 if (!description.empty())
1509 {
1510 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1511 if (stop_info_sp)
1512 {
1513 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001514 }
Greg Clayton65611552011-06-04 01:26:29 +00001515 else
1516 {
1517 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1518 }
1519 }
1520 }
Chris Lattner24943d22010-06-08 16:52:24 +00001521 }
1522 return eStateStopped;
1523 }
1524 break;
1525
1526 case 'W':
1527 // process exited
1528 return eStateExited;
1529
1530 default:
1531 break;
1532 }
1533 return eStateInvalid;
1534}
1535
1536void
1537ProcessGDBRemote::RefreshStateAfterStop ()
1538{
Greg Claytonff3448e2012-04-13 02:11:32 +00001539 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001540 m_thread_ids.clear();
1541 // Set the thread stop info. It might have a "threads" key whose value is
1542 // a list of all thread IDs in the current process, so m_thread_ids might
1543 // get set.
1544 SetThreadStopInfo (m_last_stop_packet);
1545 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1546 if (m_thread_ids.empty())
1547 {
1548 // No, we need to fetch the thread list manually
1549 UpdateThreadIDList();
1550 }
1551
Chris Lattner24943d22010-06-08 16:52:24 +00001552 // Let all threads recover from stopping and do any clean up based
1553 // on the previous thread state (if any).
1554 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001555
Chris Lattner24943d22010-06-08 16:52:24 +00001556}
1557
1558Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001559ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001560{
1561 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001562
Greg Claytona4881d02011-01-22 07:12:45 +00001563 bool timed_out = false;
1564 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001565
1566 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001567 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001568 // We are being asked to halt during an attach. We need to just close
1569 // our file handle and debugserver will go away, and we can be done...
1570 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001571 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001572 else
1573 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001574 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001575 {
1576 if (timed_out)
1577 error.SetErrorString("timed out sending interrupt packet");
1578 else
1579 error.SetErrorString("unknown error sending interrupt packet");
1580 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001581
1582 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001583 }
Chris Lattner24943d22010-06-08 16:52:24 +00001584 return error;
1585}
1586
1587Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001588ProcessGDBRemote::InterruptIfRunning
1589(
1590 bool discard_thread_plans,
1591 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001592 EventSP &stop_event_sp
1593)
Chris Lattner24943d22010-06-08 16:52:24 +00001594{
1595 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001596
Greg Clayton2860ba92011-01-23 19:58:49 +00001597 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1598
Greg Clayton68ca8232011-01-25 02:58:48 +00001599 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001600 const bool is_running = m_gdb_comm.IsRunning();
1601 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001602 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001603 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001604 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001605 is_running);
1606
Greg Clayton2860ba92011-01-23 19:58:49 +00001607 if (discard_thread_plans)
1608 {
1609 if (log)
1610 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1611 m_thread_list.DiscardThreadPlans();
1612 }
1613 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001614 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001615 if (catch_stop_event)
1616 {
1617 if (log)
1618 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1619 PausePrivateStateThread();
1620 paused_private_state_thread = true;
1621 }
1622
Greg Clayton4fb400f2010-09-27 21:07:38 +00001623 bool timed_out = false;
1624 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001625
Greg Clayton05e4d972012-03-29 01:55:41 +00001626 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001627 {
1628 if (timed_out)
1629 error.SetErrorString("timed out sending interrupt packet");
1630 else
1631 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001632 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001633 ResumePrivateStateThread();
1634 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001635 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001636
Greg Clayton72e1c782011-01-22 23:43:18 +00001637 if (catch_stop_event)
1638 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001639 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001640 TimeValue timeout_time;
1641 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001642 timeout_time.OffsetWithSeconds(5);
1643 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001644
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001645 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001646 if (log)
1647 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001648
Greg Clayton2860ba92011-01-23 19:58:49 +00001649 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001650 error.SetErrorString("unable to verify target stopped");
1651 }
1652
Greg Clayton68ca8232011-01-25 02:58:48 +00001653 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001654 {
1655 if (log)
1656 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001657 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001658 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001659 }
Chris Lattner24943d22010-06-08 16:52:24 +00001660 return error;
1661}
1662
Greg Clayton4fb400f2010-09-27 21:07:38 +00001663Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001664ProcessGDBRemote::WillDetach ()
1665{
Greg Clayton2860ba92011-01-23 19:58:49 +00001666 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1667 if (log)
1668 log->Printf ("ProcessGDBRemote::WillDetach()");
1669
Greg Clayton72e1c782011-01-22 23:43:18 +00001670 bool discard_thread_plans = true;
1671 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001672 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001673
1674 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1675 // needed. This shouldn't be a feature of a particular plugin.
1676
Greg Clayton68ca8232011-01-25 02:58:48 +00001677 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001678}
1679
1680Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001681ProcessGDBRemote::DoDetach()
1682{
1683 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001684 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001685 if (log)
1686 log->Printf ("ProcessGDBRemote::DoDetach()");
1687
1688 DisableAllBreakpointSites ();
1689
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001690 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001691
Greg Clayton516f0842012-04-11 00:24:49 +00001692 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001693 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001694 {
Greg Clayton516f0842012-04-11 00:24:49 +00001695 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001696 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1697 else
1698 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001699 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001700 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001701 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001702
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001703 SetPrivateState (eStateDetached);
1704 ResumePrivateStateThread();
1705
1706 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001707 return error;
1708}
Chris Lattner24943d22010-06-08 16:52:24 +00001709
Jim Ingham06b84492012-07-04 00:35:43 +00001710
Chris Lattner24943d22010-06-08 16:52:24 +00001711Error
1712ProcessGDBRemote::DoDestroy ()
1713{
1714 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001715 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001716 if (log)
1717 log->Printf ("ProcessGDBRemote::DoDestroy()");
1718
Jim Ingham06b84492012-07-04 00:35:43 +00001719 // There is a bug in older iOS debugservers where they don't shut down the process
1720 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1721 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1722 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1723 // destroy it again.
1724 //
1725 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1726 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1727 // the debugservers with this bug are equal. There really should be a better way to test this!
1728 //
1729 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1730 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1731 // just do the straight-forward kill.
1732 //
1733 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1734 // necessary (or helpful) to do any of this.
1735
1736 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1737 {
1738 PlatformSP platform_sp = GetTarget().GetPlatform();
1739
1740 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1741 if (platform_sp
1742 && platform_sp->GetName()
1743 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1744 {
1745 if (m_destroy_tried_resuming)
1746 {
1747 if (log)
1748 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1749 }
1750 else
1751 {
1752 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1753 // but we really need it to happen here and it doesn't matter if we do it twice.
1754 m_thread_list.DiscardThreadPlans();
1755 DisableAllBreakpointSites();
1756
1757 bool stop_looks_like_crash = false;
1758 ThreadList &threads = GetThreadList();
1759
1760 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001761 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001762
1763 size_t num_threads = threads.GetSize();
1764 for (size_t i = 0; i < num_threads; i++)
1765 {
1766 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1767 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1768 StopReason reason = eStopReasonInvalid;
1769 if (stop_info_sp)
1770 reason = stop_info_sp->GetStopReason();
1771 if (reason == eStopReasonBreakpoint
1772 || reason == eStopReasonException)
1773 {
1774 if (log)
1775 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1776 thread_sp->GetID(),
1777 stop_info_sp->GetDescription());
1778 stop_looks_like_crash = true;
1779 break;
1780 }
1781 }
1782 }
1783
1784 if (stop_looks_like_crash)
1785 {
1786 if (log)
1787 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1788 m_destroy_tried_resuming = true;
1789
1790 // If we are going to run again before killing, it would be good to suspend all the threads
1791 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1792 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1793 // have to run the risk of letting those threads proceed a bit.
1794
1795 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001796 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001797
1798 size_t num_threads = threads.GetSize();
1799 for (size_t i = 0; i < num_threads; i++)
1800 {
1801 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1802 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1803 StopReason reason = eStopReasonInvalid;
1804 if (stop_info_sp)
1805 reason = stop_info_sp->GetStopReason();
1806 if (reason != eStopReasonBreakpoint
1807 && reason != eStopReasonException)
1808 {
1809 if (log)
1810 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1811 thread_sp->GetID());
1812 thread_sp->SetResumeState(eStateSuspended);
1813 }
1814 }
1815 }
1816 Resume ();
1817 return Destroy();
1818 }
1819 }
1820 }
1821 }
1822
Chris Lattner24943d22010-06-08 16:52:24 +00001823 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001824 int exit_status = SIGABRT;
1825 std::string exit_string;
1826
Greg Claytona4881d02011-01-22 07:12:45 +00001827 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001828 {
Jim Ingham8226e942011-10-28 01:11:35 +00001829 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001830 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001831
1832 StringExtractorGDBRemote response;
1833 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001834 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1835
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001836 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001837 {
1838 char packet_cmd = response.GetChar(0);
1839
1840 if (packet_cmd == 'W' || packet_cmd == 'X')
1841 {
Greg Clayton06709002011-12-06 04:51:14 +00001842 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001843 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001844 exit_status = response.GetHexU8();
1845 }
1846 else
1847 {
1848 if (log)
1849 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1850 exit_string.assign("got unexpected response to k packet: ");
1851 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001852 }
1853 }
1854 else
1855 {
Jim Ingham8247e622012-06-06 00:32:39 +00001856 if (log)
1857 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1858 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001859 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001860
1861 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00001862 }
Jim Ingham8247e622012-06-06 00:32:39 +00001863 else
1864 {
1865 if (log)
1866 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00001867 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00001868 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001869 }
Jim Ingham8247e622012-06-06 00:32:39 +00001870 else
1871 {
1872 // If we missed setting the exit status on the way out, do it here.
1873 // NB set exit status can be called multiple times, the first one sets the status.
1874 exit_string.assign("destroying when not connected to debugserver");
1875 }
1876
1877 SetExitStatus(exit_status, exit_string.c_str());
1878
Chris Lattner24943d22010-06-08 16:52:24 +00001879 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001880 KillDebugserverProcess ();
1881 return error;
1882}
1883
Chris Lattner24943d22010-06-08 16:52:24 +00001884//------------------------------------------------------------------
1885// Process Queries
1886//------------------------------------------------------------------
1887
1888bool
1889ProcessGDBRemote::IsAlive ()
1890{
Greg Clayton58e844b2010-12-08 05:08:21 +00001891 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001892}
1893
1894addr_t
1895ProcessGDBRemote::GetImageInfoAddress()
1896{
Greg Clayton516f0842012-04-11 00:24:49 +00001897 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001898}
1899
Chris Lattner24943d22010-06-08 16:52:24 +00001900//------------------------------------------------------------------
1901// Process Memory
1902//------------------------------------------------------------------
1903size_t
1904ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1905{
1906 if (size > m_max_memory_size)
1907 {
1908 // Keep memory read sizes down to a sane limit. This function will be
1909 // called multiple times in order to complete the task by
1910 // lldb_private::Process so it is ok to do this.
1911 size = m_max_memory_size;
1912 }
1913
1914 char packet[64];
Greg Clayton851e30e2012-09-18 18:04:04 +00001915 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%llx", (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00001916 assert (packet_len + 1 < sizeof(packet));
1917 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001918 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001919 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001920 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001921 {
1922 error.Clear();
1923 return response.GetHexBytes(buf, size, '\xdd');
1924 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001925 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00001926 error.SetErrorString("memory read failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00001927 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00001928 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00001929 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00001930 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001931 }
1932 else
1933 {
1934 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1935 }
1936 return 0;
1937}
1938
1939size_t
1940ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1941{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001942 if (size > m_max_memory_size)
1943 {
1944 // Keep memory read sizes down to a sane limit. This function will be
1945 // called multiple times in order to complete the task by
1946 // lldb_private::Process so it is ok to do this.
1947 size = m_max_memory_size;
1948 }
1949
Chris Lattner24943d22010-06-08 16:52:24 +00001950 StreamString packet;
Greg Clayton851e30e2012-09-18 18:04:04 +00001951 packet.Printf("M%llx,%llx:", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00001952 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001953 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001954 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001955 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001956 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001957 {
1958 error.Clear();
1959 return size;
1960 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001961 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00001962 error.SetErrorString("memory write failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00001963 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00001964 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00001965 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00001966 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001967 }
1968 else
1969 {
1970 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1971 }
1972 return 0;
1973}
1974
1975lldb::addr_t
1976ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1977{
Greg Clayton989816b2011-05-14 01:50:35 +00001978 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1979
Greg Clayton2f085c62011-05-15 01:25:55 +00001980 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001981 switch (supported)
1982 {
1983 case eLazyBoolCalculate:
1984 case eLazyBoolYes:
1985 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1986 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1987 return allocated_addr;
1988
1989 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001990 // Call mmap() to create memory in the inferior..
1991 unsigned prot = 0;
1992 if (permissions & lldb::ePermissionsReadable)
1993 prot |= eMmapProtRead;
1994 if (permissions & lldb::ePermissionsWritable)
1995 prot |= eMmapProtWrite;
1996 if (permissions & lldb::ePermissionsExecutable)
1997 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001998
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001999 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2000 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2001 m_addr_to_mmap_size[allocated_addr] = size;
2002 else
2003 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002004 break;
2005 }
2006
Chris Lattner24943d22010-06-08 16:52:24 +00002007 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton851e30e2012-09-18 18:04:04 +00002008 error.SetErrorStringWithFormat("unable to allocate %llu bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002009 else
2010 error.Clear();
2011 return allocated_addr;
2012}
2013
2014Error
Greg Claytona9385532011-11-18 07:03:08 +00002015ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2016 MemoryRegionInfo &region_info)
2017{
2018
2019 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2020 return error;
2021}
2022
2023Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002024ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2025{
2026
2027 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2028 return error;
2029}
2030
2031Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002032ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2033{
2034 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2035 return error;
2036}
2037
2038Error
Chris Lattner24943d22010-06-08 16:52:24 +00002039ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2040{
2041 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002042 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2043
2044 switch (supported)
2045 {
2046 case eLazyBoolCalculate:
2047 // We should never be deallocating memory without allocating memory
2048 // first so we should never get eLazyBoolCalculate
2049 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2050 break;
2051
2052 case eLazyBoolYes:
2053 if (!m_gdb_comm.DeallocateMemory (addr))
2054 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2055 break;
2056
2057 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002058 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002059 {
2060 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002061 if (pos != m_addr_to_mmap_size.end() &&
2062 InferiorCallMunmap(this, addr, pos->second))
2063 m_addr_to_mmap_size.erase (pos);
2064 else
2065 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002066 }
2067 break;
2068 }
2069
Chris Lattner24943d22010-06-08 16:52:24 +00002070 return error;
2071}
2072
2073
2074//------------------------------------------------------------------
2075// Process STDIO
2076//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002077size_t
2078ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2079{
2080 if (m_stdio_communication.IsConnected())
2081 {
2082 ConnectionStatus status;
2083 m_stdio_communication.Write(src, src_len, status, NULL);
2084 }
2085 return 0;
2086}
2087
2088Error
2089ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2090{
2091 Error error;
2092 assert (bp_site != NULL);
2093
Greg Claytone005f2c2010-11-06 01:53:30 +00002094 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002095 user_id_t site_id = bp_site->GetID();
2096 const addr_t addr = bp_site->GetLoadAddress();
2097 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002098 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002099
2100 if (bp_site->IsEnabled())
2101 {
2102 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002103 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 +00002104 return error;
2105 }
2106 else
2107 {
2108 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2109
2110 if (bp_site->HardwarePreferred())
2111 {
2112 // Try and set hardware breakpoint, and if that fails, fall through
2113 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002114 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002115 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002116 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002117 {
2118 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002119 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002120 return error;
2121 }
Chris Lattner24943d22010-06-08 16:52:24 +00002122 }
2123 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002124
2125 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002126 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002127 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2128 {
2129 bp_site->SetEnabled(true);
2130 bp_site->SetType (BreakpointSite::eExternal);
2131 return error;
2132 }
Chris Lattner24943d22010-06-08 16:52:24 +00002133 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002134
2135 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002136 }
2137
2138 if (log)
2139 {
2140 const char *err_string = error.AsCString();
2141 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2142 bp_site->GetLoadAddress(),
2143 err_string ? err_string : "NULL");
2144 }
2145 // We shouldn't reach here on a successful breakpoint enable...
2146 if (error.Success())
2147 error.SetErrorToGenericError();
2148 return error;
2149}
2150
2151Error
2152ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2153{
2154 Error error;
2155 assert (bp_site != NULL);
2156 addr_t addr = bp_site->GetLoadAddress();
2157 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002158 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002159 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002160 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002161
2162 if (bp_site->IsEnabled())
2163 {
2164 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2165
Greg Claytonb72d0f02011-04-12 05:54:46 +00002166 BreakpointSite::Type bp_type = bp_site->GetType();
2167 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002168 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002169 case BreakpointSite::eSoftware:
2170 error = DisableSoftwareBreakpoint (bp_site);
2171 break;
2172
2173 case BreakpointSite::eHardware:
2174 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2175 error.SetErrorToGenericError();
2176 break;
2177
2178 case BreakpointSite::eExternal:
2179 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2180 error.SetErrorToGenericError();
2181 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002182 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002183 if (error.Success())
2184 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002185 }
2186 else
2187 {
2188 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002189 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 +00002190 return error;
2191 }
2192
2193 if (error.Success())
2194 error.SetErrorToGenericError();
2195 return error;
2196}
2197
Johnny Chen21900fb2011-09-06 22:38:36 +00002198// Pre-requisite: wp != NULL.
2199static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002200GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002201{
2202 assert(wp);
2203 bool watch_read = wp->WatchpointRead();
2204 bool watch_write = wp->WatchpointWrite();
2205
2206 // watch_read and watch_write cannot both be false.
2207 assert(watch_read || watch_write);
2208 if (watch_read && watch_write)
2209 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002210 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002211 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002212 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002213 return eWatchpointWrite;
2214}
2215
Chris Lattner24943d22010-06-08 16:52:24 +00002216Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002217ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002218{
2219 Error error;
2220 if (wp)
2221 {
2222 user_id_t watchID = wp->GetID();
2223 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002224 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002225 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002226 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002227 if (wp->IsEnabled())
2228 {
2229 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002230 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002231 return error;
2232 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002233
2234 GDBStoppointType type = GetGDBStoppointType(wp);
2235 // Pass down an appropriate z/Z packet...
2236 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002237 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002238 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2239 {
2240 wp->SetEnabled(true);
2241 return error;
2242 }
2243 else
2244 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002245 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002246 else
2247 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002248 }
2249 else
2250 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002251 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002252 }
2253 if (error.Success())
2254 error.SetErrorToGenericError();
2255 return error;
2256}
2257
2258Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002259ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002260{
2261 Error error;
2262 if (wp)
2263 {
2264 user_id_t watchID = wp->GetID();
2265
Greg Claytone005f2c2010-11-06 01:53:30 +00002266 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002267
2268 addr_t addr = wp->GetLoadAddress();
2269 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002270 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002271
Johnny Chen21900fb2011-09-06 22:38:36 +00002272 if (!wp->IsEnabled())
2273 {
2274 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002275 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002276 // See also 'class WatchpointSentry' within StopInfo.cpp.
2277 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2278 // the watchpoint object to intelligently process this action.
2279 wp->SetEnabled(false);
Johnny Chen21900fb2011-09-06 22:38:36 +00002280 return error;
2281 }
2282
Chris Lattner24943d22010-06-08 16:52:24 +00002283 if (wp->IsHardware())
2284 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002285 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002286 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002287 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2288 {
2289 wp->SetEnabled(false);
2290 return error;
2291 }
2292 else
2293 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002294 }
2295 // TODO: clear software watchpoints if we implement them
2296 }
2297 else
2298 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002299 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002300 }
2301 if (error.Success())
2302 error.SetErrorToGenericError();
2303 return error;
2304}
2305
2306void
2307ProcessGDBRemote::Clear()
2308{
2309 m_flags = 0;
2310 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002311}
2312
2313Error
2314ProcessGDBRemote::DoSignal (int signo)
2315{
2316 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002317 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002318 if (log)
2319 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2320
2321 if (!m_gdb_comm.SendAsyncSignal (signo))
2322 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2323 return error;
2324}
2325
Chris Lattner24943d22010-06-08 16:52:24 +00002326Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002327ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2328{
2329 ProcessLaunchInfo launch_info;
2330 return StartDebugserverProcess(debugserver_url, launch_info);
2331}
2332
2333Error
2334ProcessGDBRemote::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 +00002335{
2336 Error error;
2337 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2338 {
2339 // If we locate debugserver, keep that located version around
2340 static FileSpec g_debugserver_file_spec;
2341
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002342 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002343 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002344 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002345
2346 // Always check to see if we have an environment override for the path
2347 // to the debugserver to use and use it if we do.
2348 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2349 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002350 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002351 else
2352 debugserver_file_spec = g_debugserver_file_spec;
2353 bool debugserver_exists = debugserver_file_spec.Exists();
2354 if (!debugserver_exists)
2355 {
2356 // The debugserver binary is in the LLDB.framework/Resources
2357 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002358 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002359 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002360 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002361 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002362 if (debugserver_exists)
2363 {
2364 g_debugserver_file_spec = debugserver_file_spec;
2365 }
2366 else
2367 {
2368 g_debugserver_file_spec.Clear();
2369 debugserver_file_spec.Clear();
2370 }
Chris Lattner24943d22010-06-08 16:52:24 +00002371 }
2372 }
2373
2374 if (debugserver_exists)
2375 {
2376 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2377
2378 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002379
Greg Claytone005f2c2010-11-06 01:53:30 +00002380 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002381
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002382 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002383 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002384
Chris Lattner24943d22010-06-08 16:52:24 +00002385 // Start args with "debugserver /file/path -r --"
2386 debugserver_args.AppendArgument(debugserver_path);
2387 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002388 // use native registers, not the GDB registers
2389 debugserver_args.AppendArgument("--native-regs");
2390 // make debugserver run in its own session so signals generated by
2391 // special terminal key sequences (^C) don't affect debugserver
2392 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002393
Chris Lattner24943d22010-06-08 16:52:24 +00002394 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2395 if (env_debugserver_log_file)
2396 {
2397 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2398 debugserver_args.AppendArgument(arg_cstr);
2399 }
2400
2401 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2402 if (env_debugserver_log_flags)
2403 {
2404 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2405 debugserver_args.AppendArgument(arg_cstr);
2406 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00002407 debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2408 debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002409
Greg Claytonb72d0f02011-04-12 05:54:46 +00002410 // We currently send down all arguments, attach pids, or attach
2411 // process names in dedicated GDB server packets, so we don't need
2412 // to pass them as arguments. This is currently because of all the
2413 // things we need to setup prior to launching: the environment,
2414 // current working dir, file actions, etc.
2415#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002416 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002417 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002418 {
Greg Claytona2f74232011-02-24 22:24:29 +00002419 // Terminate the debugserver args so we can now append the inferior args
2420 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002421
Greg Claytona2f74232011-02-24 22:24:29 +00002422 for (int i = 0; inferior_argv[i] != NULL; ++i)
2423 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002424 }
2425 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2426 {
2427 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2428 debugserver_args.AppendArgument (arg_cstr);
2429 }
2430 else if (attach_name && attach_name[0])
2431 {
2432 if (wait_for_launch)
2433 debugserver_args.AppendArgument ("--waitfor");
2434 else
2435 debugserver_args.AppendArgument ("--attach");
2436 debugserver_args.AppendArgument (attach_name);
2437 }
Chris Lattner24943d22010-06-08 16:52:24 +00002438#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002439
2440 ProcessLaunchInfo::FileAction file_action;
2441
2442 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2443 // to "/dev/null" if we run into any problems.
2444 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002445 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002446 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002447 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002448 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002449 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002450
2451 if (log)
2452 {
2453 StreamString strm;
2454 debugserver_args.Dump (&strm);
2455 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2456 }
2457
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002458 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2459 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002460
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002461 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002462
Greg Claytonb72d0f02011-04-12 05:54:46 +00002463 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002464 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002465 else
Chris Lattner24943d22010-06-08 16:52:24 +00002466 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2467
2468 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002469 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002470 }
2471 else
2472 {
Greg Clayton9c236732011-10-26 00:56:27 +00002473 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002474 }
2475
2476 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2477 StartAsyncThread ();
2478 }
2479 return error;
2480}
2481
2482bool
2483ProcessGDBRemote::MonitorDebugserverProcess
2484(
2485 void *callback_baton,
2486 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002487 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002488 int signo, // Zero for no signal
2489 int exit_status // Exit value of process if signal is zero
2490)
2491{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002492 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2493 // and might not exist anymore, so we need to carefully try to get the
2494 // target for this process first since we have a race condition when
2495 // we are done running between getting the notice that the inferior
2496 // process has died and the debugserver that was debugging this process.
2497 // In our test suite, we are also continually running process after
2498 // process, so we must be very careful to make sure:
2499 // 1 - process object hasn't been deleted already
2500 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002501
2502 // "debugserver_pid" argument passed in is the process ID for
2503 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002504 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002505
Greg Clayton75ccf502010-08-21 02:22:51 +00002506 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002507
Greg Clayton1c4642c2011-11-16 05:37:56 +00002508 // Get a shared pointer to the target that has a matching process pointer.
2509 // This target could be gone, or the target could already have a new process
2510 // object inside of it
2511 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2512
Greg Clayton72e1c782011-01-22 23:43:18 +00002513 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002514 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 +00002515
Greg Clayton1c4642c2011-11-16 05:37:56 +00002516 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002517 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002518 // We found a process in a target that matches, but another thread
2519 // might be in the process of launching a new process that will
2520 // soon replace it, so get a shared pointer to the process so we
2521 // can keep it alive.
2522 ProcessSP process_sp (target_sp->GetProcessSP());
2523 // Now we have a shared pointer to the process that can't go away on us
2524 // so we now make sure it was the same as the one passed in, and also make
2525 // sure that our previous "process *" didn't get deleted and have a new
2526 // "process *" created in its place with the same pointer. To verify this
2527 // we make sure the process has our debugserver process ID. If we pass all
2528 // of these tests, then we are sure that this process is the one we were
2529 // looking for.
2530 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002531 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002532 // Sleep for a half a second to make sure our inferior process has
2533 // time to set its exit status before we set it incorrectly when
2534 // both the debugserver and the inferior process shut down.
2535 usleep (500000);
2536 // If our process hasn't yet exited, debugserver might have died.
2537 // If the process did exit, the we are reaping it.
2538 const StateType state = process->GetState();
2539
2540 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2541 state != eStateInvalid &&
2542 state != eStateUnloaded &&
2543 state != eStateExited &&
2544 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002545 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002546 char error_str[1024];
2547 if (signo)
2548 {
2549 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2550 if (signal_cstr)
2551 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2552 else
2553 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2554 }
Chris Lattner24943d22010-06-08 16:52:24 +00002555 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002556 {
2557 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2558 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002559
Greg Clayton1c4642c2011-11-16 05:37:56 +00002560 process->SetExitStatus (-1, error_str);
2561 }
2562 // Debugserver has exited we need to let our ProcessGDBRemote
2563 // know that it no longer has a debugserver instance
2564 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002565 }
Chris Lattner24943d22010-06-08 16:52:24 +00002566 }
2567 return true;
2568}
2569
2570void
2571ProcessGDBRemote::KillDebugserverProcess ()
2572{
2573 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2574 {
2575 ::kill (m_debugserver_pid, SIGINT);
2576 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2577 }
2578}
2579
2580void
2581ProcessGDBRemote::Initialize()
2582{
2583 static bool g_initialized = false;
2584
2585 if (g_initialized == false)
2586 {
2587 g_initialized = true;
2588 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2589 GetPluginDescriptionStatic(),
2590 CreateInstance);
2591
2592 Log::Callbacks log_callbacks = {
2593 ProcessGDBRemoteLog::DisableLog,
2594 ProcessGDBRemoteLog::EnableLog,
2595 ProcessGDBRemoteLog::ListLogCategories
2596 };
2597
2598 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2599 }
2600}
2601
2602bool
Chris Lattner24943d22010-06-08 16:52:24 +00002603ProcessGDBRemote::StartAsyncThread ()
2604{
Greg Claytone005f2c2010-11-06 01:53:30 +00002605 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002606
2607 if (log)
2608 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2609
2610 // Create a thread that watches our internal state and controls which
2611 // events make it to clients (into the DCProcess event queue).
2612 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002613 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002614}
2615
2616void
2617ProcessGDBRemote::StopAsyncThread ()
2618{
Greg Claytone005f2c2010-11-06 01:53:30 +00002619 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002620
2621 if (log)
2622 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2623
2624 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002625
2626 // This will shut down the async thread.
2627 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002628
2629 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002630 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002631 {
2632 Host::ThreadJoin (m_async_thread, NULL, NULL);
2633 }
2634}
2635
2636
2637void *
2638ProcessGDBRemote::AsyncThread (void *arg)
2639{
2640 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2641
Greg Claytone005f2c2010-11-06 01:53:30 +00002642 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002643 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002644 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002645
2646 Listener listener ("ProcessGDBRemote::AsyncThread");
2647 EventSP event_sp;
2648 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2649 eBroadcastBitAsyncThreadShouldExit;
2650
2651 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2652 {
Greg Claytona2f74232011-02-24 22:24:29 +00002653 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2654
Chris Lattner24943d22010-06-08 16:52:24 +00002655 bool done = false;
2656 while (!done)
2657 {
2658 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002659 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002660 if (listener.WaitForEvent (NULL, event_sp))
2661 {
2662 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002663 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002664 {
Greg Claytona2f74232011-02-24 22:24:29 +00002665 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002666 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 +00002667
Greg Claytona2f74232011-02-24 22:24:29 +00002668 switch (event_type)
2669 {
2670 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002671 {
Greg Claytona2f74232011-02-24 22:24:29 +00002672 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002673
Greg Claytona2f74232011-02-24 22:24:29 +00002674 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002675 {
Greg Claytona2f74232011-02-24 22:24:29 +00002676 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2677 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2678 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002679 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002680
Greg Claytona2f74232011-02-24 22:24:29 +00002681 if (::strstr (continue_cstr, "vAttach") == NULL)
2682 process->SetPrivateState(eStateRunning);
2683 StringExtractorGDBRemote response;
2684 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002685
Greg Clayton67b402c2012-05-16 02:48:06 +00002686 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2687 // The thread ID list might be contained within the "response", or the stop reply packet that
2688 // caused the stop. So clear it now before we give the stop reply packet to the process
2689 // using the process->SetLastStopPacket()...
2690 process->ClearThreadIDList ();
2691
Greg Claytona2f74232011-02-24 22:24:29 +00002692 switch (stop_state)
2693 {
2694 case eStateStopped:
2695 case eStateCrashed:
2696 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002697 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002698 process->SetPrivateState (stop_state);
2699 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002700
Greg Claytona2f74232011-02-24 22:24:29 +00002701 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002702 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002703 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002704 response.SetFilePos(1);
2705 process->SetExitStatus(response.GetHexU8(), NULL);
2706 done = true;
2707 break;
2708
2709 case eStateInvalid:
2710 process->SetExitStatus(-1, "lost connection");
2711 break;
2712
2713 default:
2714 process->SetPrivateState (stop_state);
2715 break;
2716 }
Chris Lattner24943d22010-06-08 16:52:24 +00002717 }
2718 }
Greg Claytona2f74232011-02-24 22:24:29 +00002719 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002720
Greg Claytona2f74232011-02-24 22:24:29 +00002721 case eBroadcastBitAsyncThreadShouldExit:
2722 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002723 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002724 done = true;
2725 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002726
Greg Claytona2f74232011-02-24 22:24:29 +00002727 default:
2728 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002729 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 +00002730 done = true;
2731 break;
2732 }
2733 }
2734 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2735 {
2736 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2737 {
2738 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002739 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002740 }
Chris Lattner24943d22010-06-08 16:52:24 +00002741 }
2742 }
2743 else
2744 {
2745 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002746 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 +00002747 done = true;
2748 }
2749 }
2750 }
2751
2752 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002753 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002754
2755 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2756 return NULL;
2757}
2758
Chris Lattner24943d22010-06-08 16:52:24 +00002759const char *
2760ProcessGDBRemote::GetDispatchQueueNameForThread
2761(
2762 addr_t thread_dispatch_qaddr,
2763 std::string &dispatch_queue_name
2764)
2765{
2766 dispatch_queue_name.clear();
2767 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2768 {
2769 // Cache the dispatch_queue_offsets_addr value so we don't always have
2770 // to look it up
2771 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2772 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002773 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2774 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002775 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2776 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002777 if (module_sp)
2778 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2779
2780 if (dispatch_queue_offsets_symbol == NULL)
2781 {
Greg Clayton444fe992012-02-26 05:51:37 +00002782 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2783 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002784 if (module_sp)
2785 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2786 }
Chris Lattner24943d22010-06-08 16:52:24 +00002787 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002788 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002789
2790 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2791 return NULL;
2792 }
2793
2794 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002795 DataExtractor data (memory_buffer,
2796 sizeof(memory_buffer),
2797 m_target.GetArchitecture().GetByteOrder(),
2798 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002799
2800 // Excerpt from src/queue_private.h
2801 struct dispatch_queue_offsets_s
2802 {
2803 uint16_t dqo_version;
2804 uint16_t dqo_label;
2805 uint16_t dqo_label_size;
2806 } dispatch_queue_offsets;
2807
2808
2809 Error error;
2810 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2811 {
2812 uint32_t data_offset = 0;
2813 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2814 {
2815 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2816 {
2817 data_offset = 0;
2818 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2819 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2820 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2821 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2822 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2823 dispatch_queue_name.erase (bytes_read);
2824 }
2825 }
2826 }
2827 }
2828 if (dispatch_queue_name.empty())
2829 return NULL;
2830 return dispatch_queue_name.c_str();
2831}
2832
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002833//uint32_t
2834//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2835//{
2836// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2837// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2838// if (m_local_debugserver)
2839// {
2840// return Host::ListProcessesMatchingName (name, matches, pids);
2841// }
2842// else
2843// {
2844// // FIXME: Implement talking to the remote debugserver.
2845// return 0;
2846// }
2847//
2848//}
2849//
Jim Ingham55e01d82011-01-22 01:33:44 +00002850bool
2851ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2852 lldb_private::StoppointCallbackContext *context,
2853 lldb::user_id_t break_id,
2854 lldb::user_id_t break_loc_id)
2855{
2856 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2857 // run so I can stop it if that's what I want to do.
2858 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2859 if (log)
2860 log->Printf("Hit New Thread Notification breakpoint.");
2861 return false;
2862}
2863
2864
2865bool
2866ProcessGDBRemote::StartNoticingNewThreads()
2867{
Jim Ingham55e01d82011-01-22 01:33:44 +00002868 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002869 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002870 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002871 if (log && log->GetVerbose())
2872 log->Printf("Enabled noticing new thread breakpoint.");
2873 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002874 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002875 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002876 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002877 PlatformSP platform_sp (m_target.GetPlatform());
2878 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002879 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002880 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2881 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002882 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002883 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002884 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2885 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002886 }
2887 else
2888 {
2889 if (log)
2890 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002891 }
2892 }
2893 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002894 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002895}
2896
2897bool
2898ProcessGDBRemote::StopNoticingNewThreads()
2899{
Jim Inghamff276fe2011-02-08 05:19:01 +00002900 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002901 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002902 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002903
2904 if (m_thread_create_bp_sp)
2905 m_thread_create_bp_sp->SetEnabled(false);
2906
Jim Ingham55e01d82011-01-22 01:33:44 +00002907 return true;
2908}
2909
2910