blob: d25f134de8a4214f47d1ae2ddb165fad7194cd65 [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
Greg Claytone71e2582011-02-04 01:58:07 +0000417ProcessGDBRemote::DoConnectRemote (const char *remote_url)
418{
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
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000430 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000431 if (pid == LLDB_INVALID_PROCESS_ID)
432 {
433 // We don't have a valid process ID, so note that we are connected
434 // and could now request to launch or attach, or get remote process
435 // listings...
436 SetPrivateState (eStateConnected);
437 }
438 else
439 {
440 // We have a valid process
441 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000442 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000443 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000444 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000445 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000446 if (state == eStateStopped)
447 {
448 SetPrivateState (state);
449 }
450 else
Greg Claytond9919d32011-12-01 23:28:38 +0000451 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 +0000452 }
453 else
Greg Claytond9919d32011-12-01 23:28:38 +0000454 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 +0000455 }
Jason Molendacb740b32012-05-03 22:37:30 +0000456
457 if (error.Success()
458 && !GetTarget().GetArchitecture().IsValid()
459 && m_gdb_comm.GetHostArchitecture().IsValid())
460 {
461 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
462 }
463
Greg Claytone71e2582011-02-04 01:58:07 +0000464 return error;
465}
466
467Error
Chris Lattner24943d22010-06-08 16:52:24 +0000468ProcessGDBRemote::WillLaunchOrAttach ()
469{
470 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000471 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000472 return error;
473}
474
475//----------------------------------------------------------------------
476// Process Control
477//----------------------------------------------------------------------
478Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000479ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000480{
Greg Clayton4b407112010-09-30 21:49:03 +0000481 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000482
483 uint32_t launch_flags = launch_info.GetFlags().Get();
484 const char *stdin_path = NULL;
485 const char *stdout_path = NULL;
486 const char *stderr_path = NULL;
487 const char *working_dir = launch_info.GetWorkingDirectory();
488
489 const ProcessLaunchInfo::FileAction *file_action;
490 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
491 if (file_action)
492 {
493 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
494 stdin_path = file_action->GetPath();
495 }
496 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
497 if (file_action)
498 {
499 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
500 stdout_path = file_action->GetPath();
501 }
502 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
503 if (file_action)
504 {
505 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
506 stderr_path = file_action->GetPath();
507 }
508
Chris Lattner24943d22010-06-08 16:52:24 +0000509 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
510 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
511 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000512 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000513
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000514 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000515 if (object_file)
516 {
Chris Lattner24943d22010-06-08 16:52:24 +0000517 char host_port[128];
518 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000519 char connect_url[128];
520 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000521
Greg Claytona2f74232011-02-24 22:24:29 +0000522 // Make sure we aren't already connected?
523 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000524 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000525 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000526 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000527 {
Johnny Chenc143d622011-08-09 18:56:45 +0000528 if (log)
529 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000530 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000531 }
Chris Lattner24943d22010-06-08 16:52:24 +0000532
Greg Claytone71e2582011-02-04 01:58:07 +0000533 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000534 }
535
536 if (error.Success())
537 {
538 lldb_utility::PseudoTerminal pty;
539 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000540
541 // If the debugserver is local and we aren't disabling STDIO, lets use
542 // a pseudo terminal to instead of relying on the 'O' packets for stdio
543 // since 'O' packets can really slow down debugging if the inferior
544 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000545 PlatformSP platform_sp (m_target.GetPlatform());
546 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000547 {
548 const char *slave_name = NULL;
549 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000550 {
Greg Claytona2f74232011-02-24 22:24:29 +0000551 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
552 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000553 }
Greg Claytona2f74232011-02-24 22:24:29 +0000554 if (stdin_path == NULL)
555 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000556
Greg Claytona2f74232011-02-24 22:24:29 +0000557 if (stdout_path == NULL)
558 stdout_path = slave_name;
559
560 if (stderr_path == NULL)
561 stderr_path = slave_name;
562 }
563
Greg Claytonafb81862011-03-02 21:34:46 +0000564 // Set STDIN to /dev/null if we want STDIO disabled or if either
565 // STDOUT or STDERR have been set to something and STDIN hasn't
566 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000567 stdin_path = "/dev/null";
568
Greg Claytonafb81862011-03-02 21:34:46 +0000569 // Set STDOUT to /dev/null if we want STDIO disabled or if either
570 // STDIN or STDERR have been set to something and STDOUT hasn't
571 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000572 stdout_path = "/dev/null";
573
Greg Claytonafb81862011-03-02 21:34:46 +0000574 // Set STDERR to /dev/null if we want STDIO disabled or if either
575 // STDIN or STDOUT have been set to something and STDERR hasn't
576 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000577 stderr_path = "/dev/null";
578
579 if (stdin_path)
580 m_gdb_comm.SetSTDIN (stdin_path);
581 if (stdout_path)
582 m_gdb_comm.SetSTDOUT (stdout_path);
583 if (stderr_path)
584 m_gdb_comm.SetSTDERR (stderr_path);
585
586 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
587
Greg Claytona4582402011-05-08 04:53:50 +0000588 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000589
590 if (working_dir && working_dir[0])
591 {
592 m_gdb_comm.SetWorkingDir (working_dir);
593 }
594
595 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000596 const Args &environment = launch_info.GetEnvironmentEntries();
597 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000598 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000599 size_t num_environment_entries = environment.GetArgumentCount();
600 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000601 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000602 const char *env_entry = environment.GetArgumentAtIndex(i);
603 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000604 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000605 }
Greg Claytona2f74232011-02-24 22:24:29 +0000606 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000607
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000608 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000609 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000610 if (arg_packet_err == 0)
611 {
612 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000613 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000614 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000615 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000616 }
617 else
618 {
Greg Claytona2f74232011-02-24 22:24:29 +0000619 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000620 }
Greg Claytona2f74232011-02-24 22:24:29 +0000621 }
622 else
623 {
Greg Clayton9c236732011-10-26 00:56:27 +0000624 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000625 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000626
627 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000628
Greg Claytona2f74232011-02-24 22:24:29 +0000629 if (GetID() == LLDB_INVALID_PROCESS_ID)
630 {
Johnny Chenc143d622011-08-09 18:56:45 +0000631 if (log)
632 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000633 KillDebugserverProcess ();
634 return error;
635 }
636
Greg Clayton261a18b2011-06-02 22:22:38 +0000637 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000638 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000639 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000640
641 if (!disable_stdio)
642 {
643 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000644 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000645 }
Chris Lattner24943d22010-06-08 16:52:24 +0000646 }
647 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000648 else
649 {
Johnny Chenc143d622011-08-09 18:56:45 +0000650 if (log)
651 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000652 }
Chris Lattner24943d22010-06-08 16:52:24 +0000653 }
654 else
655 {
656 // Set our user ID to an invalid process ID.
657 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000658 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
659 exe_module->GetFileSpec().GetFilename().AsCString(),
660 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000661 }
Chris Lattner24943d22010-06-08 16:52:24 +0000662 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000663
Chris Lattner24943d22010-06-08 16:52:24 +0000664}
665
666
667Error
Greg Claytone71e2582011-02-04 01:58:07 +0000668ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000669{
670 Error error;
671 // Sleep and wait a bit for debugserver to start to listen...
672 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
673 if (conn_ap.get())
674 {
Chris Lattner24943d22010-06-08 16:52:24 +0000675 const uint32_t max_retry_count = 50;
676 uint32_t retry_count = 0;
677 while (!m_gdb_comm.IsConnected())
678 {
Greg Claytone71e2582011-02-04 01:58:07 +0000679 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000680 {
681 m_gdb_comm.SetConnection (conn_ap.release());
682 break;
683 }
684 retry_count++;
685
686 if (retry_count >= max_retry_count)
687 break;
688
689 usleep (100000);
690 }
691 }
692
693 if (!m_gdb_comm.IsConnected())
694 {
695 if (error.Success())
696 error.SetErrorString("not connected to remote gdb server");
697 return error;
698 }
699
Greg Clayton24bc5d92011-03-30 18:16:51 +0000700 // We always seem to be able to open a connection to a local port
701 // so we need to make sure we can then send data to it. If we can't
702 // then we aren't actually connected to anything, so try and do the
703 // handshake with the remote GDB server and make sure that goes
704 // alright.
705 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000706 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000707 m_gdb_comm.Disconnect();
708 if (error.Success())
709 error.SetErrorString("not connected to remote gdb server");
710 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000711 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000712 m_gdb_comm.ResetDiscoverableSettings();
713 m_gdb_comm.QueryNoAckModeSupported ();
714 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000715 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000716 m_gdb_comm.GetHostInfo ();
717 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000718 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000719
720 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
721 for (size_t idx = 0; idx < num_cmds; idx++)
722 {
723 StringExtractorGDBRemote response;
724 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx));
725 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
726 }
Chris Lattner24943d22010-06-08 16:52:24 +0000727 return error;
728}
729
730void
731ProcessGDBRemote::DidLaunchOrAttach ()
732{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000733 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
734 if (log)
735 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000736 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000737 {
738 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
739
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000740 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000741
Chris Lattner24943d22010-06-08 16:52:24 +0000742 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000743
Greg Claytoncb8977d2011-03-23 00:09:55 +0000744 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
745 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000746 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000747 ArchSpec &target_arch = GetTarget().GetArchitecture();
748
749 if (target_arch.IsValid())
750 {
751 // If the remote host is ARM and we have apple as the vendor, then
752 // ARM executables and shared libraries can have mixed ARM architectures.
753 // You can have an armv6 executable, and if the host is armv7, then the
754 // system will load the best possible architecture for all shared libraries
755 // it has, so we really need to take the remote host architecture as our
756 // defacto architecture in this case.
757
758 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
759 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
760 {
761 target_arch = gdb_remote_arch;
762 }
763 else
764 {
765 // Fill in what is missing in the triple
766 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
767 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000768 if (target_triple.getVendorName().size() == 0)
769 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000770 target_triple.setVendor (remote_triple.getVendor());
771
Greg Clayton2f085c62011-05-15 01:25:55 +0000772 if (target_triple.getOSName().size() == 0)
773 {
774 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000775
Greg Clayton2f085c62011-05-15 01:25:55 +0000776 if (target_triple.getEnvironmentName().size() == 0)
777 target_triple.setEnvironment (remote_triple.getEnvironment());
778 }
779 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000780 }
781 }
782 else
783 {
784 // The target doesn't have a valid architecture yet, set it from
785 // the architecture we got from the remote GDB server
786 target_arch = gdb_remote_arch;
787 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000788 }
Chris Lattner24943d22010-06-08 16:52:24 +0000789 }
790}
791
792void
793ProcessGDBRemote::DidLaunch ()
794{
795 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000796}
797
798Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000799ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000800{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000801 ProcessAttachInfo attach_info;
802 return DoAttachToProcessWithID(attach_pid, attach_info);
803}
804
805Error
806ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
807{
Chris Lattner24943d22010-06-08 16:52:24 +0000808 Error error;
809 // Clear out and clean up from any current state
810 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000811 if (attach_pid != LLDB_INVALID_PROCESS_ID)
812 {
Greg Claytona2f74232011-02-24 22:24:29 +0000813 // Make sure we aren't already connected?
814 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000815 {
Greg Claytona2f74232011-02-24 22:24:29 +0000816 char host_port[128];
817 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
818 char connect_url[128];
819 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000820
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000821 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000822
823 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000824 {
Greg Claytona2f74232011-02-24 22:24:29 +0000825 const char *error_string = error.AsCString();
826 if (error_string == NULL)
827 error_string = "unable to launch " DEBUGSERVER_BASENAME;
828
829 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000830 }
Greg Claytona2f74232011-02-24 22:24:29 +0000831 else
832 {
833 error = ConnectToDebugserver (connect_url);
834 }
835 }
836
837 if (error.Success())
838 {
839 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000840 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000841 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000842 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000843 }
844 }
Chris Lattner24943d22010-06-08 16:52:24 +0000845 return error;
846}
847
848size_t
849ProcessGDBRemote::AttachInputReaderCallback
850(
851 void *baton,
852 InputReader *reader,
853 lldb::InputReaderAction notification,
854 const char *bytes,
855 size_t bytes_len
856)
857{
858 if (notification == eInputReaderGotToken)
859 {
860 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
861 if (gdb_process->m_waiting_for_attach)
862 gdb_process->m_waiting_for_attach = false;
863 reader->SetIsDone(true);
864 return 1;
865 }
866 return 0;
867}
868
869Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000870ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000871{
872 Error error;
873 // Clear out and clean up from any current state
874 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000875
Chris Lattner24943d22010-06-08 16:52:24 +0000876 if (process_name && process_name[0])
877 {
Greg Claytona2f74232011-02-24 22:24:29 +0000878 // Make sure we aren't already connected?
879 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000880 {
Greg Claytona2f74232011-02-24 22:24:29 +0000881 char host_port[128];
882 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
883 char connect_url[128];
884 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
885
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000886 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000887 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000888 {
Greg Claytona2f74232011-02-24 22:24:29 +0000889 const char *error_string = error.AsCString();
890 if (error_string == NULL)
891 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000892
Greg Claytona2f74232011-02-24 22:24:29 +0000893 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000894 }
Greg Claytona2f74232011-02-24 22:24:29 +0000895 else
896 {
897 error = ConnectToDebugserver (connect_url);
898 }
899 }
900
901 if (error.Success())
902 {
903 StreamString packet;
904
905 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +0000906 {
907 if (!m_gdb_comm.GetVAttachOrWaitSupported())
908 {
909 packet.PutCString ("vAttachWait");
910 }
911 else
912 {
913 if (attach_info.GetIgnoreExisting())
914 packet.PutCString("vAttachWait");
915 else
916 packet.PutCString ("vAttachOrWait");
917 }
918 }
Greg Claytona2f74232011-02-24 22:24:29 +0000919 else
920 packet.PutCString("vAttachName");
921 packet.PutChar(';');
922 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
923
924 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
925
Chris Lattner24943d22010-06-08 16:52:24 +0000926 }
927 }
Chris Lattner24943d22010-06-08 16:52:24 +0000928 return error;
929}
930
Chris Lattner24943d22010-06-08 16:52:24 +0000931
932void
933ProcessGDBRemote::DidAttach ()
934{
Greg Claytone71e2582011-02-04 01:58:07 +0000935 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000936}
937
938Error
939ProcessGDBRemote::WillResume ()
940{
Greg Claytonc1f45872011-02-12 06:28:37 +0000941 m_continue_c_tids.clear();
942 m_continue_C_tids.clear();
943 m_continue_s_tids.clear();
944 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000945 return Error();
946}
947
948Error
949ProcessGDBRemote::DoResume ()
950{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000951 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000952 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
953 if (log)
954 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000955
956 Listener listener ("gdb-remote.resume-packet-sent");
957 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
958 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000959 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
960
Greg Claytonc1f45872011-02-12 06:28:37 +0000961 StreamString continue_packet;
962 bool continue_packet_error = false;
963 if (m_gdb_comm.HasAnyVContSupport ())
964 {
965 continue_packet.PutCString ("vCont");
966
967 if (!m_continue_c_tids.empty())
968 {
969 if (m_gdb_comm.GetVContSupported ('c'))
970 {
971 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 +0000972 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000973 }
974 else
975 continue_packet_error = true;
976 }
977
978 if (!continue_packet_error && !m_continue_C_tids.empty())
979 {
980 if (m_gdb_comm.GetVContSupported ('C'))
981 {
982 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 +0000983 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000984 }
985 else
986 continue_packet_error = true;
987 }
Greg Claytonb749a262010-12-03 06:02:24 +0000988
Greg Claytonc1f45872011-02-12 06:28:37 +0000989 if (!continue_packet_error && !m_continue_s_tids.empty())
990 {
991 if (m_gdb_comm.GetVContSupported ('s'))
992 {
993 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 +0000994 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000995 }
996 else
997 continue_packet_error = true;
998 }
999
1000 if (!continue_packet_error && !m_continue_S_tids.empty())
1001 {
1002 if (m_gdb_comm.GetVContSupported ('S'))
1003 {
1004 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 +00001005 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001006 }
1007 else
1008 continue_packet_error = true;
1009 }
1010
1011 if (continue_packet_error)
1012 continue_packet.GetString().clear();
1013 }
1014 else
1015 continue_packet_error = true;
1016
1017 if (continue_packet_error)
1018 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001019 // Either no vCont support, or we tried to use part of the vCont
1020 // packet that wasn't supported by the remote GDB server.
1021 // We need to try and make a simple packet that can do our continue
1022 const size_t num_threads = GetThreadList().GetSize();
1023 const size_t num_continue_c_tids = m_continue_c_tids.size();
1024 const size_t num_continue_C_tids = m_continue_C_tids.size();
1025 const size_t num_continue_s_tids = m_continue_s_tids.size();
1026 const size_t num_continue_S_tids = m_continue_S_tids.size();
1027 if (num_continue_c_tids > 0)
1028 {
1029 if (num_continue_c_tids == num_threads)
1030 {
1031 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001032 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001033 continue_packet.PutChar ('c');
1034 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001035 }
1036 else if (num_continue_c_tids == 1 &&
1037 num_continue_C_tids == 0 &&
1038 num_continue_s_tids == 0 &&
1039 num_continue_S_tids == 0 )
1040 {
1041 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001042 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001043 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001044 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001045 }
1046 }
1047
Greg Claytonde1dd812011-06-24 03:21:43 +00001048 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001049 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001050 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1051 num_continue_C_tids > 0 &&
1052 num_continue_s_tids == 0 &&
1053 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001054 {
1055 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001056 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001057 if (num_continue_C_tids > 1)
1058 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001059 // More that one thread with a signal, yet we don't have
1060 // vCont support and we are being asked to resume each
1061 // thread with a signal, we need to make sure they are
1062 // all the same signal, or we can't issue the continue
1063 // accurately with the current support...
1064 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001065 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001066 continue_packet_error = false;
1067 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1068 {
1069 if (m_continue_C_tids[i].second != continue_signo)
1070 continue_packet_error = true;
1071 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001072 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001073 if (!continue_packet_error)
1074 m_gdb_comm.SetCurrentThreadForRun (-1);
1075 }
1076 else
1077 {
1078 // Set the continue thread ID
1079 continue_packet_error = false;
1080 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001081 }
1082 if (!continue_packet_error)
1083 {
1084 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001085 continue_packet.Printf("C%2.2x", continue_signo);
1086 }
1087 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001088 }
1089
Greg Claytonde1dd812011-06-24 03:21:43 +00001090 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001091 {
1092 if (num_continue_s_tids == num_threads)
1093 {
1094 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001095 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001096 continue_packet.PutChar ('s');
1097 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001098 }
1099 else if (num_continue_c_tids == 0 &&
1100 num_continue_C_tids == 0 &&
1101 num_continue_s_tids == 1 &&
1102 num_continue_S_tids == 0 )
1103 {
1104 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001105 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001106 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001107 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001108 }
1109 }
1110
1111 if (!continue_packet_error && num_continue_S_tids > 0)
1112 {
1113 if (num_continue_S_tids == num_threads)
1114 {
1115 const int step_signo = m_continue_S_tids.front().second;
1116 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001117 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001118 if (num_continue_S_tids > 1)
1119 {
1120 for (size_t i=1; i<num_threads; ++i)
1121 {
1122 if (m_continue_S_tids[i].second != step_signo)
1123 continue_packet_error = true;
1124 }
1125 }
1126 if (!continue_packet_error)
1127 {
1128 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001129 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001130 continue_packet.Printf("S%2.2x", step_signo);
1131 }
1132 }
1133 else if (num_continue_c_tids == 0 &&
1134 num_continue_C_tids == 0 &&
1135 num_continue_s_tids == 0 &&
1136 num_continue_S_tids == 1 )
1137 {
1138 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001139 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001140 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001141 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001142 }
1143 }
1144 }
1145
1146 if (continue_packet_error)
1147 {
1148 error.SetErrorString ("can't make continue packet for this resume");
1149 }
1150 else
1151 {
1152 EventSP event_sp;
1153 TimeValue timeout;
1154 timeout = TimeValue::Now();
1155 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001156 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1157 {
1158 error.SetErrorString ("Trying to resume but the async thread is dead.");
1159 if (log)
1160 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1161 return error;
1162 }
1163
Greg Claytonc1f45872011-02-12 06:28:37 +00001164 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1165
1166 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001167 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001168 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001169 if (log)
1170 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1171 }
1172 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1173 {
1174 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1175 if (log)
1176 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1177 return error;
1178 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001179 }
Greg Claytonb749a262010-12-03 06:02:24 +00001180 }
1181
Jim Ingham3ae449a2010-11-17 02:32:00 +00001182 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001183}
1184
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001185void
1186ProcessGDBRemote::ClearThreadIDList ()
1187{
Greg Claytonff3448e2012-04-13 02:11:32 +00001188 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001189 m_thread_ids.clear();
1190}
1191
1192bool
1193ProcessGDBRemote::UpdateThreadIDList ()
1194{
Greg Claytonff3448e2012-04-13 02:11:32 +00001195 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001196 bool sequence_mutex_unavailable = false;
1197 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1198 if (sequence_mutex_unavailable)
1199 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001200 return false; // We just didn't get the list
1201 }
1202 return true;
1203}
1204
Greg Claytonae932352012-04-10 00:18:59 +00001205bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001206ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001207{
1208 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001209 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001210 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001211 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001212
1213 size_t num_thread_ids = m_thread_ids.size();
1214 // The "m_thread_ids" thread ID list should always be updated after each stop
1215 // reply packet, but in case it isn't, update it here.
1216 if (num_thread_ids == 0)
1217 {
1218 if (!UpdateThreadIDList ())
1219 return false;
1220 num_thread_ids = m_thread_ids.size();
1221 }
Chris Lattner24943d22010-06-08 16:52:24 +00001222
Greg Clayton37f962e2011-08-22 02:49:39 +00001223 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001224 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001225 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001226 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001227 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001228 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1229 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001230 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001231 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001232 }
Chris Lattner24943d22010-06-08 16:52:24 +00001233 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001234
Greg Claytonae932352012-04-10 00:18:59 +00001235 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001236}
1237
1238
1239StateType
1240ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1241{
Greg Clayton261a18b2011-06-02 22:22:38 +00001242 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001243 const char stop_type = stop_packet.GetChar();
1244 switch (stop_type)
1245 {
1246 case 'T':
1247 case 'S':
1248 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001249 if (GetStopID() == 0)
1250 {
1251 // Our first stop, make sure we have a process ID, and also make
1252 // sure we know about our registers
1253 if (GetID() == LLDB_INVALID_PROCESS_ID)
1254 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001255 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001256 if (pid != LLDB_INVALID_PROCESS_ID)
1257 SetID (pid);
1258 }
1259 BuildDynamicRegisterInfo (true);
1260 }
Chris Lattner24943d22010-06-08 16:52:24 +00001261 // Stop with signal and thread info
1262 const uint8_t signo = stop_packet.GetHexU8();
1263 std::string name;
1264 std::string value;
1265 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001266 std::string reason;
1267 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001268 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001269 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001270 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001271 ThreadSP thread_sp;
1272
Chris Lattner24943d22010-06-08 16:52:24 +00001273 while (stop_packet.GetNameColonValue(name, value))
1274 {
1275 if (name.compare("metype") == 0)
1276 {
1277 // exception type in big endian hex
1278 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1279 }
Chris Lattner24943d22010-06-08 16:52:24 +00001280 else if (name.compare("medata") == 0)
1281 {
1282 // exception data in big endian hex
1283 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1284 }
1285 else if (name.compare("thread") == 0)
1286 {
1287 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001288 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001289 // m_thread_list does have its own mutex, but we need to
1290 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1291 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001292 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001293 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001294 if (!thread_sp)
1295 {
1296 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001297 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001298 m_thread_list.AddThread(thread_sp);
1299 }
Chris Lattner24943d22010-06-08 16:52:24 +00001300 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001301 else if (name.compare("threads") == 0)
1302 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001303 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001304 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001305 // A comma separated list of all threads in the current
1306 // process that includes the thread for this stop reply
1307 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001308 size_t comma_pos;
1309 lldb::tid_t tid;
1310 while ((comma_pos = value.find(',')) != std::string::npos)
1311 {
1312 value[comma_pos] = '\0';
1313 // thread in big endian hex
1314 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1315 if (tid != LLDB_INVALID_THREAD_ID)
1316 m_thread_ids.push_back (tid);
1317 value.erase(0, comma_pos + 1);
1318
1319 }
1320 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1321 if (tid != LLDB_INVALID_THREAD_ID)
1322 m_thread_ids.push_back (tid);
1323 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001324 else if (name.compare("hexname") == 0)
1325 {
1326 StringExtractor name_extractor;
1327 // Swap "value" over into "name_extractor"
1328 name_extractor.GetStringRef().swap(value);
1329 // Now convert the HEX bytes into a string value
1330 name_extractor.GetHexByteString (value);
1331 thread_name.swap (value);
1332 }
Chris Lattner24943d22010-06-08 16:52:24 +00001333 else if (name.compare("name") == 0)
1334 {
1335 thread_name.swap (value);
1336 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001337 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001338 {
1339 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1340 }
Greg Clayton65611552011-06-04 01:26:29 +00001341 else if (name.compare("reason") == 0)
1342 {
1343 reason.swap(value);
1344 }
1345 else if (name.compare("description") == 0)
1346 {
1347 StringExtractor desc_extractor;
1348 // Swap "value" over into "name_extractor"
1349 desc_extractor.GetStringRef().swap(value);
1350 // Now convert the HEX bytes into a string value
1351 desc_extractor.GetHexByteString (thread_name);
1352 }
Greg Claytona875b642011-01-09 21:07:35 +00001353 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1354 {
1355 // We have a register number that contains an expedited
1356 // register value. Lets supply this register to our thread
1357 // so it won't have to go and read it.
1358 if (thread_sp)
1359 {
1360 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1361
1362 if (reg != UINT32_MAX)
1363 {
1364 StringExtractor reg_value_extractor;
1365 // Swap "value" over into "reg_value_extractor"
1366 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001367 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1368 {
1369 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1370 name.c_str(),
1371 reg,
1372 reg,
1373 reg_value_extractor.GetStringRef().c_str(),
1374 stop_packet.GetStringRef().c_str());
1375 }
Greg Claytona875b642011-01-09 21:07:35 +00001376 }
1377 }
1378 }
Chris Lattner24943d22010-06-08 16:52:24 +00001379 }
Chris Lattner24943d22010-06-08 16:52:24 +00001380
1381 if (thread_sp)
1382 {
1383 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1384
1385 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001386 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001387 if (exc_type != 0)
1388 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001389 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001390
1391 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1392 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001393 exc_data_size,
1394 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001395 exc_data_size >= 2 ? exc_data[1] : 0,
1396 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001397 }
Greg Clayton65611552011-06-04 01:26:29 +00001398 else
Chris Lattner24943d22010-06-08 16:52:24 +00001399 {
Greg Clayton65611552011-06-04 01:26:29 +00001400 bool handled = false;
1401 if (!reason.empty())
1402 {
1403 if (reason.compare("trace") == 0)
1404 {
1405 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1406 handled = true;
1407 }
1408 else if (reason.compare("breakpoint") == 0)
1409 {
1410 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001411 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001412 if (bp_site_sp)
1413 {
1414 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1415 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1416 // 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 +00001417 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001418 if (bp_site_sp->ValidForThisThread (gdb_thread))
1419 {
1420 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001421 }
1422 else
1423 {
1424 StopInfoSP invalid_stop_info_sp;
1425 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001426 }
1427 }
1428
Greg Clayton65611552011-06-04 01:26:29 +00001429 }
1430 else if (reason.compare("trap") == 0)
1431 {
1432 // Let the trap just use the standard signal stop reason below...
1433 }
1434 else if (reason.compare("watchpoint") == 0)
1435 {
1436 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1437 // TODO: locate the watchpoint somehow...
1438 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1439 handled = true;
1440 }
1441 else if (reason.compare("exception") == 0)
1442 {
1443 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1444 handled = true;
1445 }
1446 }
1447
1448 if (signo)
1449 {
1450 if (signo == SIGTRAP)
1451 {
1452 // Currently we are going to assume SIGTRAP means we are either
1453 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001454 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001455 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001456 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001457
Greg Clayton65611552011-06-04 01:26:29 +00001458 if (bp_site_sp)
1459 {
1460 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1461 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1462 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1463 if (bp_site_sp->ValidForThisThread (gdb_thread))
1464 {
1465 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001466 }
1467 else
1468 {
1469 StopInfoSP invalid_stop_info_sp;
1470 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001471 }
1472 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001473 else
Greg Clayton65611552011-06-04 01:26:29 +00001474 {
1475 // TODO: check for breakpoint or trap opcode in case there is a hard
1476 // coded software trap
1477 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton65611552011-06-04 01:26:29 +00001478 }
1479 }
1480 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001481 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001482 }
1483 else
1484 {
Greg Clayton643ee732010-08-04 01:40:35 +00001485 StopInfoSP invalid_stop_info_sp;
1486 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001487 }
Greg Clayton65611552011-06-04 01:26:29 +00001488
1489 if (!description.empty())
1490 {
1491 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1492 if (stop_info_sp)
1493 {
1494 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001495 }
Greg Clayton65611552011-06-04 01:26:29 +00001496 else
1497 {
1498 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1499 }
1500 }
1501 }
Chris Lattner24943d22010-06-08 16:52:24 +00001502 }
1503 return eStateStopped;
1504 }
1505 break;
1506
1507 case 'W':
1508 // process exited
1509 return eStateExited;
1510
1511 default:
1512 break;
1513 }
1514 return eStateInvalid;
1515}
1516
1517void
1518ProcessGDBRemote::RefreshStateAfterStop ()
1519{
Greg Claytonff3448e2012-04-13 02:11:32 +00001520 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001521 m_thread_ids.clear();
1522 // Set the thread stop info. It might have a "threads" key whose value is
1523 // a list of all thread IDs in the current process, so m_thread_ids might
1524 // get set.
1525 SetThreadStopInfo (m_last_stop_packet);
1526 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1527 if (m_thread_ids.empty())
1528 {
1529 // No, we need to fetch the thread list manually
1530 UpdateThreadIDList();
1531 }
1532
Chris Lattner24943d22010-06-08 16:52:24 +00001533 // Let all threads recover from stopping and do any clean up based
1534 // on the previous thread state (if any).
1535 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001536
Chris Lattner24943d22010-06-08 16:52:24 +00001537}
1538
1539Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001540ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001541{
1542 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001543
Greg Claytona4881d02011-01-22 07:12:45 +00001544 bool timed_out = false;
1545 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001546
1547 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001548 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001549 // We are being asked to halt during an attach. We need to just close
1550 // our file handle and debugserver will go away, and we can be done...
1551 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001552 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001553 else
1554 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001555 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001556 {
1557 if (timed_out)
1558 error.SetErrorString("timed out sending interrupt packet");
1559 else
1560 error.SetErrorString("unknown error sending interrupt packet");
1561 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001562
1563 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001564 }
Chris Lattner24943d22010-06-08 16:52:24 +00001565 return error;
1566}
1567
1568Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001569ProcessGDBRemote::InterruptIfRunning
1570(
1571 bool discard_thread_plans,
1572 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001573 EventSP &stop_event_sp
1574)
Chris Lattner24943d22010-06-08 16:52:24 +00001575{
1576 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001577
Greg Clayton2860ba92011-01-23 19:58:49 +00001578 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1579
Greg Clayton68ca8232011-01-25 02:58:48 +00001580 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001581 const bool is_running = m_gdb_comm.IsRunning();
1582 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001583 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001584 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001585 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001586 is_running);
1587
Greg Clayton2860ba92011-01-23 19:58:49 +00001588 if (discard_thread_plans)
1589 {
1590 if (log)
1591 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1592 m_thread_list.DiscardThreadPlans();
1593 }
1594 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001595 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001596 if (catch_stop_event)
1597 {
1598 if (log)
1599 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1600 PausePrivateStateThread();
1601 paused_private_state_thread = true;
1602 }
1603
Greg Clayton4fb400f2010-09-27 21:07:38 +00001604 bool timed_out = false;
1605 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001606
Greg Clayton05e4d972012-03-29 01:55:41 +00001607 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001608 {
1609 if (timed_out)
1610 error.SetErrorString("timed out sending interrupt packet");
1611 else
1612 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001613 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001614 ResumePrivateStateThread();
1615 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001616 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001617
Greg Clayton72e1c782011-01-22 23:43:18 +00001618 if (catch_stop_event)
1619 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001620 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001621 TimeValue timeout_time;
1622 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001623 timeout_time.OffsetWithSeconds(5);
1624 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001625
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001626 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001627 if (log)
1628 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001629
Greg Clayton2860ba92011-01-23 19:58:49 +00001630 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001631 error.SetErrorString("unable to verify target stopped");
1632 }
1633
Greg Clayton68ca8232011-01-25 02:58:48 +00001634 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001635 {
1636 if (log)
1637 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001638 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001639 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001640 }
Chris Lattner24943d22010-06-08 16:52:24 +00001641 return error;
1642}
1643
Greg Clayton4fb400f2010-09-27 21:07:38 +00001644Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001645ProcessGDBRemote::WillDetach ()
1646{
Greg Clayton2860ba92011-01-23 19:58:49 +00001647 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1648 if (log)
1649 log->Printf ("ProcessGDBRemote::WillDetach()");
1650
Greg Clayton72e1c782011-01-22 23:43:18 +00001651 bool discard_thread_plans = true;
1652 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001653 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001654
1655 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1656 // needed. This shouldn't be a feature of a particular plugin.
1657
Greg Clayton68ca8232011-01-25 02:58:48 +00001658 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001659}
1660
1661Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001662ProcessGDBRemote::DoDetach()
1663{
1664 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001665 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001666 if (log)
1667 log->Printf ("ProcessGDBRemote::DoDetach()");
1668
1669 DisableAllBreakpointSites ();
1670
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001671 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001672
Greg Clayton516f0842012-04-11 00:24:49 +00001673 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001674 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001675 {
Greg Clayton516f0842012-04-11 00:24:49 +00001676 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001677 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1678 else
1679 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001680 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001681 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001682 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001683
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001684 SetPrivateState (eStateDetached);
1685 ResumePrivateStateThread();
1686
1687 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001688 return error;
1689}
Chris Lattner24943d22010-06-08 16:52:24 +00001690
Jim Ingham06b84492012-07-04 00:35:43 +00001691
Chris Lattner24943d22010-06-08 16:52:24 +00001692Error
1693ProcessGDBRemote::DoDestroy ()
1694{
1695 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001696 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001697 if (log)
1698 log->Printf ("ProcessGDBRemote::DoDestroy()");
1699
Jim Ingham06b84492012-07-04 00:35:43 +00001700 // There is a bug in older iOS debugservers where they don't shut down the process
1701 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1702 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1703 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1704 // destroy it again.
1705 //
1706 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1707 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1708 // the debugservers with this bug are equal. There really should be a better way to test this!
1709 //
1710 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1711 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1712 // just do the straight-forward kill.
1713 //
1714 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1715 // necessary (or helpful) to do any of this.
1716
1717 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1718 {
1719 PlatformSP platform_sp = GetTarget().GetPlatform();
1720
1721 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1722 if (platform_sp
1723 && platform_sp->GetName()
1724 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1725 {
1726 if (m_destroy_tried_resuming)
1727 {
1728 if (log)
1729 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1730 }
1731 else
1732 {
1733 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1734 // but we really need it to happen here and it doesn't matter if we do it twice.
1735 m_thread_list.DiscardThreadPlans();
1736 DisableAllBreakpointSites();
1737
1738 bool stop_looks_like_crash = false;
1739 ThreadList &threads = GetThreadList();
1740
1741 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001742 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001743
1744 size_t num_threads = threads.GetSize();
1745 for (size_t i = 0; i < num_threads; i++)
1746 {
1747 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1748 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1749 StopReason reason = eStopReasonInvalid;
1750 if (stop_info_sp)
1751 reason = stop_info_sp->GetStopReason();
1752 if (reason == eStopReasonBreakpoint
1753 || reason == eStopReasonException)
1754 {
1755 if (log)
1756 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1757 thread_sp->GetID(),
1758 stop_info_sp->GetDescription());
1759 stop_looks_like_crash = true;
1760 break;
1761 }
1762 }
1763 }
1764
1765 if (stop_looks_like_crash)
1766 {
1767 if (log)
1768 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1769 m_destroy_tried_resuming = true;
1770
1771 // If we are going to run again before killing, it would be good to suspend all the threads
1772 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1773 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1774 // have to run the risk of letting those threads proceed a bit.
1775
1776 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001777 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001778
1779 size_t num_threads = threads.GetSize();
1780 for (size_t i = 0; i < num_threads; i++)
1781 {
1782 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1783 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1784 StopReason reason = eStopReasonInvalid;
1785 if (stop_info_sp)
1786 reason = stop_info_sp->GetStopReason();
1787 if (reason != eStopReasonBreakpoint
1788 && reason != eStopReasonException)
1789 {
1790 if (log)
1791 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1792 thread_sp->GetID());
1793 thread_sp->SetResumeState(eStateSuspended);
1794 }
1795 }
1796 }
1797 Resume ();
1798 return Destroy();
1799 }
1800 }
1801 }
1802 }
1803
Chris Lattner24943d22010-06-08 16:52:24 +00001804 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001805 int exit_status = SIGABRT;
1806 std::string exit_string;
1807
Greg Claytona4881d02011-01-22 07:12:45 +00001808 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001809 {
Jim Ingham8226e942011-10-28 01:11:35 +00001810 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001811 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001812
1813 StringExtractorGDBRemote response;
1814 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001815 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1816
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001817 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001818 {
1819 char packet_cmd = response.GetChar(0);
1820
1821 if (packet_cmd == 'W' || packet_cmd == 'X')
1822 {
Greg Clayton06709002011-12-06 04:51:14 +00001823 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001824 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001825 exit_status = response.GetHexU8();
1826 }
1827 else
1828 {
1829 if (log)
1830 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1831 exit_string.assign("got unexpected response to k packet: ");
1832 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001833 }
1834 }
1835 else
1836 {
Jim Ingham8247e622012-06-06 00:32:39 +00001837 if (log)
1838 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1839 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001840 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001841
1842 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00001843 }
Jim Ingham8247e622012-06-06 00:32:39 +00001844 else
1845 {
1846 if (log)
1847 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00001848 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00001849 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001850 }
Jim Ingham8247e622012-06-06 00:32:39 +00001851 else
1852 {
1853 // If we missed setting the exit status on the way out, do it here.
1854 // NB set exit status can be called multiple times, the first one sets the status.
1855 exit_string.assign("destroying when not connected to debugserver");
1856 }
1857
1858 SetExitStatus(exit_status, exit_string.c_str());
1859
Chris Lattner24943d22010-06-08 16:52:24 +00001860 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001861 KillDebugserverProcess ();
1862 return error;
1863}
1864
Chris Lattner24943d22010-06-08 16:52:24 +00001865//------------------------------------------------------------------
1866// Process Queries
1867//------------------------------------------------------------------
1868
1869bool
1870ProcessGDBRemote::IsAlive ()
1871{
Greg Clayton58e844b2010-12-08 05:08:21 +00001872 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001873}
1874
1875addr_t
1876ProcessGDBRemote::GetImageInfoAddress()
1877{
Greg Clayton516f0842012-04-11 00:24:49 +00001878 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001879}
1880
Chris Lattner24943d22010-06-08 16:52:24 +00001881//------------------------------------------------------------------
1882// Process Memory
1883//------------------------------------------------------------------
1884size_t
1885ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1886{
1887 if (size > m_max_memory_size)
1888 {
1889 // Keep memory read sizes down to a sane limit. This function will be
1890 // called multiple times in order to complete the task by
1891 // lldb_private::Process so it is ok to do this.
1892 size = m_max_memory_size;
1893 }
1894
1895 char packet[64];
Greg Clayton851e30e2012-09-18 18:04:04 +00001896 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%llx", (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00001897 assert (packet_len + 1 < sizeof(packet));
1898 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001899 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001900 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001901 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001902 {
1903 error.Clear();
1904 return response.GetHexBytes(buf, size, '\xdd');
1905 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001906 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00001907 error.SetErrorString("memory read failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00001908 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00001909 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00001910 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00001911 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001912 }
1913 else
1914 {
1915 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1916 }
1917 return 0;
1918}
1919
1920size_t
1921ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1922{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001923 if (size > m_max_memory_size)
1924 {
1925 // Keep memory read sizes down to a sane limit. This function will be
1926 // called multiple times in order to complete the task by
1927 // lldb_private::Process so it is ok to do this.
1928 size = m_max_memory_size;
1929 }
1930
Chris Lattner24943d22010-06-08 16:52:24 +00001931 StreamString packet;
Greg Clayton851e30e2012-09-18 18:04:04 +00001932 packet.Printf("M%llx,%llx:", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00001933 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001934 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001935 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001936 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001937 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001938 {
1939 error.Clear();
1940 return size;
1941 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001942 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00001943 error.SetErrorString("memory write failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00001944 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00001945 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00001946 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00001947 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 +00001948 }
1949 else
1950 {
1951 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1952 }
1953 return 0;
1954}
1955
1956lldb::addr_t
1957ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1958{
Greg Clayton989816b2011-05-14 01:50:35 +00001959 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1960
Greg Clayton2f085c62011-05-15 01:25:55 +00001961 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001962 switch (supported)
1963 {
1964 case eLazyBoolCalculate:
1965 case eLazyBoolYes:
1966 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1967 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1968 return allocated_addr;
1969
1970 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001971 // Call mmap() to create memory in the inferior..
1972 unsigned prot = 0;
1973 if (permissions & lldb::ePermissionsReadable)
1974 prot |= eMmapProtRead;
1975 if (permissions & lldb::ePermissionsWritable)
1976 prot |= eMmapProtWrite;
1977 if (permissions & lldb::ePermissionsExecutable)
1978 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001979
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001980 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1981 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1982 m_addr_to_mmap_size[allocated_addr] = size;
1983 else
1984 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001985 break;
1986 }
1987
Chris Lattner24943d22010-06-08 16:52:24 +00001988 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton851e30e2012-09-18 18:04:04 +00001989 error.SetErrorStringWithFormat("unable to allocate %llu bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001990 else
1991 error.Clear();
1992 return allocated_addr;
1993}
1994
1995Error
Greg Claytona9385532011-11-18 07:03:08 +00001996ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1997 MemoryRegionInfo &region_info)
1998{
1999
2000 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2001 return error;
2002}
2003
2004Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002005ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2006{
2007
2008 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2009 return error;
2010}
2011
2012Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002013ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2014{
2015 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2016 return error;
2017}
2018
2019Error
Chris Lattner24943d22010-06-08 16:52:24 +00002020ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2021{
2022 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002023 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2024
2025 switch (supported)
2026 {
2027 case eLazyBoolCalculate:
2028 // We should never be deallocating memory without allocating memory
2029 // first so we should never get eLazyBoolCalculate
2030 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2031 break;
2032
2033 case eLazyBoolYes:
2034 if (!m_gdb_comm.DeallocateMemory (addr))
2035 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2036 break;
2037
2038 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002039 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002040 {
2041 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002042 if (pos != m_addr_to_mmap_size.end() &&
2043 InferiorCallMunmap(this, addr, pos->second))
2044 m_addr_to_mmap_size.erase (pos);
2045 else
2046 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002047 }
2048 break;
2049 }
2050
Chris Lattner24943d22010-06-08 16:52:24 +00002051 return error;
2052}
2053
2054
2055//------------------------------------------------------------------
2056// Process STDIO
2057//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002058size_t
2059ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2060{
2061 if (m_stdio_communication.IsConnected())
2062 {
2063 ConnectionStatus status;
2064 m_stdio_communication.Write(src, src_len, status, NULL);
2065 }
2066 return 0;
2067}
2068
2069Error
2070ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2071{
2072 Error error;
2073 assert (bp_site != NULL);
2074
Greg Claytone005f2c2010-11-06 01:53:30 +00002075 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002076 user_id_t site_id = bp_site->GetID();
2077 const addr_t addr = bp_site->GetLoadAddress();
2078 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002079 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002080
2081 if (bp_site->IsEnabled())
2082 {
2083 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002084 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 +00002085 return error;
2086 }
2087 else
2088 {
2089 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2090
2091 if (bp_site->HardwarePreferred())
2092 {
2093 // Try and set hardware breakpoint, and if that fails, fall through
2094 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002095 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002096 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002097 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002098 {
2099 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002100 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002101 return error;
2102 }
Chris Lattner24943d22010-06-08 16:52:24 +00002103 }
2104 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002105
2106 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002107 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002108 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2109 {
2110 bp_site->SetEnabled(true);
2111 bp_site->SetType (BreakpointSite::eExternal);
2112 return error;
2113 }
Chris Lattner24943d22010-06-08 16:52:24 +00002114 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002115
2116 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002117 }
2118
2119 if (log)
2120 {
2121 const char *err_string = error.AsCString();
2122 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2123 bp_site->GetLoadAddress(),
2124 err_string ? err_string : "NULL");
2125 }
2126 // We shouldn't reach here on a successful breakpoint enable...
2127 if (error.Success())
2128 error.SetErrorToGenericError();
2129 return error;
2130}
2131
2132Error
2133ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2134{
2135 Error error;
2136 assert (bp_site != NULL);
2137 addr_t addr = bp_site->GetLoadAddress();
2138 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002139 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002140 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002141 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002142
2143 if (bp_site->IsEnabled())
2144 {
2145 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2146
Greg Claytonb72d0f02011-04-12 05:54:46 +00002147 BreakpointSite::Type bp_type = bp_site->GetType();
2148 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002149 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002150 case BreakpointSite::eSoftware:
2151 error = DisableSoftwareBreakpoint (bp_site);
2152 break;
2153
2154 case BreakpointSite::eHardware:
2155 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2156 error.SetErrorToGenericError();
2157 break;
2158
2159 case BreakpointSite::eExternal:
2160 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2161 error.SetErrorToGenericError();
2162 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002163 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002164 if (error.Success())
2165 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002166 }
2167 else
2168 {
2169 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002170 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 +00002171 return error;
2172 }
2173
2174 if (error.Success())
2175 error.SetErrorToGenericError();
2176 return error;
2177}
2178
Johnny Chen21900fb2011-09-06 22:38:36 +00002179// Pre-requisite: wp != NULL.
2180static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002181GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002182{
2183 assert(wp);
2184 bool watch_read = wp->WatchpointRead();
2185 bool watch_write = wp->WatchpointWrite();
2186
2187 // watch_read and watch_write cannot both be false.
2188 assert(watch_read || watch_write);
2189 if (watch_read && watch_write)
2190 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002191 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002192 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002193 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002194 return eWatchpointWrite;
2195}
2196
Chris Lattner24943d22010-06-08 16:52:24 +00002197Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002198ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002199{
2200 Error error;
2201 if (wp)
2202 {
2203 user_id_t watchID = wp->GetID();
2204 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002205 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002206 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002207 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002208 if (wp->IsEnabled())
2209 {
2210 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002211 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002212 return error;
2213 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002214
2215 GDBStoppointType type = GetGDBStoppointType(wp);
2216 // Pass down an appropriate z/Z packet...
2217 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002218 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002219 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2220 {
2221 wp->SetEnabled(true);
2222 return error;
2223 }
2224 else
2225 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002226 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002227 else
2228 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002229 }
2230 else
2231 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002232 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002233 }
2234 if (error.Success())
2235 error.SetErrorToGenericError();
2236 return error;
2237}
2238
2239Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002240ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002241{
2242 Error error;
2243 if (wp)
2244 {
2245 user_id_t watchID = wp->GetID();
2246
Greg Claytone005f2c2010-11-06 01:53:30 +00002247 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002248
2249 addr_t addr = wp->GetLoadAddress();
2250 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002251 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002252
Johnny Chen21900fb2011-09-06 22:38:36 +00002253 if (!wp->IsEnabled())
2254 {
2255 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002256 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002257 // See also 'class WatchpointSentry' within StopInfo.cpp.
2258 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2259 // the watchpoint object to intelligently process this action.
2260 wp->SetEnabled(false);
Johnny Chen21900fb2011-09-06 22:38:36 +00002261 return error;
2262 }
2263
Chris Lattner24943d22010-06-08 16:52:24 +00002264 if (wp->IsHardware())
2265 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002266 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002267 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002268 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2269 {
2270 wp->SetEnabled(false);
2271 return error;
2272 }
2273 else
2274 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002275 }
2276 // TODO: clear software watchpoints if we implement them
2277 }
2278 else
2279 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002280 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002281 }
2282 if (error.Success())
2283 error.SetErrorToGenericError();
2284 return error;
2285}
2286
2287void
2288ProcessGDBRemote::Clear()
2289{
2290 m_flags = 0;
2291 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002292}
2293
2294Error
2295ProcessGDBRemote::DoSignal (int signo)
2296{
2297 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002298 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002299 if (log)
2300 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2301
2302 if (!m_gdb_comm.SendAsyncSignal (signo))
2303 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2304 return error;
2305}
2306
Chris Lattner24943d22010-06-08 16:52:24 +00002307Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002308ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2309{
2310 ProcessLaunchInfo launch_info;
2311 return StartDebugserverProcess(debugserver_url, launch_info);
2312}
2313
2314Error
2315ProcessGDBRemote::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 +00002316{
2317 Error error;
2318 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2319 {
2320 // If we locate debugserver, keep that located version around
2321 static FileSpec g_debugserver_file_spec;
2322
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002323 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002324 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002325 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002326
2327 // Always check to see if we have an environment override for the path
2328 // to the debugserver to use and use it if we do.
2329 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2330 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002331 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002332 else
2333 debugserver_file_spec = g_debugserver_file_spec;
2334 bool debugserver_exists = debugserver_file_spec.Exists();
2335 if (!debugserver_exists)
2336 {
2337 // The debugserver binary is in the LLDB.framework/Resources
2338 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002339 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002340 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002341 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002342 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002343 if (debugserver_exists)
2344 {
2345 g_debugserver_file_spec = debugserver_file_spec;
2346 }
2347 else
2348 {
2349 g_debugserver_file_spec.Clear();
2350 debugserver_file_spec.Clear();
2351 }
Chris Lattner24943d22010-06-08 16:52:24 +00002352 }
2353 }
2354
2355 if (debugserver_exists)
2356 {
2357 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2358
2359 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002360
Greg Claytone005f2c2010-11-06 01:53:30 +00002361 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002362
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002363 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002364 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002365
Chris Lattner24943d22010-06-08 16:52:24 +00002366 // Start args with "debugserver /file/path -r --"
2367 debugserver_args.AppendArgument(debugserver_path);
2368 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002369 // use native registers, not the GDB registers
2370 debugserver_args.AppendArgument("--native-regs");
2371 // make debugserver run in its own session so signals generated by
2372 // special terminal key sequences (^C) don't affect debugserver
2373 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002374
Chris Lattner24943d22010-06-08 16:52:24 +00002375 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2376 if (env_debugserver_log_file)
2377 {
2378 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2379 debugserver_args.AppendArgument(arg_cstr);
2380 }
2381
2382 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2383 if (env_debugserver_log_flags)
2384 {
2385 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2386 debugserver_args.AppendArgument(arg_cstr);
2387 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00002388 debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2389 debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002390
Greg Claytonb72d0f02011-04-12 05:54:46 +00002391 // We currently send down all arguments, attach pids, or attach
2392 // process names in dedicated GDB server packets, so we don't need
2393 // to pass them as arguments. This is currently because of all the
2394 // things we need to setup prior to launching: the environment,
2395 // current working dir, file actions, etc.
2396#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002397 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002398 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002399 {
Greg Claytona2f74232011-02-24 22:24:29 +00002400 // Terminate the debugserver args so we can now append the inferior args
2401 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002402
Greg Claytona2f74232011-02-24 22:24:29 +00002403 for (int i = 0; inferior_argv[i] != NULL; ++i)
2404 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002405 }
2406 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2407 {
2408 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2409 debugserver_args.AppendArgument (arg_cstr);
2410 }
2411 else if (attach_name && attach_name[0])
2412 {
2413 if (wait_for_launch)
2414 debugserver_args.AppendArgument ("--waitfor");
2415 else
2416 debugserver_args.AppendArgument ("--attach");
2417 debugserver_args.AppendArgument (attach_name);
2418 }
Chris Lattner24943d22010-06-08 16:52:24 +00002419#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002420
2421 ProcessLaunchInfo::FileAction file_action;
2422
2423 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2424 // to "/dev/null" if we run into any problems.
2425 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002426 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002427 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002428 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002429 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002430 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002431
2432 if (log)
2433 {
2434 StreamString strm;
2435 debugserver_args.Dump (&strm);
2436 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2437 }
2438
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002439 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2440 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002441
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002442 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002443
Greg Claytonb72d0f02011-04-12 05:54:46 +00002444 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002445 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002446 else
Chris Lattner24943d22010-06-08 16:52:24 +00002447 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2448
2449 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002450 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002451 }
2452 else
2453 {
Greg Clayton9c236732011-10-26 00:56:27 +00002454 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002455 }
2456
2457 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2458 StartAsyncThread ();
2459 }
2460 return error;
2461}
2462
2463bool
2464ProcessGDBRemote::MonitorDebugserverProcess
2465(
2466 void *callback_baton,
2467 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002468 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002469 int signo, // Zero for no signal
2470 int exit_status // Exit value of process if signal is zero
2471)
2472{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002473 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2474 // and might not exist anymore, so we need to carefully try to get the
2475 // target for this process first since we have a race condition when
2476 // we are done running between getting the notice that the inferior
2477 // process has died and the debugserver that was debugging this process.
2478 // In our test suite, we are also continually running process after
2479 // process, so we must be very careful to make sure:
2480 // 1 - process object hasn't been deleted already
2481 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002482
2483 // "debugserver_pid" argument passed in is the process ID for
2484 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002485 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002486
Greg Clayton75ccf502010-08-21 02:22:51 +00002487 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002488
Greg Clayton1c4642c2011-11-16 05:37:56 +00002489 // Get a shared pointer to the target that has a matching process pointer.
2490 // This target could be gone, or the target could already have a new process
2491 // object inside of it
2492 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2493
Greg Clayton72e1c782011-01-22 23:43:18 +00002494 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002495 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 +00002496
Greg Clayton1c4642c2011-11-16 05:37:56 +00002497 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002498 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002499 // We found a process in a target that matches, but another thread
2500 // might be in the process of launching a new process that will
2501 // soon replace it, so get a shared pointer to the process so we
2502 // can keep it alive.
2503 ProcessSP process_sp (target_sp->GetProcessSP());
2504 // Now we have a shared pointer to the process that can't go away on us
2505 // so we now make sure it was the same as the one passed in, and also make
2506 // sure that our previous "process *" didn't get deleted and have a new
2507 // "process *" created in its place with the same pointer. To verify this
2508 // we make sure the process has our debugserver process ID. If we pass all
2509 // of these tests, then we are sure that this process is the one we were
2510 // looking for.
2511 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002512 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002513 // Sleep for a half a second to make sure our inferior process has
2514 // time to set its exit status before we set it incorrectly when
2515 // both the debugserver and the inferior process shut down.
2516 usleep (500000);
2517 // If our process hasn't yet exited, debugserver might have died.
2518 // If the process did exit, the we are reaping it.
2519 const StateType state = process->GetState();
2520
2521 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2522 state != eStateInvalid &&
2523 state != eStateUnloaded &&
2524 state != eStateExited &&
2525 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002526 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002527 char error_str[1024];
2528 if (signo)
2529 {
2530 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2531 if (signal_cstr)
2532 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2533 else
2534 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2535 }
Chris Lattner24943d22010-06-08 16:52:24 +00002536 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002537 {
2538 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2539 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002540
Greg Clayton1c4642c2011-11-16 05:37:56 +00002541 process->SetExitStatus (-1, error_str);
2542 }
2543 // Debugserver has exited we need to let our ProcessGDBRemote
2544 // know that it no longer has a debugserver instance
2545 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002546 }
Chris Lattner24943d22010-06-08 16:52:24 +00002547 }
2548 return true;
2549}
2550
2551void
2552ProcessGDBRemote::KillDebugserverProcess ()
2553{
2554 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2555 {
2556 ::kill (m_debugserver_pid, SIGINT);
2557 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2558 }
2559}
2560
2561void
2562ProcessGDBRemote::Initialize()
2563{
2564 static bool g_initialized = false;
2565
2566 if (g_initialized == false)
2567 {
2568 g_initialized = true;
2569 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2570 GetPluginDescriptionStatic(),
2571 CreateInstance);
2572
2573 Log::Callbacks log_callbacks = {
2574 ProcessGDBRemoteLog::DisableLog,
2575 ProcessGDBRemoteLog::EnableLog,
2576 ProcessGDBRemoteLog::ListLogCategories
2577 };
2578
2579 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2580 }
2581}
2582
2583bool
Chris Lattner24943d22010-06-08 16:52:24 +00002584ProcessGDBRemote::StartAsyncThread ()
2585{
Greg Claytone005f2c2010-11-06 01:53:30 +00002586 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002587
2588 if (log)
2589 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2590
2591 // Create a thread that watches our internal state and controls which
2592 // events make it to clients (into the DCProcess event queue).
2593 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002594 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002595}
2596
2597void
2598ProcessGDBRemote::StopAsyncThread ()
2599{
Greg Claytone005f2c2010-11-06 01:53:30 +00002600 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002601
2602 if (log)
2603 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2604
2605 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002606
2607 // This will shut down the async thread.
2608 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002609
2610 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002611 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002612 {
2613 Host::ThreadJoin (m_async_thread, NULL, NULL);
2614 }
2615}
2616
2617
2618void *
2619ProcessGDBRemote::AsyncThread (void *arg)
2620{
2621 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2622
Greg Claytone005f2c2010-11-06 01:53:30 +00002623 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002624 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002625 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002626
2627 Listener listener ("ProcessGDBRemote::AsyncThread");
2628 EventSP event_sp;
2629 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2630 eBroadcastBitAsyncThreadShouldExit;
2631
2632 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2633 {
Greg Claytona2f74232011-02-24 22:24:29 +00002634 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2635
Chris Lattner24943d22010-06-08 16:52:24 +00002636 bool done = false;
2637 while (!done)
2638 {
2639 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002640 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002641 if (listener.WaitForEvent (NULL, event_sp))
2642 {
2643 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002644 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002645 {
Greg Claytona2f74232011-02-24 22:24:29 +00002646 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002647 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 +00002648
Greg Claytona2f74232011-02-24 22:24:29 +00002649 switch (event_type)
2650 {
2651 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002652 {
Greg Claytona2f74232011-02-24 22:24:29 +00002653 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002654
Greg Claytona2f74232011-02-24 22:24:29 +00002655 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002656 {
Greg Claytona2f74232011-02-24 22:24:29 +00002657 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2658 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2659 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002660 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002661
Greg Claytona2f74232011-02-24 22:24:29 +00002662 if (::strstr (continue_cstr, "vAttach") == NULL)
2663 process->SetPrivateState(eStateRunning);
2664 StringExtractorGDBRemote response;
2665 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002666
Greg Clayton67b402c2012-05-16 02:48:06 +00002667 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2668 // The thread ID list might be contained within the "response", or the stop reply packet that
2669 // caused the stop. So clear it now before we give the stop reply packet to the process
2670 // using the process->SetLastStopPacket()...
2671 process->ClearThreadIDList ();
2672
Greg Claytona2f74232011-02-24 22:24:29 +00002673 switch (stop_state)
2674 {
2675 case eStateStopped:
2676 case eStateCrashed:
2677 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002678 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002679 process->SetPrivateState (stop_state);
2680 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002681
Greg Claytona2f74232011-02-24 22:24:29 +00002682 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002683 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002684 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002685 response.SetFilePos(1);
2686 process->SetExitStatus(response.GetHexU8(), NULL);
2687 done = true;
2688 break;
2689
2690 case eStateInvalid:
2691 process->SetExitStatus(-1, "lost connection");
2692 break;
2693
2694 default:
2695 process->SetPrivateState (stop_state);
2696 break;
2697 }
Chris Lattner24943d22010-06-08 16:52:24 +00002698 }
2699 }
Greg Claytona2f74232011-02-24 22:24:29 +00002700 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002701
Greg Claytona2f74232011-02-24 22:24:29 +00002702 case eBroadcastBitAsyncThreadShouldExit:
2703 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002704 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002705 done = true;
2706 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002707
Greg Claytona2f74232011-02-24 22:24:29 +00002708 default:
2709 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002710 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 +00002711 done = true;
2712 break;
2713 }
2714 }
2715 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2716 {
2717 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2718 {
2719 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002720 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002721 }
Chris Lattner24943d22010-06-08 16:52:24 +00002722 }
2723 }
2724 else
2725 {
2726 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002727 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 +00002728 done = true;
2729 }
2730 }
2731 }
2732
2733 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002734 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002735
2736 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2737 return NULL;
2738}
2739
Chris Lattner24943d22010-06-08 16:52:24 +00002740const char *
2741ProcessGDBRemote::GetDispatchQueueNameForThread
2742(
2743 addr_t thread_dispatch_qaddr,
2744 std::string &dispatch_queue_name
2745)
2746{
2747 dispatch_queue_name.clear();
2748 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2749 {
2750 // Cache the dispatch_queue_offsets_addr value so we don't always have
2751 // to look it up
2752 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2753 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002754 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2755 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002756 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2757 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002758 if (module_sp)
2759 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2760
2761 if (dispatch_queue_offsets_symbol == NULL)
2762 {
Greg Clayton444fe992012-02-26 05:51:37 +00002763 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2764 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002765 if (module_sp)
2766 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2767 }
Chris Lattner24943d22010-06-08 16:52:24 +00002768 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002769 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002770
2771 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2772 return NULL;
2773 }
2774
2775 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002776 DataExtractor data (memory_buffer,
2777 sizeof(memory_buffer),
2778 m_target.GetArchitecture().GetByteOrder(),
2779 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002780
2781 // Excerpt from src/queue_private.h
2782 struct dispatch_queue_offsets_s
2783 {
2784 uint16_t dqo_version;
2785 uint16_t dqo_label;
2786 uint16_t dqo_label_size;
2787 } dispatch_queue_offsets;
2788
2789
2790 Error error;
2791 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2792 {
2793 uint32_t data_offset = 0;
2794 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2795 {
2796 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2797 {
2798 data_offset = 0;
2799 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2800 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2801 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2802 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2803 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2804 dispatch_queue_name.erase (bytes_read);
2805 }
2806 }
2807 }
2808 }
2809 if (dispatch_queue_name.empty())
2810 return NULL;
2811 return dispatch_queue_name.c_str();
2812}
2813
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002814//uint32_t
2815//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2816//{
2817// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2818// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2819// if (m_local_debugserver)
2820// {
2821// return Host::ListProcessesMatchingName (name, matches, pids);
2822// }
2823// else
2824// {
2825// // FIXME: Implement talking to the remote debugserver.
2826// return 0;
2827// }
2828//
2829//}
2830//
Jim Ingham55e01d82011-01-22 01:33:44 +00002831bool
2832ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2833 lldb_private::StoppointCallbackContext *context,
2834 lldb::user_id_t break_id,
2835 lldb::user_id_t break_loc_id)
2836{
2837 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2838 // run so I can stop it if that's what I want to do.
2839 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2840 if (log)
2841 log->Printf("Hit New Thread Notification breakpoint.");
2842 return false;
2843}
2844
2845
2846bool
2847ProcessGDBRemote::StartNoticingNewThreads()
2848{
Jim Ingham55e01d82011-01-22 01:33:44 +00002849 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002850 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002851 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002852 if (log && log->GetVerbose())
2853 log->Printf("Enabled noticing new thread breakpoint.");
2854 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002855 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002856 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002857 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002858 PlatformSP platform_sp (m_target.GetPlatform());
2859 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002860 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002861 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2862 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002863 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002864 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002865 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2866 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002867 }
2868 else
2869 {
2870 if (log)
2871 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002872 }
2873 }
2874 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002875 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002876}
2877
2878bool
2879ProcessGDBRemote::StopNoticingNewThreads()
2880{
Jim Inghamff276fe2011-02-08 05:19:01 +00002881 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002882 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002883 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002884
2885 if (m_thread_create_bp_sp)
2886 m_thread_create_bp_sp->SetEnabled(false);
2887
Jim Ingham55e01d82011-01-22 01:33:44 +00002888 return true;
2889}
2890
2891