blob: 6e48482901bdf7f267659df4deba3e2254142374 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Sean Callanan483d00a2012-07-19 18:07:36 +000014#include <netinet/in.h>
Greg Clayton989816b2011-05-14 01:50:35 +000015#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000017#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000018#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000019
20// C++ Includes
21#include <algorithm>
22#include <map>
23
24// Other libraries and framework includes
25
Johnny Chenecd4feb2011-10-14 00:42:25 +000026#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000027#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Core/ArchSpec.h"
29#include "lldb/Core/Debugger.h"
30#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000031#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "lldb/Core/InputReader.h"
33#include "lldb/Core/Module.h"
34#include "lldb/Core/PluginManager.h"
35#include "lldb/Core/State.h"
Greg Clayton33559462012-04-13 21:24:18 +000036#include "lldb/Core/StreamFile.h"
Chris Lattner24943d22010-06-08 16:52:24 +000037#include "lldb/Core/StreamString.h"
38#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000039#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040#include "lldb/Host/TimeValue.h"
41#include "lldb/Symbol/ObjectFile.h"
42#include "lldb/Target/DynamicLoader.h"
43#include "lldb/Target/Target.h"
44#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000045#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000046#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000047
48// Project includes
49#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000050#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jim Ingham06b84492012-07-04 00:35:43 +000051#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000052#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000053#include "GDBRemoteRegisterContext.h"
54#include "ProcessGDBRemote.h"
55#include "ProcessGDBRemoteLog.h"
56#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000057#include "StopInfoMachException.h"
58
Greg Clayton451fa822012-04-09 22:46:21 +000059namespace lldb
60{
61 // Provide a function that can easily dump the packet history if we know a
62 // ProcessGDBRemote * value (which we can get from logs or from debugging).
63 // We need the function in the lldb namespace so it makes it into the final
64 // executable since the LLDB shared library only exports stuff in the lldb
65 // namespace. This allows you to attach with a debugger and call this
66 // function and get the packet history dumped to a file.
67 void
68 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
69 {
Greg Clayton33559462012-04-13 21:24:18 +000070 lldb_private::StreamFile strm;
71 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
72 if (error.Success())
73 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000074 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000075}
Chris Lattner24943d22010-06-08 16:52:24 +000076
Chris Lattner24943d22010-06-08 16:52:24 +000077
78#define DEBUGSERVER_BASENAME "debugserver"
79using namespace lldb;
80using namespace lldb_private;
81
Jim Inghamf9600482011-03-29 21:45:47 +000082static bool rand_initialized = false;
83
Sean Callanan483d00a2012-07-19 18:07:36 +000084// TODO Randomly assigning a port is unsafe. We should get an unused
85// ephemeral port from the kernel and make sure we reserve it before passing
86// it to debugserver.
87
88#if defined (__APPLE__)
89#define LOW_PORT (IPPORT_RESERVED)
90#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
91#else
92#define LOW_PORT (1024u)
93#define HIGH_PORT (49151u)
94#endif
95
Chris Lattner24943d22010-06-08 16:52:24 +000096static inline uint16_t
97get_random_port ()
98{
Jim Inghamf9600482011-03-29 21:45:47 +000099 if (!rand_initialized)
100 {
Stephen Wilson60f19d52011-03-30 00:12:40 +0000101 time_t seed = time(NULL);
102
Jim Inghamf9600482011-03-29 21:45:47 +0000103 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +0000104 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +0000105 }
Sean Callanan483d00a2012-07-19 18:07:36 +0000106 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner24943d22010-06-08 16:52:24 +0000107}
108
109
110const char *
111ProcessGDBRemote::GetPluginNameStatic()
112{
Greg Claytonb1888f22011-03-19 01:12:21 +0000113 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000114}
115
116const char *
117ProcessGDBRemote::GetPluginDescriptionStatic()
118{
119 return "GDB Remote protocol based debugging plug-in.";
120}
121
122void
123ProcessGDBRemote::Terminate()
124{
125 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
126}
127
128
Greg Clayton46c9a352012-02-09 06:16:32 +0000129lldb::ProcessSP
130ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000131{
Greg Clayton46c9a352012-02-09 06:16:32 +0000132 lldb::ProcessSP process_sp;
133 if (crash_file_path == NULL)
134 process_sp.reset (new ProcessGDBRemote (target, listener));
135 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000136}
137
138bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000139ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000140{
Greg Clayton61ddf562011-10-21 21:41:45 +0000141 if (plugin_specified_by_name)
142 return true;
143
Chris Lattner24943d22010-06-08 16:52:24 +0000144 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000145 Module *exe_module = target.GetExecutableModulePointer();
146 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000147 {
148 ObjectFile *exe_objfile = exe_module->GetObjectFile();
149 // We can't debug core files...
150 switch (exe_objfile->GetType())
151 {
152 case ObjectFile::eTypeInvalid:
153 case ObjectFile::eTypeCoreFile:
154 case ObjectFile::eTypeDebugInfo:
155 case ObjectFile::eTypeObjectFile:
156 case ObjectFile::eTypeSharedLibrary:
157 case ObjectFile::eTypeStubLibrary:
158 return false;
159 case ObjectFile::eTypeExecutable:
160 case ObjectFile::eTypeDynamicLinker:
161 case ObjectFile::eTypeUnknown:
162 break;
163 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000164 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000165 }
Jim Ingham7508e732010-08-09 23:31:02 +0000166 // However, if there is no executable module, we return true since we might be preparing to attach.
167 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000168}
169
170//----------------------------------------------------------------------
171// ProcessGDBRemote constructor
172//----------------------------------------------------------------------
173ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
174 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000175 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000176 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000177 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000178 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000179 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000180 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000181 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000182 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000183 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000184 m_continue_c_tids (),
185 m_continue_C_tids (),
186 m_continue_s_tids (),
187 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000188 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000189 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000190 m_addr_to_mmap_size (),
191 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000192 m_waiting_for_attach (false),
193 m_destroy_tried_resuming (false)
Chris Lattner24943d22010-06-08 16:52:24 +0000194{
Greg Claytonff39f742011-04-01 00:29:43 +0000195 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
196 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000197 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000198}
199
200//----------------------------------------------------------------------
201// Destructor
202//----------------------------------------------------------------------
203ProcessGDBRemote::~ProcessGDBRemote()
204{
205 // m_mach_process.UnregisterNotificationCallbacks (this);
206 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000207 // We need to call finalize on the process before destroying ourselves
208 // to make sure all of the broadcaster cleanup goes as planned. If we
209 // destruct this class, then Process::~Process() might have problems
210 // trying to fully destroy the broadcaster.
211 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000212}
213
214//----------------------------------------------------------------------
215// PluginInterface
216//----------------------------------------------------------------------
217const char *
218ProcessGDBRemote::GetPluginName()
219{
220 return "Process debugging plug-in that uses the GDB remote protocol";
221}
222
223const char *
224ProcessGDBRemote::GetShortPluginName()
225{
226 return GetPluginNameStatic();
227}
228
229uint32_t
230ProcessGDBRemote::GetPluginVersion()
231{
232 return 1;
233}
234
235void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000236ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000237{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000238 if (!force && m_register_info.GetNumRegisters() > 0)
239 return;
240
241 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000242 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000243 uint32_t reg_offset = 0;
244 uint32_t reg_num = 0;
Greg Clayton4a379b12012-07-17 03:23:13 +0000245 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton61d043b2011-03-22 04:00:09 +0000246 response_type == StringExtractorGDBRemote::eResponse;
247 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000248 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000249 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
250 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000251 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000252 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000253 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000254 response_type = response.GetResponseType();
255 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000256 {
257 std::string name;
258 std::string value;
259 ConstString reg_name;
260 ConstString alt_name;
261 ConstString set_name;
262 RegisterInfo reg_info = { NULL, // Name
263 NULL, // Alt name
264 0, // byte size
265 reg_offset, // offset
266 eEncodingUint, // encoding
267 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000268 {
269 LLDB_INVALID_REGNUM, // GCC reg num
270 LLDB_INVALID_REGNUM, // DWARF reg num
271 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000272 reg_num, // GDB reg num
273 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000274 },
275 NULL,
276 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000277 };
278
279 while (response.GetNameColonValue(name, value))
280 {
281 if (name.compare("name") == 0)
282 {
283 reg_name.SetCString(value.c_str());
284 }
285 else if (name.compare("alt-name") == 0)
286 {
287 alt_name.SetCString(value.c_str());
288 }
289 else if (name.compare("bitsize") == 0)
290 {
291 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
292 }
293 else if (name.compare("offset") == 0)
294 {
295 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000296 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000297 {
298 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000299 }
300 }
301 else if (name.compare("encoding") == 0)
302 {
303 if (value.compare("uint") == 0)
304 reg_info.encoding = eEncodingUint;
305 else if (value.compare("sint") == 0)
306 reg_info.encoding = eEncodingSint;
307 else if (value.compare("ieee754") == 0)
308 reg_info.encoding = eEncodingIEEE754;
309 else if (value.compare("vector") == 0)
310 reg_info.encoding = eEncodingVector;
311 }
312 else if (name.compare("format") == 0)
313 {
314 if (value.compare("binary") == 0)
315 reg_info.format = eFormatBinary;
316 else if (value.compare("decimal") == 0)
317 reg_info.format = eFormatDecimal;
318 else if (value.compare("hex") == 0)
319 reg_info.format = eFormatHex;
320 else if (value.compare("float") == 0)
321 reg_info.format = eFormatFloat;
322 else if (value.compare("vector-sint8") == 0)
323 reg_info.format = eFormatVectorOfSInt8;
324 else if (value.compare("vector-uint8") == 0)
325 reg_info.format = eFormatVectorOfUInt8;
326 else if (value.compare("vector-sint16") == 0)
327 reg_info.format = eFormatVectorOfSInt16;
328 else if (value.compare("vector-uint16") == 0)
329 reg_info.format = eFormatVectorOfUInt16;
330 else if (value.compare("vector-sint32") == 0)
331 reg_info.format = eFormatVectorOfSInt32;
332 else if (value.compare("vector-uint32") == 0)
333 reg_info.format = eFormatVectorOfUInt32;
334 else if (value.compare("vector-float32") == 0)
335 reg_info.format = eFormatVectorOfFloat32;
336 else if (value.compare("vector-uint128") == 0)
337 reg_info.format = eFormatVectorOfUInt128;
338 }
339 else if (name.compare("set") == 0)
340 {
341 set_name.SetCString(value.c_str());
342 }
343 else if (name.compare("gcc") == 0)
344 {
345 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
346 }
347 else if (name.compare("dwarf") == 0)
348 {
349 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
350 }
351 else if (name.compare("generic") == 0)
352 {
353 if (value.compare("pc") == 0)
354 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
355 else if (value.compare("sp") == 0)
356 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
357 else if (value.compare("fp") == 0)
358 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
359 else if (value.compare("ra") == 0)
360 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
361 else if (value.compare("flags") == 0)
362 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000363 else if (value.find("arg") == 0)
364 {
365 if (value.size() == 4)
366 {
367 switch (value[3])
368 {
369 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
370 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
371 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
372 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
373 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
374 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
375 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
376 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
377 }
378 }
379 }
Chris Lattner24943d22010-06-08 16:52:24 +0000380 }
381 }
382
Jason Molenda53d96862010-06-11 23:44:18 +0000383 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000384 assert (reg_info.byte_size != 0);
385 reg_offset += reg_info.byte_size;
386 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
387 }
388 }
389 else
390 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000391 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000392 }
393 }
394
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000395 // We didn't get anything if the accumulated reg_num is zero. See if we are
396 // debugging ARM and fill with a hard coded register set until we can get an
397 // updated debugserver down on the devices.
398 // On the other hand, if the accumulated reg_num is positive, see if we can
399 // add composite registers to the existing primordial ones.
400 bool from_scratch = (reg_num == 0);
401
402 const ArchSpec &target_arch = GetTarget().GetArchitecture();
403 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
404 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000405 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000406 if (remote_arch.IsValid()
407 && remote_arch.GetMachine() == llvm::Triple::arm
408 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
409 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000410 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000411 else if (target_arch.GetMachine() == llvm::Triple::arm)
412 {
413 m_register_info.HardcodeARMRegisters(from_scratch);
414 }
415
Johnny Chend2e30662012-05-22 00:57:05 +0000416 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000417 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
418 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000419 m_register_info.Addx86_64ConvenienceRegisters();
420
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000421 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000422 m_register_info.Finalize ();
423}
424
425Error
426ProcessGDBRemote::WillLaunch (Module* module)
427{
428 return WillLaunchOrAttach ();
429}
430
431Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000432ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000433{
434 return WillLaunchOrAttach ();
435}
436
437Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000438ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000439{
440 return WillLaunchOrAttach ();
441}
442
443Error
Greg Claytone71e2582011-02-04 01:58:07 +0000444ProcessGDBRemote::DoConnectRemote (const char *remote_url)
445{
446 Error error (WillLaunchOrAttach ());
447
448 if (error.Fail())
449 return error;
450
Greg Clayton180546b2011-04-30 01:09:13 +0000451 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000452
453 if (error.Fail())
454 return error;
455 StartAsyncThread ();
456
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000457 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000458 if (pid == LLDB_INVALID_PROCESS_ID)
459 {
460 // We don't have a valid process ID, so note that we are connected
461 // and could now request to launch or attach, or get remote process
462 // listings...
463 SetPrivateState (eStateConnected);
464 }
465 else
466 {
467 // We have a valid process
468 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000469 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000470 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000471 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000472 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000473 if (state == eStateStopped)
474 {
475 SetPrivateState (state);
476 }
477 else
Greg Claytond9919d32011-12-01 23:28:38 +0000478 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 +0000479 }
480 else
Greg Claytond9919d32011-12-01 23:28:38 +0000481 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 +0000482 }
Jason Molendacb740b32012-05-03 22:37:30 +0000483
484 if (error.Success()
485 && !GetTarget().GetArchitecture().IsValid()
486 && m_gdb_comm.GetHostArchitecture().IsValid())
487 {
488 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
489 }
490
Greg Claytone71e2582011-02-04 01:58:07 +0000491 return error;
492}
493
494Error
Chris Lattner24943d22010-06-08 16:52:24 +0000495ProcessGDBRemote::WillLaunchOrAttach ()
496{
497 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000498 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000499 return error;
500}
501
502//----------------------------------------------------------------------
503// Process Control
504//----------------------------------------------------------------------
505Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000506ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000507{
Greg Clayton4b407112010-09-30 21:49:03 +0000508 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000509
510 uint32_t launch_flags = launch_info.GetFlags().Get();
511 const char *stdin_path = NULL;
512 const char *stdout_path = NULL;
513 const char *stderr_path = NULL;
514 const char *working_dir = launch_info.GetWorkingDirectory();
515
516 const ProcessLaunchInfo::FileAction *file_action;
517 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
518 if (file_action)
519 {
520 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
521 stdin_path = file_action->GetPath();
522 }
523 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
524 if (file_action)
525 {
526 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
527 stdout_path = file_action->GetPath();
528 }
529 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
530 if (file_action)
531 {
532 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
533 stderr_path = file_action->GetPath();
534 }
535
Chris Lattner24943d22010-06-08 16:52:24 +0000536 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
537 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
538 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000539 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000540
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000541 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000542 if (object_file)
543 {
Chris Lattner24943d22010-06-08 16:52:24 +0000544 char host_port[128];
545 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000546 char connect_url[128];
547 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000548
Greg Claytona2f74232011-02-24 22:24:29 +0000549 // Make sure we aren't already connected?
550 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000551 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000552 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000553 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000554 {
Johnny Chenc143d622011-08-09 18:56:45 +0000555 if (log)
556 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000557 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000558 }
Chris Lattner24943d22010-06-08 16:52:24 +0000559
Greg Claytone71e2582011-02-04 01:58:07 +0000560 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000561 }
562
563 if (error.Success())
564 {
565 lldb_utility::PseudoTerminal pty;
566 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000567
568 // If the debugserver is local and we aren't disabling STDIO, lets use
569 // a pseudo terminal to instead of relying on the 'O' packets for stdio
570 // since 'O' packets can really slow down debugging if the inferior
571 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000572 PlatformSP platform_sp (m_target.GetPlatform());
573 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000574 {
575 const char *slave_name = NULL;
576 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000577 {
Greg Claytona2f74232011-02-24 22:24:29 +0000578 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
579 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000580 }
Greg Claytona2f74232011-02-24 22:24:29 +0000581 if (stdin_path == NULL)
582 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000583
Greg Claytona2f74232011-02-24 22:24:29 +0000584 if (stdout_path == NULL)
585 stdout_path = slave_name;
586
587 if (stderr_path == NULL)
588 stderr_path = slave_name;
589 }
590
Greg Claytonafb81862011-03-02 21:34:46 +0000591 // Set STDIN to /dev/null if we want STDIO disabled or if either
592 // STDOUT or STDERR have been set to something and STDIN hasn't
593 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000594 stdin_path = "/dev/null";
595
Greg Claytonafb81862011-03-02 21:34:46 +0000596 // Set STDOUT to /dev/null if we want STDIO disabled or if either
597 // STDIN or STDERR have been set to something and STDOUT hasn't
598 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000599 stdout_path = "/dev/null";
600
Greg Claytonafb81862011-03-02 21:34:46 +0000601 // Set STDERR to /dev/null if we want STDIO disabled or if either
602 // STDIN or STDOUT have been set to something and STDERR hasn't
603 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000604 stderr_path = "/dev/null";
605
606 if (stdin_path)
607 m_gdb_comm.SetSTDIN (stdin_path);
608 if (stdout_path)
609 m_gdb_comm.SetSTDOUT (stdout_path);
610 if (stderr_path)
611 m_gdb_comm.SetSTDERR (stderr_path);
612
613 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
614
Greg Claytona4582402011-05-08 04:53:50 +0000615 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000616
617 if (working_dir && working_dir[0])
618 {
619 m_gdb_comm.SetWorkingDir (working_dir);
620 }
621
622 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000623 const Args &environment = launch_info.GetEnvironmentEntries();
624 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000625 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000626 size_t num_environment_entries = environment.GetArgumentCount();
627 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000628 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000629 const char *env_entry = environment.GetArgumentAtIndex(i);
630 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000631 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000632 }
Greg Claytona2f74232011-02-24 22:24:29 +0000633 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000634
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000635 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000636 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000637 if (arg_packet_err == 0)
638 {
639 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000640 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000641 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000642 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000643 }
644 else
645 {
Greg Claytona2f74232011-02-24 22:24:29 +0000646 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000647 }
Greg Claytona2f74232011-02-24 22:24:29 +0000648 }
649 else
650 {
Greg Clayton9c236732011-10-26 00:56:27 +0000651 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000652 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000653
654 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000655
Greg Claytona2f74232011-02-24 22:24:29 +0000656 if (GetID() == LLDB_INVALID_PROCESS_ID)
657 {
Johnny Chenc143d622011-08-09 18:56:45 +0000658 if (log)
659 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000660 KillDebugserverProcess ();
661 return error;
662 }
663
Greg Clayton261a18b2011-06-02 22:22:38 +0000664 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000665 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000666 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000667
668 if (!disable_stdio)
669 {
670 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000671 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000672 }
Chris Lattner24943d22010-06-08 16:52:24 +0000673 }
674 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000675 else
676 {
Johnny Chenc143d622011-08-09 18:56:45 +0000677 if (log)
678 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000679 }
Chris Lattner24943d22010-06-08 16:52:24 +0000680 }
681 else
682 {
683 // Set our user ID to an invalid process ID.
684 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000685 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
686 exe_module->GetFileSpec().GetFilename().AsCString(),
687 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000688 }
Chris Lattner24943d22010-06-08 16:52:24 +0000689 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000690
Chris Lattner24943d22010-06-08 16:52:24 +0000691}
692
693
694Error
Greg Claytone71e2582011-02-04 01:58:07 +0000695ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000696{
697 Error error;
698 // Sleep and wait a bit for debugserver to start to listen...
699 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
700 if (conn_ap.get())
701 {
Chris Lattner24943d22010-06-08 16:52:24 +0000702 const uint32_t max_retry_count = 50;
703 uint32_t retry_count = 0;
704 while (!m_gdb_comm.IsConnected())
705 {
Greg Claytone71e2582011-02-04 01:58:07 +0000706 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000707 {
708 m_gdb_comm.SetConnection (conn_ap.release());
709 break;
710 }
711 retry_count++;
712
713 if (retry_count >= max_retry_count)
714 break;
715
716 usleep (100000);
717 }
718 }
719
720 if (!m_gdb_comm.IsConnected())
721 {
722 if (error.Success())
723 error.SetErrorString("not connected to remote gdb server");
724 return error;
725 }
726
Greg Clayton24bc5d92011-03-30 18:16:51 +0000727 // We always seem to be able to open a connection to a local port
728 // so we need to make sure we can then send data to it. If we can't
729 // then we aren't actually connected to anything, so try and do the
730 // handshake with the remote GDB server and make sure that goes
731 // alright.
732 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000733 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000734 m_gdb_comm.Disconnect();
735 if (error.Success())
736 error.SetErrorString("not connected to remote gdb server");
737 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000738 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000739 m_gdb_comm.ResetDiscoverableSettings();
740 m_gdb_comm.QueryNoAckModeSupported ();
741 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000742 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000743 m_gdb_comm.GetHostInfo ();
744 m_gdb_comm.GetVContSupported ('c');
Jim Ingham86827fb2012-07-02 05:40:07 +0000745
746 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
747 for (size_t idx = 0; idx < num_cmds; idx++)
748 {
749 StringExtractorGDBRemote response;
750 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx));
751 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
752 }
Chris Lattner24943d22010-06-08 16:52:24 +0000753 return error;
754}
755
756void
757ProcessGDBRemote::DidLaunchOrAttach ()
758{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000759 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
760 if (log)
761 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000762 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000763 {
764 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
765
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000766 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000767
Chris Lattner24943d22010-06-08 16:52:24 +0000768 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000769
Greg Claytoncb8977d2011-03-23 00:09:55 +0000770 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
771 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000772 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000773 ArchSpec &target_arch = GetTarget().GetArchitecture();
774
775 if (target_arch.IsValid())
776 {
777 // If the remote host is ARM and we have apple as the vendor, then
778 // ARM executables and shared libraries can have mixed ARM architectures.
779 // You can have an armv6 executable, and if the host is armv7, then the
780 // system will load the best possible architecture for all shared libraries
781 // it has, so we really need to take the remote host architecture as our
782 // defacto architecture in this case.
783
784 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
785 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
786 {
787 target_arch = gdb_remote_arch;
788 }
789 else
790 {
791 // Fill in what is missing in the triple
792 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
793 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000794 if (target_triple.getVendorName().size() == 0)
795 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000796 target_triple.setVendor (remote_triple.getVendor());
797
Greg Clayton2f085c62011-05-15 01:25:55 +0000798 if (target_triple.getOSName().size() == 0)
799 {
800 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000801
Greg Clayton2f085c62011-05-15 01:25:55 +0000802 if (target_triple.getEnvironmentName().size() == 0)
803 target_triple.setEnvironment (remote_triple.getEnvironment());
804 }
805 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000806 }
807 }
808 else
809 {
810 // The target doesn't have a valid architecture yet, set it from
811 // the architecture we got from the remote GDB server
812 target_arch = gdb_remote_arch;
813 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000814 }
Chris Lattner24943d22010-06-08 16:52:24 +0000815 }
816}
817
818void
819ProcessGDBRemote::DidLaunch ()
820{
821 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000822}
823
824Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000825ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000826{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000827 ProcessAttachInfo attach_info;
828 return DoAttachToProcessWithID(attach_pid, attach_info);
829}
830
831Error
832ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
833{
Chris Lattner24943d22010-06-08 16:52:24 +0000834 Error error;
835 // Clear out and clean up from any current state
836 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000837 if (attach_pid != LLDB_INVALID_PROCESS_ID)
838 {
Greg Claytona2f74232011-02-24 22:24:29 +0000839 // Make sure we aren't already connected?
840 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000841 {
Greg Claytona2f74232011-02-24 22:24:29 +0000842 char host_port[128];
843 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
844 char connect_url[128];
845 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000846
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000847 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000848
849 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000850 {
Greg Claytona2f74232011-02-24 22:24:29 +0000851 const char *error_string = error.AsCString();
852 if (error_string == NULL)
853 error_string = "unable to launch " DEBUGSERVER_BASENAME;
854
855 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000856 }
Greg Claytona2f74232011-02-24 22:24:29 +0000857 else
858 {
859 error = ConnectToDebugserver (connect_url);
860 }
861 }
862
863 if (error.Success())
864 {
865 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000866 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000867 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000868 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000869 }
870 }
Chris Lattner24943d22010-06-08 16:52:24 +0000871 return error;
872}
873
874size_t
875ProcessGDBRemote::AttachInputReaderCallback
876(
877 void *baton,
878 InputReader *reader,
879 lldb::InputReaderAction notification,
880 const char *bytes,
881 size_t bytes_len
882)
883{
884 if (notification == eInputReaderGotToken)
885 {
886 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
887 if (gdb_process->m_waiting_for_attach)
888 gdb_process->m_waiting_for_attach = false;
889 reader->SetIsDone(true);
890 return 1;
891 }
892 return 0;
893}
894
895Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000896ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000897{
898 Error error;
899 // Clear out and clean up from any current state
900 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000901
Chris Lattner24943d22010-06-08 16:52:24 +0000902 if (process_name && process_name[0])
903 {
Greg Claytona2f74232011-02-24 22:24:29 +0000904 // Make sure we aren't already connected?
905 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000906 {
Greg Claytona2f74232011-02-24 22:24:29 +0000907 char host_port[128];
908 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
909 char connect_url[128];
910 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
911
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000912 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000913 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000914 {
Greg Claytona2f74232011-02-24 22:24:29 +0000915 const char *error_string = error.AsCString();
916 if (error_string == NULL)
917 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000918
Greg Claytona2f74232011-02-24 22:24:29 +0000919 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000920 }
Greg Claytona2f74232011-02-24 22:24:29 +0000921 else
922 {
923 error = ConnectToDebugserver (connect_url);
924 }
925 }
926
927 if (error.Success())
928 {
929 StreamString packet;
930
931 if (wait_for_launch)
932 packet.PutCString("vAttachWait");
933 else
934 packet.PutCString("vAttachName");
935 packet.PutChar(';');
936 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
937
938 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
939
Chris Lattner24943d22010-06-08 16:52:24 +0000940 }
941 }
Chris Lattner24943d22010-06-08 16:52:24 +0000942 return error;
943}
944
Chris Lattner24943d22010-06-08 16:52:24 +0000945
946void
947ProcessGDBRemote::DidAttach ()
948{
Greg Claytone71e2582011-02-04 01:58:07 +0000949 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000950}
951
952Error
953ProcessGDBRemote::WillResume ()
954{
Greg Claytonc1f45872011-02-12 06:28:37 +0000955 m_continue_c_tids.clear();
956 m_continue_C_tids.clear();
957 m_continue_s_tids.clear();
958 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000959 return Error();
960}
961
962Error
963ProcessGDBRemote::DoResume ()
964{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000965 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000966 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
967 if (log)
968 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000969
970 Listener listener ("gdb-remote.resume-packet-sent");
971 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
972 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000973 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
974
Greg Claytonc1f45872011-02-12 06:28:37 +0000975 StreamString continue_packet;
976 bool continue_packet_error = false;
977 if (m_gdb_comm.HasAnyVContSupport ())
978 {
979 continue_packet.PutCString ("vCont");
980
981 if (!m_continue_c_tids.empty())
982 {
983 if (m_gdb_comm.GetVContSupported ('c'))
984 {
985 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 +0000986 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000987 }
988 else
989 continue_packet_error = true;
990 }
991
992 if (!continue_packet_error && !m_continue_C_tids.empty())
993 {
994 if (m_gdb_comm.GetVContSupported ('C'))
995 {
996 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 +0000997 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000998 }
999 else
1000 continue_packet_error = true;
1001 }
Greg Claytonb749a262010-12-03 06:02:24 +00001002
Greg Claytonc1f45872011-02-12 06:28:37 +00001003 if (!continue_packet_error && !m_continue_s_tids.empty())
1004 {
1005 if (m_gdb_comm.GetVContSupported ('s'))
1006 {
1007 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 +00001008 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001009 }
1010 else
1011 continue_packet_error = true;
1012 }
1013
1014 if (!continue_packet_error && !m_continue_S_tids.empty())
1015 {
1016 if (m_gdb_comm.GetVContSupported ('S'))
1017 {
1018 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 +00001019 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001020 }
1021 else
1022 continue_packet_error = true;
1023 }
1024
1025 if (continue_packet_error)
1026 continue_packet.GetString().clear();
1027 }
1028 else
1029 continue_packet_error = true;
1030
1031 if (continue_packet_error)
1032 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001033 // Either no vCont support, or we tried to use part of the vCont
1034 // packet that wasn't supported by the remote GDB server.
1035 // We need to try and make a simple packet that can do our continue
1036 const size_t num_threads = GetThreadList().GetSize();
1037 const size_t num_continue_c_tids = m_continue_c_tids.size();
1038 const size_t num_continue_C_tids = m_continue_C_tids.size();
1039 const size_t num_continue_s_tids = m_continue_s_tids.size();
1040 const size_t num_continue_S_tids = m_continue_S_tids.size();
1041 if (num_continue_c_tids > 0)
1042 {
1043 if (num_continue_c_tids == num_threads)
1044 {
1045 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001046 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001047 continue_packet.PutChar ('c');
1048 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001049 }
1050 else if (num_continue_c_tids == 1 &&
1051 num_continue_C_tids == 0 &&
1052 num_continue_s_tids == 0 &&
1053 num_continue_S_tids == 0 )
1054 {
1055 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001056 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001057 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001058 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001059 }
1060 }
1061
Greg Claytonde1dd812011-06-24 03:21:43 +00001062 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001063 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001064 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1065 num_continue_C_tids > 0 &&
1066 num_continue_s_tids == 0 &&
1067 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001068 {
1069 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001070 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001071 if (num_continue_C_tids > 1)
1072 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001073 // More that one thread with a signal, yet we don't have
1074 // vCont support and we are being asked to resume each
1075 // thread with a signal, we need to make sure they are
1076 // all the same signal, or we can't issue the continue
1077 // accurately with the current support...
1078 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001079 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001080 continue_packet_error = false;
1081 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1082 {
1083 if (m_continue_C_tids[i].second != continue_signo)
1084 continue_packet_error = true;
1085 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001086 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001087 if (!continue_packet_error)
1088 m_gdb_comm.SetCurrentThreadForRun (-1);
1089 }
1090 else
1091 {
1092 // Set the continue thread ID
1093 continue_packet_error = false;
1094 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001095 }
1096 if (!continue_packet_error)
1097 {
1098 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001099 continue_packet.Printf("C%2.2x", continue_signo);
1100 }
1101 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001102 }
1103
Greg Claytonde1dd812011-06-24 03:21:43 +00001104 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001105 {
1106 if (num_continue_s_tids == num_threads)
1107 {
1108 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001109 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001110 continue_packet.PutChar ('s');
1111 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001112 }
1113 else if (num_continue_c_tids == 0 &&
1114 num_continue_C_tids == 0 &&
1115 num_continue_s_tids == 1 &&
1116 num_continue_S_tids == 0 )
1117 {
1118 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001119 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001120 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001121 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001122 }
1123 }
1124
1125 if (!continue_packet_error && num_continue_S_tids > 0)
1126 {
1127 if (num_continue_S_tids == num_threads)
1128 {
1129 const int step_signo = m_continue_S_tids.front().second;
1130 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001131 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001132 if (num_continue_S_tids > 1)
1133 {
1134 for (size_t i=1; i<num_threads; ++i)
1135 {
1136 if (m_continue_S_tids[i].second != step_signo)
1137 continue_packet_error = true;
1138 }
1139 }
1140 if (!continue_packet_error)
1141 {
1142 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001143 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001144 continue_packet.Printf("S%2.2x", step_signo);
1145 }
1146 }
1147 else if (num_continue_c_tids == 0 &&
1148 num_continue_C_tids == 0 &&
1149 num_continue_s_tids == 0 &&
1150 num_continue_S_tids == 1 )
1151 {
1152 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001153 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001154 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001155 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001156 }
1157 }
1158 }
1159
1160 if (continue_packet_error)
1161 {
1162 error.SetErrorString ("can't make continue packet for this resume");
1163 }
1164 else
1165 {
1166 EventSP event_sp;
1167 TimeValue timeout;
1168 timeout = TimeValue::Now();
1169 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001170 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1171 {
1172 error.SetErrorString ("Trying to resume but the async thread is dead.");
1173 if (log)
1174 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1175 return error;
1176 }
1177
Greg Claytonc1f45872011-02-12 06:28:37 +00001178 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1179
1180 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001181 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001182 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001183 if (log)
1184 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1185 }
1186 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1187 {
1188 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1189 if (log)
1190 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1191 return error;
1192 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001193 }
Greg Claytonb749a262010-12-03 06:02:24 +00001194 }
1195
Jim Ingham3ae449a2010-11-17 02:32:00 +00001196 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001197}
1198
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001199void
1200ProcessGDBRemote::ClearThreadIDList ()
1201{
Greg Claytonff3448e2012-04-13 02:11:32 +00001202 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001203 m_thread_ids.clear();
1204}
1205
1206bool
1207ProcessGDBRemote::UpdateThreadIDList ()
1208{
Greg Claytonff3448e2012-04-13 02:11:32 +00001209 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001210 bool sequence_mutex_unavailable = false;
1211 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1212 if (sequence_mutex_unavailable)
1213 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001214 return false; // We just didn't get the list
1215 }
1216 return true;
1217}
1218
Greg Claytonae932352012-04-10 00:18:59 +00001219bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001220ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001221{
1222 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001223 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001224 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001225 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001226
1227 size_t num_thread_ids = m_thread_ids.size();
1228 // The "m_thread_ids" thread ID list should always be updated after each stop
1229 // reply packet, but in case it isn't, update it here.
1230 if (num_thread_ids == 0)
1231 {
1232 if (!UpdateThreadIDList ())
1233 return false;
1234 num_thread_ids = m_thread_ids.size();
1235 }
Chris Lattner24943d22010-06-08 16:52:24 +00001236
Greg Clayton37f962e2011-08-22 02:49:39 +00001237 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001238 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001239 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001240 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001241 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001242 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1243 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001244 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001245 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001246 }
Chris Lattner24943d22010-06-08 16:52:24 +00001247 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001248
Greg Claytonae932352012-04-10 00:18:59 +00001249 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001250}
1251
1252
1253StateType
1254ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1255{
Greg Clayton261a18b2011-06-02 22:22:38 +00001256 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001257 const char stop_type = stop_packet.GetChar();
1258 switch (stop_type)
1259 {
1260 case 'T':
1261 case 'S':
1262 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001263 if (GetStopID() == 0)
1264 {
1265 // Our first stop, make sure we have a process ID, and also make
1266 // sure we know about our registers
1267 if (GetID() == LLDB_INVALID_PROCESS_ID)
1268 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001269 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001270 if (pid != LLDB_INVALID_PROCESS_ID)
1271 SetID (pid);
1272 }
1273 BuildDynamicRegisterInfo (true);
1274 }
Chris Lattner24943d22010-06-08 16:52:24 +00001275 // Stop with signal and thread info
1276 const uint8_t signo = stop_packet.GetHexU8();
1277 std::string name;
1278 std::string value;
1279 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001280 std::string reason;
1281 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001282 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001283 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001284 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001285 ThreadSP thread_sp;
1286
Chris Lattner24943d22010-06-08 16:52:24 +00001287 while (stop_packet.GetNameColonValue(name, value))
1288 {
1289 if (name.compare("metype") == 0)
1290 {
1291 // exception type in big endian hex
1292 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1293 }
Chris Lattner24943d22010-06-08 16:52:24 +00001294 else if (name.compare("medata") == 0)
1295 {
1296 // exception data in big endian hex
1297 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1298 }
1299 else if (name.compare("thread") == 0)
1300 {
1301 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001302 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001303 // m_thread_list does have its own mutex, but we need to
1304 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1305 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001306 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001307 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001308 if (!thread_sp)
1309 {
1310 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001311 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001312 m_thread_list.AddThread(thread_sp);
1313 }
Chris Lattner24943d22010-06-08 16:52:24 +00001314 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001315 else if (name.compare("threads") == 0)
1316 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001317 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001318 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001319 // A comma separated list of all threads in the current
1320 // process that includes the thread for this stop reply
1321 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001322 size_t comma_pos;
1323 lldb::tid_t tid;
1324 while ((comma_pos = value.find(',')) != std::string::npos)
1325 {
1326 value[comma_pos] = '\0';
1327 // thread in big endian hex
1328 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1329 if (tid != LLDB_INVALID_THREAD_ID)
1330 m_thread_ids.push_back (tid);
1331 value.erase(0, comma_pos + 1);
1332
1333 }
1334 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1335 if (tid != LLDB_INVALID_THREAD_ID)
1336 m_thread_ids.push_back (tid);
1337 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001338 else if (name.compare("hexname") == 0)
1339 {
1340 StringExtractor name_extractor;
1341 // Swap "value" over into "name_extractor"
1342 name_extractor.GetStringRef().swap(value);
1343 // Now convert the HEX bytes into a string value
1344 name_extractor.GetHexByteString (value);
1345 thread_name.swap (value);
1346 }
Chris Lattner24943d22010-06-08 16:52:24 +00001347 else if (name.compare("name") == 0)
1348 {
1349 thread_name.swap (value);
1350 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001351 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001352 {
1353 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1354 }
Greg Clayton65611552011-06-04 01:26:29 +00001355 else if (name.compare("reason") == 0)
1356 {
1357 reason.swap(value);
1358 }
1359 else if (name.compare("description") == 0)
1360 {
1361 StringExtractor desc_extractor;
1362 // Swap "value" over into "name_extractor"
1363 desc_extractor.GetStringRef().swap(value);
1364 // Now convert the HEX bytes into a string value
1365 desc_extractor.GetHexByteString (thread_name);
1366 }
Greg Claytona875b642011-01-09 21:07:35 +00001367 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1368 {
1369 // We have a register number that contains an expedited
1370 // register value. Lets supply this register to our thread
1371 // so it won't have to go and read it.
1372 if (thread_sp)
1373 {
1374 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1375
1376 if (reg != UINT32_MAX)
1377 {
1378 StringExtractor reg_value_extractor;
1379 // Swap "value" over into "reg_value_extractor"
1380 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001381 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1382 {
1383 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1384 name.c_str(),
1385 reg,
1386 reg,
1387 reg_value_extractor.GetStringRef().c_str(),
1388 stop_packet.GetStringRef().c_str());
1389 }
Greg Claytona875b642011-01-09 21:07:35 +00001390 }
1391 }
1392 }
Chris Lattner24943d22010-06-08 16:52:24 +00001393 }
Chris Lattner24943d22010-06-08 16:52:24 +00001394
1395 if (thread_sp)
1396 {
1397 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1398
1399 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001400 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001401 if (exc_type != 0)
1402 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001403 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001404
1405 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1406 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001407 exc_data_size,
1408 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001409 exc_data_size >= 2 ? exc_data[1] : 0,
1410 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001411 }
Greg Clayton65611552011-06-04 01:26:29 +00001412 else
Chris Lattner24943d22010-06-08 16:52:24 +00001413 {
Greg Clayton65611552011-06-04 01:26:29 +00001414 bool handled = false;
1415 if (!reason.empty())
1416 {
1417 if (reason.compare("trace") == 0)
1418 {
1419 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1420 handled = true;
1421 }
1422 else if (reason.compare("breakpoint") == 0)
1423 {
1424 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001425 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001426 if (bp_site_sp)
1427 {
1428 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1429 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1430 // 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 +00001431 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001432 if (bp_site_sp->ValidForThisThread (gdb_thread))
1433 {
1434 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001435 }
1436 else
1437 {
1438 StopInfoSP invalid_stop_info_sp;
1439 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001440 }
1441 }
1442
Greg Clayton65611552011-06-04 01:26:29 +00001443 }
1444 else if (reason.compare("trap") == 0)
1445 {
1446 // Let the trap just use the standard signal stop reason below...
1447 }
1448 else if (reason.compare("watchpoint") == 0)
1449 {
1450 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1451 // TODO: locate the watchpoint somehow...
1452 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1453 handled = true;
1454 }
1455 else if (reason.compare("exception") == 0)
1456 {
1457 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1458 handled = true;
1459 }
1460 }
1461
1462 if (signo)
1463 {
1464 if (signo == SIGTRAP)
1465 {
1466 // Currently we are going to assume SIGTRAP means we are either
1467 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001468 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001469 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001470 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001471
Greg Clayton65611552011-06-04 01:26:29 +00001472 if (bp_site_sp)
1473 {
1474 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1475 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1476 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1477 if (bp_site_sp->ValidForThisThread (gdb_thread))
1478 {
1479 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001480 }
1481 else
1482 {
1483 StopInfoSP invalid_stop_info_sp;
1484 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001485 }
1486 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001487 else
Greg Clayton65611552011-06-04 01:26:29 +00001488 {
1489 // TODO: check for breakpoint or trap opcode in case there is a hard
1490 // coded software trap
1491 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton65611552011-06-04 01:26:29 +00001492 }
1493 }
1494 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001495 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001496 }
1497 else
1498 {
Greg Clayton643ee732010-08-04 01:40:35 +00001499 StopInfoSP invalid_stop_info_sp;
1500 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001501 }
Greg Clayton65611552011-06-04 01:26:29 +00001502
1503 if (!description.empty())
1504 {
1505 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1506 if (stop_info_sp)
1507 {
1508 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001509 }
Greg Clayton65611552011-06-04 01:26:29 +00001510 else
1511 {
1512 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1513 }
1514 }
1515 }
Chris Lattner24943d22010-06-08 16:52:24 +00001516 }
1517 return eStateStopped;
1518 }
1519 break;
1520
1521 case 'W':
1522 // process exited
1523 return eStateExited;
1524
1525 default:
1526 break;
1527 }
1528 return eStateInvalid;
1529}
1530
1531void
1532ProcessGDBRemote::RefreshStateAfterStop ()
1533{
Greg Claytonff3448e2012-04-13 02:11:32 +00001534 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001535 m_thread_ids.clear();
1536 // Set the thread stop info. It might have a "threads" key whose value is
1537 // a list of all thread IDs in the current process, so m_thread_ids might
1538 // get set.
1539 SetThreadStopInfo (m_last_stop_packet);
1540 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1541 if (m_thread_ids.empty())
1542 {
1543 // No, we need to fetch the thread list manually
1544 UpdateThreadIDList();
1545 }
1546
Chris Lattner24943d22010-06-08 16:52:24 +00001547 // Let all threads recover from stopping and do any clean up based
1548 // on the previous thread state (if any).
1549 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001550
Chris Lattner24943d22010-06-08 16:52:24 +00001551}
1552
1553Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001554ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001555{
1556 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001557
Greg Claytona4881d02011-01-22 07:12:45 +00001558 bool timed_out = false;
1559 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001560
1561 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001562 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001563 // We are being asked to halt during an attach. We need to just close
1564 // our file handle and debugserver will go away, and we can be done...
1565 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001566 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001567 else
1568 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001569 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001570 {
1571 if (timed_out)
1572 error.SetErrorString("timed out sending interrupt packet");
1573 else
1574 error.SetErrorString("unknown error sending interrupt packet");
1575 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001576
1577 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001578 }
Chris Lattner24943d22010-06-08 16:52:24 +00001579 return error;
1580}
1581
1582Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001583ProcessGDBRemote::InterruptIfRunning
1584(
1585 bool discard_thread_plans,
1586 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001587 EventSP &stop_event_sp
1588)
Chris Lattner24943d22010-06-08 16:52:24 +00001589{
1590 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001591
Greg Clayton2860ba92011-01-23 19:58:49 +00001592 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1593
Greg Clayton68ca8232011-01-25 02:58:48 +00001594 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001595 const bool is_running = m_gdb_comm.IsRunning();
1596 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001597 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001598 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001599 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001600 is_running);
1601
Greg Clayton2860ba92011-01-23 19:58:49 +00001602 if (discard_thread_plans)
1603 {
1604 if (log)
1605 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1606 m_thread_list.DiscardThreadPlans();
1607 }
1608 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001609 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001610 if (catch_stop_event)
1611 {
1612 if (log)
1613 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1614 PausePrivateStateThread();
1615 paused_private_state_thread = true;
1616 }
1617
Greg Clayton4fb400f2010-09-27 21:07:38 +00001618 bool timed_out = false;
1619 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001620
Greg Clayton05e4d972012-03-29 01:55:41 +00001621 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001622 {
1623 if (timed_out)
1624 error.SetErrorString("timed out sending interrupt packet");
1625 else
1626 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001627 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001628 ResumePrivateStateThread();
1629 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001630 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001631
Greg Clayton72e1c782011-01-22 23:43:18 +00001632 if (catch_stop_event)
1633 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001634 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001635 TimeValue timeout_time;
1636 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001637 timeout_time.OffsetWithSeconds(5);
1638 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001639
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001640 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001641 if (log)
1642 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001643
Greg Clayton2860ba92011-01-23 19:58:49 +00001644 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001645 error.SetErrorString("unable to verify target stopped");
1646 }
1647
Greg Clayton68ca8232011-01-25 02:58:48 +00001648 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001649 {
1650 if (log)
1651 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001652 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001653 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001654 }
Chris Lattner24943d22010-06-08 16:52:24 +00001655 return error;
1656}
1657
Greg Clayton4fb400f2010-09-27 21:07:38 +00001658Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001659ProcessGDBRemote::WillDetach ()
1660{
Greg Clayton2860ba92011-01-23 19:58:49 +00001661 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1662 if (log)
1663 log->Printf ("ProcessGDBRemote::WillDetach()");
1664
Greg Clayton72e1c782011-01-22 23:43:18 +00001665 bool discard_thread_plans = true;
1666 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001667 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001668
1669 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1670 // needed. This shouldn't be a feature of a particular plugin.
1671
Greg Clayton68ca8232011-01-25 02:58:48 +00001672 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001673}
1674
1675Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001676ProcessGDBRemote::DoDetach()
1677{
1678 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001679 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001680 if (log)
1681 log->Printf ("ProcessGDBRemote::DoDetach()");
1682
1683 DisableAllBreakpointSites ();
1684
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001685 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001686
Greg Clayton516f0842012-04-11 00:24:49 +00001687 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001688 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001689 {
Greg Clayton516f0842012-04-11 00:24:49 +00001690 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001691 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1692 else
1693 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001694 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001695 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001696 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001697
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001698 SetPrivateState (eStateDetached);
1699 ResumePrivateStateThread();
1700
1701 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001702 return error;
1703}
Chris Lattner24943d22010-06-08 16:52:24 +00001704
Jim Ingham06b84492012-07-04 00:35:43 +00001705
Chris Lattner24943d22010-06-08 16:52:24 +00001706Error
1707ProcessGDBRemote::DoDestroy ()
1708{
1709 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001710 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001711 if (log)
1712 log->Printf ("ProcessGDBRemote::DoDestroy()");
1713
Jim Ingham06b84492012-07-04 00:35:43 +00001714 // There is a bug in older iOS debugservers where they don't shut down the process
1715 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1716 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1717 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1718 // destroy it again.
1719 //
1720 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1721 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1722 // the debugservers with this bug are equal. There really should be a better way to test this!
1723 //
1724 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1725 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1726 // just do the straight-forward kill.
1727 //
1728 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1729 // necessary (or helpful) to do any of this.
1730
1731 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1732 {
1733 PlatformSP platform_sp = GetTarget().GetPlatform();
1734
1735 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1736 if (platform_sp
1737 && platform_sp->GetName()
1738 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1739 {
1740 if (m_destroy_tried_resuming)
1741 {
1742 if (log)
1743 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1744 }
1745 else
1746 {
1747 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1748 // but we really need it to happen here and it doesn't matter if we do it twice.
1749 m_thread_list.DiscardThreadPlans();
1750 DisableAllBreakpointSites();
1751
1752 bool stop_looks_like_crash = false;
1753 ThreadList &threads = GetThreadList();
1754
1755 {
1756 Mutex::Locker(threads.GetMutex());
1757
1758 size_t num_threads = threads.GetSize();
1759 for (size_t i = 0; i < num_threads; i++)
1760 {
1761 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1762 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1763 StopReason reason = eStopReasonInvalid;
1764 if (stop_info_sp)
1765 reason = stop_info_sp->GetStopReason();
1766 if (reason == eStopReasonBreakpoint
1767 || reason == eStopReasonException)
1768 {
1769 if (log)
1770 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1771 thread_sp->GetID(),
1772 stop_info_sp->GetDescription());
1773 stop_looks_like_crash = true;
1774 break;
1775 }
1776 }
1777 }
1778
1779 if (stop_looks_like_crash)
1780 {
1781 if (log)
1782 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1783 m_destroy_tried_resuming = true;
1784
1785 // If we are going to run again before killing, it would be good to suspend all the threads
1786 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1787 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1788 // have to run the risk of letting those threads proceed a bit.
1789
1790 {
1791 Mutex::Locker(threads.GetMutex());
1792
1793 size_t num_threads = threads.GetSize();
1794 for (size_t i = 0; i < num_threads; i++)
1795 {
1796 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1797 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1798 StopReason reason = eStopReasonInvalid;
1799 if (stop_info_sp)
1800 reason = stop_info_sp->GetStopReason();
1801 if (reason != eStopReasonBreakpoint
1802 && reason != eStopReasonException)
1803 {
1804 if (log)
1805 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1806 thread_sp->GetID());
1807 thread_sp->SetResumeState(eStateSuspended);
1808 }
1809 }
1810 }
1811 Resume ();
1812 return Destroy();
1813 }
1814 }
1815 }
1816 }
1817
Chris Lattner24943d22010-06-08 16:52:24 +00001818 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001819 int exit_status = SIGABRT;
1820 std::string exit_string;
1821
Greg Claytona4881d02011-01-22 07:12:45 +00001822 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001823 {
Jim Ingham8226e942011-10-28 01:11:35 +00001824 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001825 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001826
1827 StringExtractorGDBRemote response;
1828 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001829 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001830 {
1831 char packet_cmd = response.GetChar(0);
1832
1833 if (packet_cmd == 'W' || packet_cmd == 'X')
1834 {
Greg Clayton06709002011-12-06 04:51:14 +00001835 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001836 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001837 exit_status = response.GetHexU8();
1838 }
1839 else
1840 {
1841 if (log)
1842 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1843 exit_string.assign("got unexpected response to k packet: ");
1844 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001845 }
1846 }
1847 else
1848 {
Jim Ingham8247e622012-06-06 00:32:39 +00001849 if (log)
1850 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1851 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001852 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001853 }
Jim Ingham8247e622012-06-06 00:32:39 +00001854 else
1855 {
1856 if (log)
1857 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1858 exit_string.assign ("killing while attaching.");
1859 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001860 }
Jim Ingham8247e622012-06-06 00:32:39 +00001861 else
1862 {
1863 // If we missed setting the exit status on the way out, do it here.
1864 // NB set exit status can be called multiple times, the first one sets the status.
1865 exit_string.assign("destroying when not connected to debugserver");
1866 }
1867
1868 SetExitStatus(exit_status, exit_string.c_str());
1869
Chris Lattner24943d22010-06-08 16:52:24 +00001870 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001871 KillDebugserverProcess ();
1872 return error;
1873}
1874
Chris Lattner24943d22010-06-08 16:52:24 +00001875//------------------------------------------------------------------
1876// Process Queries
1877//------------------------------------------------------------------
1878
1879bool
1880ProcessGDBRemote::IsAlive ()
1881{
Greg Clayton58e844b2010-12-08 05:08:21 +00001882 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001883}
1884
1885addr_t
1886ProcessGDBRemote::GetImageInfoAddress()
1887{
Greg Clayton516f0842012-04-11 00:24:49 +00001888 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001889}
1890
Chris Lattner24943d22010-06-08 16:52:24 +00001891//------------------------------------------------------------------
1892// Process Memory
1893//------------------------------------------------------------------
1894size_t
1895ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1896{
1897 if (size > m_max_memory_size)
1898 {
1899 // Keep memory read sizes down to a sane limit. This function will be
1900 // called multiple times in order to complete the task by
1901 // lldb_private::Process so it is ok to do this.
1902 size = m_max_memory_size;
1903 }
1904
1905 char packet[64];
1906 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1907 assert (packet_len + 1 < sizeof(packet));
1908 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001909 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001910 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001911 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001912 {
1913 error.Clear();
1914 return response.GetHexBytes(buf, size, '\xdd');
1915 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001916 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001917 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001918 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001919 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1920 else
1921 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1922 }
1923 else
1924 {
1925 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1926 }
1927 return 0;
1928}
1929
1930size_t
1931ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1932{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001933 if (size > m_max_memory_size)
1934 {
1935 // Keep memory read sizes down to a sane limit. This function will be
1936 // called multiple times in order to complete the task by
1937 // lldb_private::Process so it is ok to do this.
1938 size = m_max_memory_size;
1939 }
1940
Chris Lattner24943d22010-06-08 16:52:24 +00001941 StreamString packet;
1942 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001943 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001944 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001945 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001946 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001947 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001948 {
1949 error.Clear();
1950 return size;
1951 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001952 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001953 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001954 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001955 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1956 else
1957 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1958 }
1959 else
1960 {
1961 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1962 }
1963 return 0;
1964}
1965
1966lldb::addr_t
1967ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1968{
Greg Clayton989816b2011-05-14 01:50:35 +00001969 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1970
Greg Clayton2f085c62011-05-15 01:25:55 +00001971 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001972 switch (supported)
1973 {
1974 case eLazyBoolCalculate:
1975 case eLazyBoolYes:
1976 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1977 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1978 return allocated_addr;
1979
1980 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001981 // Call mmap() to create memory in the inferior..
1982 unsigned prot = 0;
1983 if (permissions & lldb::ePermissionsReadable)
1984 prot |= eMmapProtRead;
1985 if (permissions & lldb::ePermissionsWritable)
1986 prot |= eMmapProtWrite;
1987 if (permissions & lldb::ePermissionsExecutable)
1988 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001989
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001990 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1991 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1992 m_addr_to_mmap_size[allocated_addr] = size;
1993 else
1994 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001995 break;
1996 }
1997
Chris Lattner24943d22010-06-08 16:52:24 +00001998 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001999 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002000 else
2001 error.Clear();
2002 return allocated_addr;
2003}
2004
2005Error
Greg Claytona9385532011-11-18 07:03:08 +00002006ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2007 MemoryRegionInfo &region_info)
2008{
2009
2010 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2011 return error;
2012}
2013
2014Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002015ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2016{
2017
2018 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2019 return error;
2020}
2021
2022Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002023ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2024{
2025 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2026 return error;
2027}
2028
2029Error
Chris Lattner24943d22010-06-08 16:52:24 +00002030ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2031{
2032 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002033 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2034
2035 switch (supported)
2036 {
2037 case eLazyBoolCalculate:
2038 // We should never be deallocating memory without allocating memory
2039 // first so we should never get eLazyBoolCalculate
2040 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2041 break;
2042
2043 case eLazyBoolYes:
2044 if (!m_gdb_comm.DeallocateMemory (addr))
2045 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2046 break;
2047
2048 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002049 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002050 {
2051 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002052 if (pos != m_addr_to_mmap_size.end() &&
2053 InferiorCallMunmap(this, addr, pos->second))
2054 m_addr_to_mmap_size.erase (pos);
2055 else
2056 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002057 }
2058 break;
2059 }
2060
Chris Lattner24943d22010-06-08 16:52:24 +00002061 return error;
2062}
2063
2064
2065//------------------------------------------------------------------
2066// Process STDIO
2067//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002068size_t
2069ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2070{
2071 if (m_stdio_communication.IsConnected())
2072 {
2073 ConnectionStatus status;
2074 m_stdio_communication.Write(src, src_len, status, NULL);
2075 }
2076 return 0;
2077}
2078
2079Error
2080ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2081{
2082 Error error;
2083 assert (bp_site != NULL);
2084
Greg Claytone005f2c2010-11-06 01:53:30 +00002085 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002086 user_id_t site_id = bp_site->GetID();
2087 const addr_t addr = bp_site->GetLoadAddress();
2088 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002089 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002090
2091 if (bp_site->IsEnabled())
2092 {
2093 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002094 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 +00002095 return error;
2096 }
2097 else
2098 {
2099 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2100
2101 if (bp_site->HardwarePreferred())
2102 {
2103 // Try and set hardware breakpoint, and if that fails, fall through
2104 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002105 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002106 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002107 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002108 {
2109 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002110 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002111 return error;
2112 }
Chris Lattner24943d22010-06-08 16:52:24 +00002113 }
2114 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002115
2116 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002117 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002118 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2119 {
2120 bp_site->SetEnabled(true);
2121 bp_site->SetType (BreakpointSite::eExternal);
2122 return error;
2123 }
Chris Lattner24943d22010-06-08 16:52:24 +00002124 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002125
2126 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002127 }
2128
2129 if (log)
2130 {
2131 const char *err_string = error.AsCString();
2132 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2133 bp_site->GetLoadAddress(),
2134 err_string ? err_string : "NULL");
2135 }
2136 // We shouldn't reach here on a successful breakpoint enable...
2137 if (error.Success())
2138 error.SetErrorToGenericError();
2139 return error;
2140}
2141
2142Error
2143ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2144{
2145 Error error;
2146 assert (bp_site != NULL);
2147 addr_t addr = bp_site->GetLoadAddress();
2148 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002149 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002150 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002151 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002152
2153 if (bp_site->IsEnabled())
2154 {
2155 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2156
Greg Claytonb72d0f02011-04-12 05:54:46 +00002157 BreakpointSite::Type bp_type = bp_site->GetType();
2158 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002159 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002160 case BreakpointSite::eSoftware:
2161 error = DisableSoftwareBreakpoint (bp_site);
2162 break;
2163
2164 case BreakpointSite::eHardware:
2165 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2166 error.SetErrorToGenericError();
2167 break;
2168
2169 case BreakpointSite::eExternal:
2170 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2171 error.SetErrorToGenericError();
2172 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002173 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002174 if (error.Success())
2175 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002176 }
2177 else
2178 {
2179 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002180 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 +00002181 return error;
2182 }
2183
2184 if (error.Success())
2185 error.SetErrorToGenericError();
2186 return error;
2187}
2188
Johnny Chen21900fb2011-09-06 22:38:36 +00002189// Pre-requisite: wp != NULL.
2190static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002191GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002192{
2193 assert(wp);
2194 bool watch_read = wp->WatchpointRead();
2195 bool watch_write = wp->WatchpointWrite();
2196
2197 // watch_read and watch_write cannot both be false.
2198 assert(watch_read || watch_write);
2199 if (watch_read && watch_write)
2200 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002201 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002202 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002203 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002204 return eWatchpointWrite;
2205}
2206
Chris Lattner24943d22010-06-08 16:52:24 +00002207Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002208ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002209{
2210 Error error;
2211 if (wp)
2212 {
2213 user_id_t watchID = wp->GetID();
2214 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002215 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002216 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002217 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002218 if (wp->IsEnabled())
2219 {
2220 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002221 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002222 return error;
2223 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002224
2225 GDBStoppointType type = GetGDBStoppointType(wp);
2226 // Pass down an appropriate z/Z packet...
2227 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002228 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002229 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2230 {
2231 wp->SetEnabled(true);
2232 return error;
2233 }
2234 else
2235 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002236 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002237 else
2238 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002239 }
2240 else
2241 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002242 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002243 }
2244 if (error.Success())
2245 error.SetErrorToGenericError();
2246 return error;
2247}
2248
2249Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002250ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002251{
2252 Error error;
2253 if (wp)
2254 {
2255 user_id_t watchID = wp->GetID();
2256
Greg Claytone005f2c2010-11-06 01:53:30 +00002257 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002258
2259 addr_t addr = wp->GetLoadAddress();
2260 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002261 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002262
Johnny Chen21900fb2011-09-06 22:38:36 +00002263 if (!wp->IsEnabled())
2264 {
2265 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002266 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002267 return error;
2268 }
2269
Chris Lattner24943d22010-06-08 16:52:24 +00002270 if (wp->IsHardware())
2271 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002272 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002273 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002274 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2275 {
2276 wp->SetEnabled(false);
2277 return error;
2278 }
2279 else
2280 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002281 }
2282 // TODO: clear software watchpoints if we implement them
2283 }
2284 else
2285 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002286 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002287 }
2288 if (error.Success())
2289 error.SetErrorToGenericError();
2290 return error;
2291}
2292
2293void
2294ProcessGDBRemote::Clear()
2295{
2296 m_flags = 0;
2297 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002298}
2299
2300Error
2301ProcessGDBRemote::DoSignal (int signo)
2302{
2303 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002304 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002305 if (log)
2306 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2307
2308 if (!m_gdb_comm.SendAsyncSignal (signo))
2309 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2310 return error;
2311}
2312
Chris Lattner24943d22010-06-08 16:52:24 +00002313Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002314ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2315{
2316 ProcessLaunchInfo launch_info;
2317 return StartDebugserverProcess(debugserver_url, launch_info);
2318}
2319
2320Error
2321ProcessGDBRemote::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 +00002322{
2323 Error error;
2324 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2325 {
2326 // If we locate debugserver, keep that located version around
2327 static FileSpec g_debugserver_file_spec;
2328
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002329 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002330 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002331 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002332
2333 // Always check to see if we have an environment override for the path
2334 // to the debugserver to use and use it if we do.
2335 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2336 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002337 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002338 else
2339 debugserver_file_spec = g_debugserver_file_spec;
2340 bool debugserver_exists = debugserver_file_spec.Exists();
2341 if (!debugserver_exists)
2342 {
2343 // The debugserver binary is in the LLDB.framework/Resources
2344 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002345 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002346 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002347 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002348 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002349 if (debugserver_exists)
2350 {
2351 g_debugserver_file_spec = debugserver_file_spec;
2352 }
2353 else
2354 {
2355 g_debugserver_file_spec.Clear();
2356 debugserver_file_spec.Clear();
2357 }
Chris Lattner24943d22010-06-08 16:52:24 +00002358 }
2359 }
2360
2361 if (debugserver_exists)
2362 {
2363 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2364
2365 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002366
Greg Claytone005f2c2010-11-06 01:53:30 +00002367 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002368
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002369 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002370 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002371
Chris Lattner24943d22010-06-08 16:52:24 +00002372 // Start args with "debugserver /file/path -r --"
2373 debugserver_args.AppendArgument(debugserver_path);
2374 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002375 // use native registers, not the GDB registers
2376 debugserver_args.AppendArgument("--native-regs");
2377 // make debugserver run in its own session so signals generated by
2378 // special terminal key sequences (^C) don't affect debugserver
2379 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002380
Chris Lattner24943d22010-06-08 16:52:24 +00002381 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2382 if (env_debugserver_log_file)
2383 {
2384 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2385 debugserver_args.AppendArgument(arg_cstr);
2386 }
2387
2388 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2389 if (env_debugserver_log_flags)
2390 {
2391 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2392 debugserver_args.AppendArgument(arg_cstr);
2393 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002394// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002395// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002396
Greg Claytonb72d0f02011-04-12 05:54:46 +00002397 // We currently send down all arguments, attach pids, or attach
2398 // process names in dedicated GDB server packets, so we don't need
2399 // to pass them as arguments. This is currently because of all the
2400 // things we need to setup prior to launching: the environment,
2401 // current working dir, file actions, etc.
2402#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002403 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002404 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002405 {
Greg Claytona2f74232011-02-24 22:24:29 +00002406 // Terminate the debugserver args so we can now append the inferior args
2407 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002408
Greg Claytona2f74232011-02-24 22:24:29 +00002409 for (int i = 0; inferior_argv[i] != NULL; ++i)
2410 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002411 }
2412 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2413 {
2414 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2415 debugserver_args.AppendArgument (arg_cstr);
2416 }
2417 else if (attach_name && attach_name[0])
2418 {
2419 if (wait_for_launch)
2420 debugserver_args.AppendArgument ("--waitfor");
2421 else
2422 debugserver_args.AppendArgument ("--attach");
2423 debugserver_args.AppendArgument (attach_name);
2424 }
Chris Lattner24943d22010-06-08 16:52:24 +00002425#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002426
2427 ProcessLaunchInfo::FileAction file_action;
2428
2429 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2430 // to "/dev/null" if we run into any problems.
2431 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002432 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002433 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002434 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002435 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002436 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002437
2438 if (log)
2439 {
2440 StreamString strm;
2441 debugserver_args.Dump (&strm);
2442 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2443 }
2444
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002445 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2446 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002447
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002448 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002449
Greg Claytonb72d0f02011-04-12 05:54:46 +00002450 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002451 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002452 else
Chris Lattner24943d22010-06-08 16:52:24 +00002453 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2454
2455 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002456 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002457 }
2458 else
2459 {
Greg Clayton9c236732011-10-26 00:56:27 +00002460 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002461 }
2462
2463 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2464 StartAsyncThread ();
2465 }
2466 return error;
2467}
2468
2469bool
2470ProcessGDBRemote::MonitorDebugserverProcess
2471(
2472 void *callback_baton,
2473 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002474 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002475 int signo, // Zero for no signal
2476 int exit_status // Exit value of process if signal is zero
2477)
2478{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002479 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2480 // and might not exist anymore, so we need to carefully try to get the
2481 // target for this process first since we have a race condition when
2482 // we are done running between getting the notice that the inferior
2483 // process has died and the debugserver that was debugging this process.
2484 // In our test suite, we are also continually running process after
2485 // process, so we must be very careful to make sure:
2486 // 1 - process object hasn't been deleted already
2487 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002488
2489 // "debugserver_pid" argument passed in is the process ID for
2490 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002491 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002492
Greg Clayton75ccf502010-08-21 02:22:51 +00002493 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002494
Greg Clayton1c4642c2011-11-16 05:37:56 +00002495 // Get a shared pointer to the target that has a matching process pointer.
2496 // This target could be gone, or the target could already have a new process
2497 // object inside of it
2498 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2499
Greg Clayton72e1c782011-01-22 23:43:18 +00002500 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002501 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 +00002502
Greg Clayton1c4642c2011-11-16 05:37:56 +00002503 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002504 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002505 // We found a process in a target that matches, but another thread
2506 // might be in the process of launching a new process that will
2507 // soon replace it, so get a shared pointer to the process so we
2508 // can keep it alive.
2509 ProcessSP process_sp (target_sp->GetProcessSP());
2510 // Now we have a shared pointer to the process that can't go away on us
2511 // so we now make sure it was the same as the one passed in, and also make
2512 // sure that our previous "process *" didn't get deleted and have a new
2513 // "process *" created in its place with the same pointer. To verify this
2514 // we make sure the process has our debugserver process ID. If we pass all
2515 // of these tests, then we are sure that this process is the one we were
2516 // looking for.
2517 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002518 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002519 // Sleep for a half a second to make sure our inferior process has
2520 // time to set its exit status before we set it incorrectly when
2521 // both the debugserver and the inferior process shut down.
2522 usleep (500000);
2523 // If our process hasn't yet exited, debugserver might have died.
2524 // If the process did exit, the we are reaping it.
2525 const StateType state = process->GetState();
2526
2527 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2528 state != eStateInvalid &&
2529 state != eStateUnloaded &&
2530 state != eStateExited &&
2531 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002532 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002533 char error_str[1024];
2534 if (signo)
2535 {
2536 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2537 if (signal_cstr)
2538 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2539 else
2540 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2541 }
Chris Lattner24943d22010-06-08 16:52:24 +00002542 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002543 {
2544 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2545 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002546
Greg Clayton1c4642c2011-11-16 05:37:56 +00002547 process->SetExitStatus (-1, error_str);
2548 }
2549 // Debugserver has exited we need to let our ProcessGDBRemote
2550 // know that it no longer has a debugserver instance
2551 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002552 }
Chris Lattner24943d22010-06-08 16:52:24 +00002553 }
2554 return true;
2555}
2556
2557void
2558ProcessGDBRemote::KillDebugserverProcess ()
2559{
2560 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2561 {
2562 ::kill (m_debugserver_pid, SIGINT);
2563 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2564 }
2565}
2566
2567void
2568ProcessGDBRemote::Initialize()
2569{
2570 static bool g_initialized = false;
2571
2572 if (g_initialized == false)
2573 {
2574 g_initialized = true;
2575 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2576 GetPluginDescriptionStatic(),
2577 CreateInstance);
2578
2579 Log::Callbacks log_callbacks = {
2580 ProcessGDBRemoteLog::DisableLog,
2581 ProcessGDBRemoteLog::EnableLog,
2582 ProcessGDBRemoteLog::ListLogCategories
2583 };
2584
2585 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2586 }
2587}
2588
2589bool
Chris Lattner24943d22010-06-08 16:52:24 +00002590ProcessGDBRemote::StartAsyncThread ()
2591{
Greg Claytone005f2c2010-11-06 01:53:30 +00002592 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002593
2594 if (log)
2595 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2596
2597 // Create a thread that watches our internal state and controls which
2598 // events make it to clients (into the DCProcess event queue).
2599 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002600 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002601}
2602
2603void
2604ProcessGDBRemote::StopAsyncThread ()
2605{
Greg Claytone005f2c2010-11-06 01:53:30 +00002606 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002607
2608 if (log)
2609 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2610
2611 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002612
2613 // This will shut down the async thread.
2614 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002615
2616 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002617 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002618 {
2619 Host::ThreadJoin (m_async_thread, NULL, NULL);
2620 }
2621}
2622
2623
2624void *
2625ProcessGDBRemote::AsyncThread (void *arg)
2626{
2627 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2628
Greg Claytone005f2c2010-11-06 01:53:30 +00002629 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002630 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002631 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002632
2633 Listener listener ("ProcessGDBRemote::AsyncThread");
2634 EventSP event_sp;
2635 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2636 eBroadcastBitAsyncThreadShouldExit;
2637
2638 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2639 {
Greg Claytona2f74232011-02-24 22:24:29 +00002640 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2641
Chris Lattner24943d22010-06-08 16:52:24 +00002642 bool done = false;
2643 while (!done)
2644 {
2645 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002646 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002647 if (listener.WaitForEvent (NULL, event_sp))
2648 {
2649 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002650 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002651 {
Greg Claytona2f74232011-02-24 22:24:29 +00002652 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002653 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 +00002654
Greg Claytona2f74232011-02-24 22:24:29 +00002655 switch (event_type)
2656 {
2657 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002658 {
Greg Claytona2f74232011-02-24 22:24:29 +00002659 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002660
Greg Claytona2f74232011-02-24 22:24:29 +00002661 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002662 {
Greg Claytona2f74232011-02-24 22:24:29 +00002663 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2664 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2665 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002666 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002667
Greg Claytona2f74232011-02-24 22:24:29 +00002668 if (::strstr (continue_cstr, "vAttach") == NULL)
2669 process->SetPrivateState(eStateRunning);
2670 StringExtractorGDBRemote response;
2671 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002672
Greg Clayton67b402c2012-05-16 02:48:06 +00002673 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2674 // The thread ID list might be contained within the "response", or the stop reply packet that
2675 // caused the stop. So clear it now before we give the stop reply packet to the process
2676 // using the process->SetLastStopPacket()...
2677 process->ClearThreadIDList ();
2678
Greg Claytona2f74232011-02-24 22:24:29 +00002679 switch (stop_state)
2680 {
2681 case eStateStopped:
2682 case eStateCrashed:
2683 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002684 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002685 process->SetPrivateState (stop_state);
2686 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002687
Greg Claytona2f74232011-02-24 22:24:29 +00002688 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002689 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002690 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002691 response.SetFilePos(1);
2692 process->SetExitStatus(response.GetHexU8(), NULL);
2693 done = true;
2694 break;
2695
2696 case eStateInvalid:
2697 process->SetExitStatus(-1, "lost connection");
2698 break;
2699
2700 default:
2701 process->SetPrivateState (stop_state);
2702 break;
2703 }
Chris Lattner24943d22010-06-08 16:52:24 +00002704 }
2705 }
Greg Claytona2f74232011-02-24 22:24:29 +00002706 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002707
Greg Claytona2f74232011-02-24 22:24:29 +00002708 case eBroadcastBitAsyncThreadShouldExit:
2709 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002710 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002711 done = true;
2712 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002713
Greg Claytona2f74232011-02-24 22:24:29 +00002714 default:
2715 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002716 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 +00002717 done = true;
2718 break;
2719 }
2720 }
2721 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2722 {
2723 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2724 {
2725 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002726 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002727 }
Chris Lattner24943d22010-06-08 16:52:24 +00002728 }
2729 }
2730 else
2731 {
2732 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002733 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 +00002734 done = true;
2735 }
2736 }
2737 }
2738
2739 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002740 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002741
2742 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2743 return NULL;
2744}
2745
Chris Lattner24943d22010-06-08 16:52:24 +00002746const char *
2747ProcessGDBRemote::GetDispatchQueueNameForThread
2748(
2749 addr_t thread_dispatch_qaddr,
2750 std::string &dispatch_queue_name
2751)
2752{
2753 dispatch_queue_name.clear();
2754 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2755 {
2756 // Cache the dispatch_queue_offsets_addr value so we don't always have
2757 // to look it up
2758 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2759 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002760 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2761 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002762 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2763 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002764 if (module_sp)
2765 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2766
2767 if (dispatch_queue_offsets_symbol == NULL)
2768 {
Greg Clayton444fe992012-02-26 05:51:37 +00002769 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2770 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002771 if (module_sp)
2772 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2773 }
Chris Lattner24943d22010-06-08 16:52:24 +00002774 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002775 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002776
2777 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2778 return NULL;
2779 }
2780
2781 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002782 DataExtractor data (memory_buffer,
2783 sizeof(memory_buffer),
2784 m_target.GetArchitecture().GetByteOrder(),
2785 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002786
2787 // Excerpt from src/queue_private.h
2788 struct dispatch_queue_offsets_s
2789 {
2790 uint16_t dqo_version;
2791 uint16_t dqo_label;
2792 uint16_t dqo_label_size;
2793 } dispatch_queue_offsets;
2794
2795
2796 Error error;
2797 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2798 {
2799 uint32_t data_offset = 0;
2800 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2801 {
2802 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2803 {
2804 data_offset = 0;
2805 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2806 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2807 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2808 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2809 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2810 dispatch_queue_name.erase (bytes_read);
2811 }
2812 }
2813 }
2814 }
2815 if (dispatch_queue_name.empty())
2816 return NULL;
2817 return dispatch_queue_name.c_str();
2818}
2819
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002820//uint32_t
2821//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2822//{
2823// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2824// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2825// if (m_local_debugserver)
2826// {
2827// return Host::ListProcessesMatchingName (name, matches, pids);
2828// }
2829// else
2830// {
2831// // FIXME: Implement talking to the remote debugserver.
2832// return 0;
2833// }
2834//
2835//}
2836//
Jim Ingham55e01d82011-01-22 01:33:44 +00002837bool
2838ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2839 lldb_private::StoppointCallbackContext *context,
2840 lldb::user_id_t break_id,
2841 lldb::user_id_t break_loc_id)
2842{
2843 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2844 // run so I can stop it if that's what I want to do.
2845 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2846 if (log)
2847 log->Printf("Hit New Thread Notification breakpoint.");
2848 return false;
2849}
2850
2851
2852bool
2853ProcessGDBRemote::StartNoticingNewThreads()
2854{
Jim Ingham55e01d82011-01-22 01:33:44 +00002855 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002856 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002857 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002858 if (log && log->GetVerbose())
2859 log->Printf("Enabled noticing new thread breakpoint.");
2860 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002861 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002862 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002863 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002864 PlatformSP platform_sp (m_target.GetPlatform());
2865 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002866 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002867 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2868 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002869 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002870 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002871 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2872 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002873 }
2874 else
2875 {
2876 if (log)
2877 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002878 }
2879 }
2880 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002881 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002882}
2883
2884bool
2885ProcessGDBRemote::StopNoticingNewThreads()
2886{
Jim Inghamff276fe2011-02-08 05:19:01 +00002887 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002888 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002889 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002890
2891 if (m_thread_create_bp_sp)
2892 m_thread_create_bp_sp->SetEnabled(false);
2893
Jim Ingham55e01d82011-01-22 01:33:44 +00002894 return true;
2895}
2896
2897