blob: e0d22360156cc5c40b98e833bef9ae46e0a14186 [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>
Greg Clayton989816b2011-05-14 01:50:35 +000014#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000016#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000017#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000018
19// C++ Includes
20#include <algorithm>
21#include <map>
22
23// Other libraries and framework includes
24
Johnny Chenecd4feb2011-10-14 00:42:25 +000025#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000026#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Core/ArchSpec.h"
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000030#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Core/InputReader.h"
32#include "lldb/Core/Module.h"
33#include "lldb/Core/PluginManager.h"
34#include "lldb/Core/State.h"
Greg Clayton33559462012-04-13 21:24:18 +000035#include "lldb/Core/StreamFile.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Core/StreamString.h"
37#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000038#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000039#include "lldb/Host/TimeValue.h"
40#include "lldb/Symbol/ObjectFile.h"
41#include "lldb/Target/DynamicLoader.h"
42#include "lldb/Target/Target.h"
43#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000044#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000045#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046
47// Project includes
48#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000049#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jim Ingham06b84492012-07-04 00:35:43 +000050#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000051#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000052#include "GDBRemoteRegisterContext.h"
53#include "ProcessGDBRemote.h"
54#include "ProcessGDBRemoteLog.h"
55#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000056#include "StopInfoMachException.h"
57
Greg Clayton451fa822012-04-09 22:46:21 +000058namespace lldb
59{
60 // Provide a function that can easily dump the packet history if we know a
61 // ProcessGDBRemote * value (which we can get from logs or from debugging).
62 // We need the function in the lldb namespace so it makes it into the final
63 // executable since the LLDB shared library only exports stuff in the lldb
64 // namespace. This allows you to attach with a debugger and call this
65 // function and get the packet history dumped to a file.
66 void
67 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
68 {
Greg Clayton33559462012-04-13 21:24:18 +000069 lldb_private::StreamFile strm;
70 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
71 if (error.Success())
72 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000073 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000074}
Chris Lattner24943d22010-06-08 16:52:24 +000075
Chris Lattner24943d22010-06-08 16:52:24 +000076
77#define DEBUGSERVER_BASENAME "debugserver"
78using namespace lldb;
79using namespace lldb_private;
80
Jim Inghamf9600482011-03-29 21:45:47 +000081static bool rand_initialized = false;
82
Chris Lattner24943d22010-06-08 16:52:24 +000083static inline uint16_t
84get_random_port ()
85{
Jim Inghamf9600482011-03-29 21:45:47 +000086 if (!rand_initialized)
87 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000088 time_t seed = time(NULL);
89
Jim Inghamf9600482011-03-29 21:45:47 +000090 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000091 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000092 }
Stephen Wilson50daf772011-03-25 18:16:28 +000093 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000094}
95
96
97const char *
98ProcessGDBRemote::GetPluginNameStatic()
99{
Greg Claytonb1888f22011-03-19 01:12:21 +0000100 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000101}
102
103const char *
104ProcessGDBRemote::GetPluginDescriptionStatic()
105{
106 return "GDB Remote protocol based debugging plug-in.";
107}
108
109void
110ProcessGDBRemote::Terminate()
111{
112 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
113}
114
115
Greg Clayton46c9a352012-02-09 06:16:32 +0000116lldb::ProcessSP
117ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000118{
Greg Clayton46c9a352012-02-09 06:16:32 +0000119 lldb::ProcessSP process_sp;
120 if (crash_file_path == NULL)
121 process_sp.reset (new ProcessGDBRemote (target, listener));
122 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000123}
124
125bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000126ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000127{
Greg Clayton61ddf562011-10-21 21:41:45 +0000128 if (plugin_specified_by_name)
129 return true;
130
Chris Lattner24943d22010-06-08 16:52:24 +0000131 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000132 Module *exe_module = target.GetExecutableModulePointer();
133 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000134 {
135 ObjectFile *exe_objfile = exe_module->GetObjectFile();
136 // We can't debug core files...
137 switch (exe_objfile->GetType())
138 {
139 case ObjectFile::eTypeInvalid:
140 case ObjectFile::eTypeCoreFile:
141 case ObjectFile::eTypeDebugInfo:
142 case ObjectFile::eTypeObjectFile:
143 case ObjectFile::eTypeSharedLibrary:
144 case ObjectFile::eTypeStubLibrary:
145 return false;
146 case ObjectFile::eTypeExecutable:
147 case ObjectFile::eTypeDynamicLinker:
148 case ObjectFile::eTypeUnknown:
149 break;
150 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000151 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000152 }
Jim Ingham7508e732010-08-09 23:31:02 +0000153 // However, if there is no executable module, we return true since we might be preparing to attach.
154 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000155}
156
157//----------------------------------------------------------------------
158// ProcessGDBRemote constructor
159//----------------------------------------------------------------------
160ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
161 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000162 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000163 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000164 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000165 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000166 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000167 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000168 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000169 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000170 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000171 m_continue_c_tids (),
172 m_continue_C_tids (),
173 m_continue_s_tids (),
174 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000175 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000176 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000177 m_addr_to_mmap_size (),
178 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000179 m_waiting_for_attach (false),
180 m_destroy_tried_resuming (false)
Chris Lattner24943d22010-06-08 16:52:24 +0000181{
Greg Claytonff39f742011-04-01 00:29:43 +0000182 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
183 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000184 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000185}
186
187//----------------------------------------------------------------------
188// Destructor
189//----------------------------------------------------------------------
190ProcessGDBRemote::~ProcessGDBRemote()
191{
192 // m_mach_process.UnregisterNotificationCallbacks (this);
193 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000194 // We need to call finalize on the process before destroying ourselves
195 // to make sure all of the broadcaster cleanup goes as planned. If we
196 // destruct this class, then Process::~Process() might have problems
197 // trying to fully destroy the broadcaster.
198 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000199}
200
201//----------------------------------------------------------------------
202// PluginInterface
203//----------------------------------------------------------------------
204const char *
205ProcessGDBRemote::GetPluginName()
206{
207 return "Process debugging plug-in that uses the GDB remote protocol";
208}
209
210const char *
211ProcessGDBRemote::GetShortPluginName()
212{
213 return GetPluginNameStatic();
214}
215
216uint32_t
217ProcessGDBRemote::GetPluginVersion()
218{
219 return 1;
220}
221
222void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000223ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000224{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000225 if (!force && m_register_info.GetNumRegisters() > 0)
226 return;
227
228 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000229 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000230 uint32_t reg_offset = 0;
231 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000232 StringExtractorGDBRemote::ResponseType response_type;
233 for (response_type = StringExtractorGDBRemote::eResponse;
234 response_type == StringExtractorGDBRemote::eResponse;
235 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000236 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000237 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
238 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000239 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000240 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000241 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000242 response_type = response.GetResponseType();
243 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000244 {
245 std::string name;
246 std::string value;
247 ConstString reg_name;
248 ConstString alt_name;
249 ConstString set_name;
250 RegisterInfo reg_info = { NULL, // Name
251 NULL, // Alt name
252 0, // byte size
253 reg_offset, // offset
254 eEncodingUint, // encoding
255 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000256 {
257 LLDB_INVALID_REGNUM, // GCC reg num
258 LLDB_INVALID_REGNUM, // DWARF reg num
259 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000260 reg_num, // GDB reg num
261 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000262 },
263 NULL,
264 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000265 };
266
267 while (response.GetNameColonValue(name, value))
268 {
269 if (name.compare("name") == 0)
270 {
271 reg_name.SetCString(value.c_str());
272 }
273 else if (name.compare("alt-name") == 0)
274 {
275 alt_name.SetCString(value.c_str());
276 }
277 else if (name.compare("bitsize") == 0)
278 {
279 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
280 }
281 else if (name.compare("offset") == 0)
282 {
283 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000284 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000285 {
286 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000287 }
288 }
289 else if (name.compare("encoding") == 0)
290 {
291 if (value.compare("uint") == 0)
292 reg_info.encoding = eEncodingUint;
293 else if (value.compare("sint") == 0)
294 reg_info.encoding = eEncodingSint;
295 else if (value.compare("ieee754") == 0)
296 reg_info.encoding = eEncodingIEEE754;
297 else if (value.compare("vector") == 0)
298 reg_info.encoding = eEncodingVector;
299 }
300 else if (name.compare("format") == 0)
301 {
302 if (value.compare("binary") == 0)
303 reg_info.format = eFormatBinary;
304 else if (value.compare("decimal") == 0)
305 reg_info.format = eFormatDecimal;
306 else if (value.compare("hex") == 0)
307 reg_info.format = eFormatHex;
308 else if (value.compare("float") == 0)
309 reg_info.format = eFormatFloat;
310 else if (value.compare("vector-sint8") == 0)
311 reg_info.format = eFormatVectorOfSInt8;
312 else if (value.compare("vector-uint8") == 0)
313 reg_info.format = eFormatVectorOfUInt8;
314 else if (value.compare("vector-sint16") == 0)
315 reg_info.format = eFormatVectorOfSInt16;
316 else if (value.compare("vector-uint16") == 0)
317 reg_info.format = eFormatVectorOfUInt16;
318 else if (value.compare("vector-sint32") == 0)
319 reg_info.format = eFormatVectorOfSInt32;
320 else if (value.compare("vector-uint32") == 0)
321 reg_info.format = eFormatVectorOfUInt32;
322 else if (value.compare("vector-float32") == 0)
323 reg_info.format = eFormatVectorOfFloat32;
324 else if (value.compare("vector-uint128") == 0)
325 reg_info.format = eFormatVectorOfUInt128;
326 }
327 else if (name.compare("set") == 0)
328 {
329 set_name.SetCString(value.c_str());
330 }
331 else if (name.compare("gcc") == 0)
332 {
333 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
334 }
335 else if (name.compare("dwarf") == 0)
336 {
337 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
338 }
339 else if (name.compare("generic") == 0)
340 {
341 if (value.compare("pc") == 0)
342 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
343 else if (value.compare("sp") == 0)
344 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
345 else if (value.compare("fp") == 0)
346 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
347 else if (value.compare("ra") == 0)
348 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
349 else if (value.compare("flags") == 0)
350 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000351 else if (value.find("arg") == 0)
352 {
353 if (value.size() == 4)
354 {
355 switch (value[3])
356 {
357 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
358 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
359 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
360 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
361 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
362 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
363 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
364 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
365 }
366 }
367 }
Chris Lattner24943d22010-06-08 16:52:24 +0000368 }
369 }
370
Jason Molenda53d96862010-06-11 23:44:18 +0000371 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000372 assert (reg_info.byte_size != 0);
373 reg_offset += reg_info.byte_size;
374 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
375 }
376 }
377 else
378 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000379 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000380 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000381 }
382 }
383
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000384 // We didn't get anything if the accumulated reg_num is zero. See if we are
385 // debugging ARM and fill with a hard coded register set until we can get an
386 // updated debugserver down on the devices.
387 // On the other hand, if the accumulated reg_num is positive, see if we can
388 // add composite registers to the existing primordial ones.
389 bool from_scratch = (reg_num == 0);
390
391 const ArchSpec &target_arch = GetTarget().GetArchitecture();
392 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
393 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000394 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000395 if (remote_arch.IsValid()
396 && remote_arch.GetMachine() == llvm::Triple::arm
397 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
398 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000399 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000400 else if (target_arch.GetMachine() == llvm::Triple::arm)
401 {
402 m_register_info.HardcodeARMRegisters(from_scratch);
403 }
404
Johnny Chend2e30662012-05-22 00:57:05 +0000405 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000406 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
407 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000408 m_register_info.Addx86_64ConvenienceRegisters();
409
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000410 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000411 m_register_info.Finalize ();
412}
413
414Error
415ProcessGDBRemote::WillLaunch (Module* module)
416{
417 return WillLaunchOrAttach ();
418}
419
420Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000421ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000422{
423 return WillLaunchOrAttach ();
424}
425
426Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000427ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000428{
429 return WillLaunchOrAttach ();
430}
431
432Error
Greg Claytone71e2582011-02-04 01:58:07 +0000433ProcessGDBRemote::DoConnectRemote (const char *remote_url)
434{
435 Error error (WillLaunchOrAttach ());
436
437 if (error.Fail())
438 return error;
439
Greg Clayton180546b2011-04-30 01:09:13 +0000440 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000441
442 if (error.Fail())
443 return error;
444 StartAsyncThread ();
445
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000446 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000447 if (pid == LLDB_INVALID_PROCESS_ID)
448 {
449 // We don't have a valid process ID, so note that we are connected
450 // and could now request to launch or attach, or get remote process
451 // listings...
452 SetPrivateState (eStateConnected);
453 }
454 else
455 {
456 // We have a valid process
457 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000458 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000459 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000460 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000461 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000462 if (state == eStateStopped)
463 {
464 SetPrivateState (state);
465 }
466 else
Greg Claytond9919d32011-12-01 23:28:38 +0000467 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 +0000468 }
469 else
Greg Claytond9919d32011-12-01 23:28:38 +0000470 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 +0000471 }
Jason Molendacb740b32012-05-03 22:37:30 +0000472
473 if (error.Success()
474 && !GetTarget().GetArchitecture().IsValid()
475 && m_gdb_comm.GetHostArchitecture().IsValid())
476 {
477 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
478 }
479
Greg Claytone71e2582011-02-04 01:58:07 +0000480 return error;
481}
482
483Error
Chris Lattner24943d22010-06-08 16:52:24 +0000484ProcessGDBRemote::WillLaunchOrAttach ()
485{
486 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000487 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000488 return error;
489}
490
491//----------------------------------------------------------------------
492// Process Control
493//----------------------------------------------------------------------
494Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000495ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000496{
Greg Clayton4b407112010-09-30 21:49:03 +0000497 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000498
499 uint32_t launch_flags = launch_info.GetFlags().Get();
500 const char *stdin_path = NULL;
501 const char *stdout_path = NULL;
502 const char *stderr_path = NULL;
503 const char *working_dir = launch_info.GetWorkingDirectory();
504
505 const ProcessLaunchInfo::FileAction *file_action;
506 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
507 if (file_action)
508 {
509 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
510 stdin_path = file_action->GetPath();
511 }
512 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
513 if (file_action)
514 {
515 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
516 stdout_path = file_action->GetPath();
517 }
518 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
519 if (file_action)
520 {
521 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
522 stderr_path = file_action->GetPath();
523 }
524
Chris Lattner24943d22010-06-08 16:52:24 +0000525 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
526 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
527 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000528 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000529
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000530 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000531 if (object_file)
532 {
Chris Lattner24943d22010-06-08 16:52:24 +0000533 char host_port[128];
534 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000535 char connect_url[128];
536 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000537
Greg Claytona2f74232011-02-24 22:24:29 +0000538 // Make sure we aren't already connected?
539 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000540 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000541 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000542 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000543 {
Johnny Chenc143d622011-08-09 18:56:45 +0000544 if (log)
545 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000546 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000547 }
Chris Lattner24943d22010-06-08 16:52:24 +0000548
Greg Claytone71e2582011-02-04 01:58:07 +0000549 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000550 }
551
552 if (error.Success())
553 {
554 lldb_utility::PseudoTerminal pty;
555 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000556
557 // If the debugserver is local and we aren't disabling STDIO, lets use
558 // a pseudo terminal to instead of relying on the 'O' packets for stdio
559 // since 'O' packets can really slow down debugging if the inferior
560 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000561 PlatformSP platform_sp (m_target.GetPlatform());
562 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000563 {
564 const char *slave_name = NULL;
565 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000566 {
Greg Claytona2f74232011-02-24 22:24:29 +0000567 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
568 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000569 }
Greg Claytona2f74232011-02-24 22:24:29 +0000570 if (stdin_path == NULL)
571 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000572
Greg Claytona2f74232011-02-24 22:24:29 +0000573 if (stdout_path == NULL)
574 stdout_path = slave_name;
575
576 if (stderr_path == NULL)
577 stderr_path = slave_name;
578 }
579
Greg Claytonafb81862011-03-02 21:34:46 +0000580 // Set STDIN to /dev/null if we want STDIO disabled or if either
581 // STDOUT or STDERR have been set to something and STDIN hasn't
582 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000583 stdin_path = "/dev/null";
584
Greg Claytonafb81862011-03-02 21:34:46 +0000585 // Set STDOUT to /dev/null if we want STDIO disabled or if either
586 // STDIN or STDERR have been set to something and STDOUT hasn't
587 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000588 stdout_path = "/dev/null";
589
Greg Claytonafb81862011-03-02 21:34:46 +0000590 // Set STDERR to /dev/null if we want STDIO disabled or if either
591 // STDIN or STDOUT have been set to something and STDERR hasn't
592 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000593 stderr_path = "/dev/null";
594
595 if (stdin_path)
596 m_gdb_comm.SetSTDIN (stdin_path);
597 if (stdout_path)
598 m_gdb_comm.SetSTDOUT (stdout_path);
599 if (stderr_path)
600 m_gdb_comm.SetSTDERR (stderr_path);
601
602 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
603
Greg Claytona4582402011-05-08 04:53:50 +0000604 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000605
606 if (working_dir && working_dir[0])
607 {
608 m_gdb_comm.SetWorkingDir (working_dir);
609 }
610
611 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000612 const Args &environment = launch_info.GetEnvironmentEntries();
613 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000614 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000615 size_t num_environment_entries = environment.GetArgumentCount();
616 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000617 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000618 const char *env_entry = environment.GetArgumentAtIndex(i);
619 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000620 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000621 }
Greg Claytona2f74232011-02-24 22:24:29 +0000622 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000623
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000624 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000625 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000626 if (arg_packet_err == 0)
627 {
628 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000629 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000630 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000631 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000632 }
633 else
634 {
Greg Claytona2f74232011-02-24 22:24:29 +0000635 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000636 }
Greg Claytona2f74232011-02-24 22:24:29 +0000637 }
638 else
639 {
Greg Clayton9c236732011-10-26 00:56:27 +0000640 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000641 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000642
643 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000644
Greg Claytona2f74232011-02-24 22:24:29 +0000645 if (GetID() == LLDB_INVALID_PROCESS_ID)
646 {
Johnny Chenc143d622011-08-09 18:56:45 +0000647 if (log)
648 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000649 KillDebugserverProcess ();
650 return error;
651 }
652
Greg Clayton261a18b2011-06-02 22:22:38 +0000653 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000654 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000655 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000656
657 if (!disable_stdio)
658 {
659 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000660 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000661 }
Chris Lattner24943d22010-06-08 16:52:24 +0000662 }
663 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000664 else
665 {
Johnny Chenc143d622011-08-09 18:56:45 +0000666 if (log)
667 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000668 }
Chris Lattner24943d22010-06-08 16:52:24 +0000669 }
670 else
671 {
672 // Set our user ID to an invalid process ID.
673 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000674 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
675 exe_module->GetFileSpec().GetFilename().AsCString(),
676 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000677 }
Chris Lattner24943d22010-06-08 16:52:24 +0000678 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000679
Chris Lattner24943d22010-06-08 16:52:24 +0000680}
681
682
683Error
Greg Claytone71e2582011-02-04 01:58:07 +0000684ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000685{
686 Error error;
687 // Sleep and wait a bit for debugserver to start to listen...
688 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
689 if (conn_ap.get())
690 {
Chris Lattner24943d22010-06-08 16:52:24 +0000691 const uint32_t max_retry_count = 50;
692 uint32_t retry_count = 0;
693 while (!m_gdb_comm.IsConnected())
694 {
Greg Claytone71e2582011-02-04 01:58:07 +0000695 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000696 {
697 m_gdb_comm.SetConnection (conn_ap.release());
698 break;
699 }
700 retry_count++;
701
702 if (retry_count >= max_retry_count)
703 break;
704
705 usleep (100000);
706 }
707 }
708
709 if (!m_gdb_comm.IsConnected())
710 {
711 if (error.Success())
712 error.SetErrorString("not connected to remote gdb server");
713 return error;
714 }
715
Greg Clayton24bc5d92011-03-30 18:16:51 +0000716 // We always seem to be able to open a connection to a local port
717 // so we need to make sure we can then send data to it. If we can't
718 // then we aren't actually connected to anything, so try and do the
719 // handshake with the remote GDB server and make sure that goes
720 // alright.
721 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000722 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000723 m_gdb_comm.Disconnect();
724 if (error.Success())
725 error.SetErrorString("not connected to remote gdb server");
726 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000727 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000728 m_gdb_comm.ResetDiscoverableSettings();
729 m_gdb_comm.QueryNoAckModeSupported ();
730 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000731 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000732 m_gdb_comm.GetHostInfo ();
733 m_gdb_comm.GetVContSupported ('c');
Jim Ingham86827fb2012-07-02 05:40:07 +0000734
735 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
736 for (size_t idx = 0; idx < num_cmds; idx++)
737 {
738 StringExtractorGDBRemote response;
739 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx));
740 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
741 }
Chris Lattner24943d22010-06-08 16:52:24 +0000742 return error;
743}
744
745void
746ProcessGDBRemote::DidLaunchOrAttach ()
747{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000748 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
749 if (log)
750 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000751 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000752 {
753 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
754
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000755 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000756
Chris Lattner24943d22010-06-08 16:52:24 +0000757 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000758
Greg Claytoncb8977d2011-03-23 00:09:55 +0000759 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
760 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000761 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000762 ArchSpec &target_arch = GetTarget().GetArchitecture();
763
764 if (target_arch.IsValid())
765 {
766 // If the remote host is ARM and we have apple as the vendor, then
767 // ARM executables and shared libraries can have mixed ARM architectures.
768 // You can have an armv6 executable, and if the host is armv7, then the
769 // system will load the best possible architecture for all shared libraries
770 // it has, so we really need to take the remote host architecture as our
771 // defacto architecture in this case.
772
773 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
774 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
775 {
776 target_arch = gdb_remote_arch;
777 }
778 else
779 {
780 // Fill in what is missing in the triple
781 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
782 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000783 if (target_triple.getVendorName().size() == 0)
784 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000785 target_triple.setVendor (remote_triple.getVendor());
786
Greg Clayton2f085c62011-05-15 01:25:55 +0000787 if (target_triple.getOSName().size() == 0)
788 {
789 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000790
Greg Clayton2f085c62011-05-15 01:25:55 +0000791 if (target_triple.getEnvironmentName().size() == 0)
792 target_triple.setEnvironment (remote_triple.getEnvironment());
793 }
794 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000795 }
796 }
797 else
798 {
799 // The target doesn't have a valid architecture yet, set it from
800 // the architecture we got from the remote GDB server
801 target_arch = gdb_remote_arch;
802 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000803 }
Chris Lattner24943d22010-06-08 16:52:24 +0000804 }
805}
806
807void
808ProcessGDBRemote::DidLaunch ()
809{
810 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000811}
812
813Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000814ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000815{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000816 ProcessAttachInfo attach_info;
817 return DoAttachToProcessWithID(attach_pid, attach_info);
818}
819
820Error
821ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
822{
Chris Lattner24943d22010-06-08 16:52:24 +0000823 Error error;
824 // Clear out and clean up from any current state
825 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000826 if (attach_pid != LLDB_INVALID_PROCESS_ID)
827 {
Greg Claytona2f74232011-02-24 22:24:29 +0000828 // Make sure we aren't already connected?
829 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000830 {
Greg Claytona2f74232011-02-24 22:24:29 +0000831 char host_port[128];
832 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
833 char connect_url[128];
834 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000835
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000836 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000837
838 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000839 {
Greg Claytona2f74232011-02-24 22:24:29 +0000840 const char *error_string = error.AsCString();
841 if (error_string == NULL)
842 error_string = "unable to launch " DEBUGSERVER_BASENAME;
843
844 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000845 }
Greg Claytona2f74232011-02-24 22:24:29 +0000846 else
847 {
848 error = ConnectToDebugserver (connect_url);
849 }
850 }
851
852 if (error.Success())
853 {
854 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000855 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000856 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000857 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000858 }
859 }
Chris Lattner24943d22010-06-08 16:52:24 +0000860 return error;
861}
862
863size_t
864ProcessGDBRemote::AttachInputReaderCallback
865(
866 void *baton,
867 InputReader *reader,
868 lldb::InputReaderAction notification,
869 const char *bytes,
870 size_t bytes_len
871)
872{
873 if (notification == eInputReaderGotToken)
874 {
875 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
876 if (gdb_process->m_waiting_for_attach)
877 gdb_process->m_waiting_for_attach = false;
878 reader->SetIsDone(true);
879 return 1;
880 }
881 return 0;
882}
883
884Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000885ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000886{
887 Error error;
888 // Clear out and clean up from any current state
889 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000890
Chris Lattner24943d22010-06-08 16:52:24 +0000891 if (process_name && process_name[0])
892 {
Greg Claytona2f74232011-02-24 22:24:29 +0000893 // Make sure we aren't already connected?
894 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000895 {
Greg Claytona2f74232011-02-24 22:24:29 +0000896 char host_port[128];
897 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
898 char connect_url[128];
899 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
900
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000901 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000902 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000903 {
Greg Claytona2f74232011-02-24 22:24:29 +0000904 const char *error_string = error.AsCString();
905 if (error_string == NULL)
906 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000907
Greg Claytona2f74232011-02-24 22:24:29 +0000908 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000909 }
Greg Claytona2f74232011-02-24 22:24:29 +0000910 else
911 {
912 error = ConnectToDebugserver (connect_url);
913 }
914 }
915
916 if (error.Success())
917 {
918 StreamString packet;
919
920 if (wait_for_launch)
921 packet.PutCString("vAttachWait");
922 else
923 packet.PutCString("vAttachName");
924 packet.PutChar(';');
925 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
926
927 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
928
Chris Lattner24943d22010-06-08 16:52:24 +0000929 }
930 }
Chris Lattner24943d22010-06-08 16:52:24 +0000931 return error;
932}
933
Chris Lattner24943d22010-06-08 16:52:24 +0000934
935void
936ProcessGDBRemote::DidAttach ()
937{
Greg Claytone71e2582011-02-04 01:58:07 +0000938 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000939}
940
941Error
942ProcessGDBRemote::WillResume ()
943{
Greg Claytonc1f45872011-02-12 06:28:37 +0000944 m_continue_c_tids.clear();
945 m_continue_C_tids.clear();
946 m_continue_s_tids.clear();
947 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000948 return Error();
949}
950
951Error
952ProcessGDBRemote::DoResume ()
953{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000954 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000955 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
956 if (log)
957 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000958
959 Listener listener ("gdb-remote.resume-packet-sent");
960 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
961 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000962 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
963
Greg Claytonc1f45872011-02-12 06:28:37 +0000964 StreamString continue_packet;
965 bool continue_packet_error = false;
966 if (m_gdb_comm.HasAnyVContSupport ())
967 {
968 continue_packet.PutCString ("vCont");
969
970 if (!m_continue_c_tids.empty())
971 {
972 if (m_gdb_comm.GetVContSupported ('c'))
973 {
974 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 +0000975 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000976 }
977 else
978 continue_packet_error = true;
979 }
980
981 if (!continue_packet_error && !m_continue_C_tids.empty())
982 {
983 if (m_gdb_comm.GetVContSupported ('C'))
984 {
985 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 +0000986 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000987 }
988 else
989 continue_packet_error = true;
990 }
Greg Claytonb749a262010-12-03 06:02:24 +0000991
Greg Claytonc1f45872011-02-12 06:28:37 +0000992 if (!continue_packet_error && !m_continue_s_tids.empty())
993 {
994 if (m_gdb_comm.GetVContSupported ('s'))
995 {
996 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 +0000997 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000998 }
999 else
1000 continue_packet_error = true;
1001 }
1002
1003 if (!continue_packet_error && !m_continue_S_tids.empty())
1004 {
1005 if (m_gdb_comm.GetVContSupported ('S'))
1006 {
1007 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 +00001008 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001009 }
1010 else
1011 continue_packet_error = true;
1012 }
1013
1014 if (continue_packet_error)
1015 continue_packet.GetString().clear();
1016 }
1017 else
1018 continue_packet_error = true;
1019
1020 if (continue_packet_error)
1021 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001022 // Either no vCont support, or we tried to use part of the vCont
1023 // packet that wasn't supported by the remote GDB server.
1024 // We need to try and make a simple packet that can do our continue
1025 const size_t num_threads = GetThreadList().GetSize();
1026 const size_t num_continue_c_tids = m_continue_c_tids.size();
1027 const size_t num_continue_C_tids = m_continue_C_tids.size();
1028 const size_t num_continue_s_tids = m_continue_s_tids.size();
1029 const size_t num_continue_S_tids = m_continue_S_tids.size();
1030 if (num_continue_c_tids > 0)
1031 {
1032 if (num_continue_c_tids == num_threads)
1033 {
1034 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001035 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001036 continue_packet.PutChar ('c');
1037 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001038 }
1039 else if (num_continue_c_tids == 1 &&
1040 num_continue_C_tids == 0 &&
1041 num_continue_s_tids == 0 &&
1042 num_continue_S_tids == 0 )
1043 {
1044 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001045 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001046 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001047 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001048 }
1049 }
1050
Greg Claytonde1dd812011-06-24 03:21:43 +00001051 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001052 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001053 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1054 num_continue_C_tids > 0 &&
1055 num_continue_s_tids == 0 &&
1056 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001057 {
1058 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001059 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001060 if (num_continue_C_tids > 1)
1061 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001062 // More that one thread with a signal, yet we don't have
1063 // vCont support and we are being asked to resume each
1064 // thread with a signal, we need to make sure they are
1065 // all the same signal, or we can't issue the continue
1066 // accurately with the current support...
1067 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001068 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001069 continue_packet_error = false;
1070 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1071 {
1072 if (m_continue_C_tids[i].second != continue_signo)
1073 continue_packet_error = true;
1074 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001075 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001076 if (!continue_packet_error)
1077 m_gdb_comm.SetCurrentThreadForRun (-1);
1078 }
1079 else
1080 {
1081 // Set the continue thread ID
1082 continue_packet_error = false;
1083 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001084 }
1085 if (!continue_packet_error)
1086 {
1087 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001088 continue_packet.Printf("C%2.2x", continue_signo);
1089 }
1090 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001091 }
1092
Greg Claytonde1dd812011-06-24 03:21:43 +00001093 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001094 {
1095 if (num_continue_s_tids == num_threads)
1096 {
1097 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001098 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001099 continue_packet.PutChar ('s');
1100 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001101 }
1102 else if (num_continue_c_tids == 0 &&
1103 num_continue_C_tids == 0 &&
1104 num_continue_s_tids == 1 &&
1105 num_continue_S_tids == 0 )
1106 {
1107 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001108 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001109 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001110 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001111 }
1112 }
1113
1114 if (!continue_packet_error && num_continue_S_tids > 0)
1115 {
1116 if (num_continue_S_tids == num_threads)
1117 {
1118 const int step_signo = m_continue_S_tids.front().second;
1119 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001120 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001121 if (num_continue_S_tids > 1)
1122 {
1123 for (size_t i=1; i<num_threads; ++i)
1124 {
1125 if (m_continue_S_tids[i].second != step_signo)
1126 continue_packet_error = true;
1127 }
1128 }
1129 if (!continue_packet_error)
1130 {
1131 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001132 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001133 continue_packet.Printf("S%2.2x", step_signo);
1134 }
1135 }
1136 else if (num_continue_c_tids == 0 &&
1137 num_continue_C_tids == 0 &&
1138 num_continue_s_tids == 0 &&
1139 num_continue_S_tids == 1 )
1140 {
1141 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001142 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001143 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001144 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001145 }
1146 }
1147 }
1148
1149 if (continue_packet_error)
1150 {
1151 error.SetErrorString ("can't make continue packet for this resume");
1152 }
1153 else
1154 {
1155 EventSP event_sp;
1156 TimeValue timeout;
1157 timeout = TimeValue::Now();
1158 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001159 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1160 {
1161 error.SetErrorString ("Trying to resume but the async thread is dead.");
1162 if (log)
1163 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1164 return error;
1165 }
1166
Greg Claytonc1f45872011-02-12 06:28:37 +00001167 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1168
1169 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001170 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001171 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001172 if (log)
1173 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1174 }
1175 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1176 {
1177 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1178 if (log)
1179 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1180 return error;
1181 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001182 }
Greg Claytonb749a262010-12-03 06:02:24 +00001183 }
1184
Jim Ingham3ae449a2010-11-17 02:32:00 +00001185 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001186}
1187
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001188void
1189ProcessGDBRemote::ClearThreadIDList ()
1190{
Greg Claytonff3448e2012-04-13 02:11:32 +00001191 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001192 m_thread_ids.clear();
1193}
1194
1195bool
1196ProcessGDBRemote::UpdateThreadIDList ()
1197{
Greg Claytonff3448e2012-04-13 02:11:32 +00001198 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001199 bool sequence_mutex_unavailable = false;
1200 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1201 if (sequence_mutex_unavailable)
1202 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001203 return false; // We just didn't get the list
1204 }
1205 return true;
1206}
1207
Greg Claytonae932352012-04-10 00:18:59 +00001208bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001209ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001210{
1211 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001212 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001213 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001214 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001215
1216 size_t num_thread_ids = m_thread_ids.size();
1217 // The "m_thread_ids" thread ID list should always be updated after each stop
1218 // reply packet, but in case it isn't, update it here.
1219 if (num_thread_ids == 0)
1220 {
1221 if (!UpdateThreadIDList ())
1222 return false;
1223 num_thread_ids = m_thread_ids.size();
1224 }
Chris Lattner24943d22010-06-08 16:52:24 +00001225
Greg Clayton37f962e2011-08-22 02:49:39 +00001226 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001227 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001228 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001229 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001230 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001231 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1232 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001233 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001234 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001235 }
Chris Lattner24943d22010-06-08 16:52:24 +00001236 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001237
Greg Claytonae932352012-04-10 00:18:59 +00001238 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001239}
1240
1241
1242StateType
1243ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1244{
Greg Clayton261a18b2011-06-02 22:22:38 +00001245 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001246 const char stop_type = stop_packet.GetChar();
1247 switch (stop_type)
1248 {
1249 case 'T':
1250 case 'S':
1251 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001252 if (GetStopID() == 0)
1253 {
1254 // Our first stop, make sure we have a process ID, and also make
1255 // sure we know about our registers
1256 if (GetID() == LLDB_INVALID_PROCESS_ID)
1257 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001258 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001259 if (pid != LLDB_INVALID_PROCESS_ID)
1260 SetID (pid);
1261 }
1262 BuildDynamicRegisterInfo (true);
1263 }
Chris Lattner24943d22010-06-08 16:52:24 +00001264 // Stop with signal and thread info
1265 const uint8_t signo = stop_packet.GetHexU8();
1266 std::string name;
1267 std::string value;
1268 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001269 std::string reason;
1270 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001271 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001272 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001273 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1274 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001275 ThreadSP thread_sp;
1276
Chris Lattner24943d22010-06-08 16:52:24 +00001277 while (stop_packet.GetNameColonValue(name, value))
1278 {
1279 if (name.compare("metype") == 0)
1280 {
1281 // exception type in big endian hex
1282 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1283 }
1284 else if (name.compare("mecount") == 0)
1285 {
1286 // exception count in big endian hex
1287 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1288 }
1289 else if (name.compare("medata") == 0)
1290 {
1291 // exception data in big endian hex
1292 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1293 }
1294 else if (name.compare("thread") == 0)
1295 {
1296 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001297 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001298 // m_thread_list does have its own mutex, but we need to
1299 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1300 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001301 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001302 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001303 if (!thread_sp)
1304 {
1305 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001306 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001307 m_thread_list.AddThread(thread_sp);
1308 }
Chris Lattner24943d22010-06-08 16:52:24 +00001309 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001310 else if (name.compare("threads") == 0)
1311 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001312 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001313 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001314 // A comma separated list of all threads in the current
1315 // process that includes the thread for this stop reply
1316 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001317 size_t comma_pos;
1318 lldb::tid_t tid;
1319 while ((comma_pos = value.find(',')) != std::string::npos)
1320 {
1321 value[comma_pos] = '\0';
1322 // thread in big endian hex
1323 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1324 if (tid != LLDB_INVALID_THREAD_ID)
1325 m_thread_ids.push_back (tid);
1326 value.erase(0, comma_pos + 1);
1327
1328 }
1329 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1330 if (tid != LLDB_INVALID_THREAD_ID)
1331 m_thread_ids.push_back (tid);
1332 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001333 else if (name.compare("hexname") == 0)
1334 {
1335 StringExtractor name_extractor;
1336 // Swap "value" over into "name_extractor"
1337 name_extractor.GetStringRef().swap(value);
1338 // Now convert the HEX bytes into a string value
1339 name_extractor.GetHexByteString (value);
1340 thread_name.swap (value);
1341 }
Chris Lattner24943d22010-06-08 16:52:24 +00001342 else if (name.compare("name") == 0)
1343 {
1344 thread_name.swap (value);
1345 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001346 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001347 {
1348 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1349 }
Greg Clayton65611552011-06-04 01:26:29 +00001350 else if (name.compare("reason") == 0)
1351 {
1352 reason.swap(value);
1353 }
1354 else if (name.compare("description") == 0)
1355 {
1356 StringExtractor desc_extractor;
1357 // Swap "value" over into "name_extractor"
1358 desc_extractor.GetStringRef().swap(value);
1359 // Now convert the HEX bytes into a string value
1360 desc_extractor.GetHexByteString (thread_name);
1361 }
Greg Claytona875b642011-01-09 21:07:35 +00001362 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1363 {
1364 // We have a register number that contains an expedited
1365 // register value. Lets supply this register to our thread
1366 // so it won't have to go and read it.
1367 if (thread_sp)
1368 {
1369 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1370
1371 if (reg != UINT32_MAX)
1372 {
1373 StringExtractor reg_value_extractor;
1374 // Swap "value" over into "reg_value_extractor"
1375 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001376 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1377 {
1378 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1379 name.c_str(),
1380 reg,
1381 reg,
1382 reg_value_extractor.GetStringRef().c_str(),
1383 stop_packet.GetStringRef().c_str());
1384 }
Greg Claytona875b642011-01-09 21:07:35 +00001385 }
1386 }
1387 }
Chris Lattner24943d22010-06-08 16:52:24 +00001388 }
Chris Lattner24943d22010-06-08 16:52:24 +00001389
1390 if (thread_sp)
1391 {
1392 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1393
1394 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001395 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001396 if (exc_type != 0)
1397 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001398 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001399
1400 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1401 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001402 exc_data_size,
1403 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001404 exc_data_size >= 2 ? exc_data[1] : 0,
1405 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001406 }
Greg Clayton65611552011-06-04 01:26:29 +00001407 else
Chris Lattner24943d22010-06-08 16:52:24 +00001408 {
Greg Clayton65611552011-06-04 01:26:29 +00001409 bool handled = false;
1410 if (!reason.empty())
1411 {
1412 if (reason.compare("trace") == 0)
1413 {
1414 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1415 handled = true;
1416 }
1417 else if (reason.compare("breakpoint") == 0)
1418 {
1419 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001420 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001421 if (bp_site_sp)
1422 {
1423 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1424 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1425 // 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 +00001426 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001427 if (bp_site_sp->ValidForThisThread (gdb_thread))
1428 {
1429 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001430 }
1431 else
1432 {
1433 StopInfoSP invalid_stop_info_sp;
1434 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001435 }
1436 }
1437
Greg Clayton65611552011-06-04 01:26:29 +00001438 }
1439 else if (reason.compare("trap") == 0)
1440 {
1441 // Let the trap just use the standard signal stop reason below...
1442 }
1443 else if (reason.compare("watchpoint") == 0)
1444 {
1445 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1446 // TODO: locate the watchpoint somehow...
1447 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1448 handled = true;
1449 }
1450 else if (reason.compare("exception") == 0)
1451 {
1452 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1453 handled = true;
1454 }
1455 }
1456
1457 if (signo)
1458 {
1459 if (signo == SIGTRAP)
1460 {
1461 // Currently we are going to assume SIGTRAP means we are either
1462 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001463 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001464 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001465 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001466
Greg Clayton65611552011-06-04 01:26:29 +00001467 if (bp_site_sp)
1468 {
1469 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1470 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1471 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1472 if (bp_site_sp->ValidForThisThread (gdb_thread))
1473 {
1474 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001475 }
1476 else
1477 {
1478 StopInfoSP invalid_stop_info_sp;
1479 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001480 }
1481 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001482 else
Greg Clayton65611552011-06-04 01:26:29 +00001483 {
1484 // TODO: check for breakpoint or trap opcode in case there is a hard
1485 // coded software trap
1486 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton65611552011-06-04 01:26:29 +00001487 }
1488 }
1489 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001490 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001491 }
1492 else
1493 {
Greg Clayton643ee732010-08-04 01:40:35 +00001494 StopInfoSP invalid_stop_info_sp;
1495 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001496 }
Greg Clayton65611552011-06-04 01:26:29 +00001497
1498 if (!description.empty())
1499 {
1500 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1501 if (stop_info_sp)
1502 {
1503 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001504 }
Greg Clayton65611552011-06-04 01:26:29 +00001505 else
1506 {
1507 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1508 }
1509 }
1510 }
Chris Lattner24943d22010-06-08 16:52:24 +00001511 }
1512 return eStateStopped;
1513 }
1514 break;
1515
1516 case 'W':
1517 // process exited
1518 return eStateExited;
1519
1520 default:
1521 break;
1522 }
1523 return eStateInvalid;
1524}
1525
1526void
1527ProcessGDBRemote::RefreshStateAfterStop ()
1528{
Greg Claytonff3448e2012-04-13 02:11:32 +00001529 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001530 m_thread_ids.clear();
1531 // Set the thread stop info. It might have a "threads" key whose value is
1532 // a list of all thread IDs in the current process, so m_thread_ids might
1533 // get set.
1534 SetThreadStopInfo (m_last_stop_packet);
1535 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1536 if (m_thread_ids.empty())
1537 {
1538 // No, we need to fetch the thread list manually
1539 UpdateThreadIDList();
1540 }
1541
Chris Lattner24943d22010-06-08 16:52:24 +00001542 // Let all threads recover from stopping and do any clean up based
1543 // on the previous thread state (if any).
1544 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001545
Chris Lattner24943d22010-06-08 16:52:24 +00001546}
1547
1548Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001549ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001550{
1551 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001552
Greg Claytona4881d02011-01-22 07:12:45 +00001553 bool timed_out = false;
1554 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001555
1556 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001557 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001558 // We are being asked to halt during an attach. We need to just close
1559 // our file handle and debugserver will go away, and we can be done...
1560 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001561 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001562 else
1563 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001564 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001565 {
1566 if (timed_out)
1567 error.SetErrorString("timed out sending interrupt packet");
1568 else
1569 error.SetErrorString("unknown error sending interrupt packet");
1570 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001571
1572 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001573 }
Chris Lattner24943d22010-06-08 16:52:24 +00001574 return error;
1575}
1576
1577Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001578ProcessGDBRemote::InterruptIfRunning
1579(
1580 bool discard_thread_plans,
1581 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001582 EventSP &stop_event_sp
1583)
Chris Lattner24943d22010-06-08 16:52:24 +00001584{
1585 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001586
Greg Clayton2860ba92011-01-23 19:58:49 +00001587 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1588
Greg Clayton68ca8232011-01-25 02:58:48 +00001589 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001590 const bool is_running = m_gdb_comm.IsRunning();
1591 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001592 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001593 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001594 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001595 is_running);
1596
Greg Clayton2860ba92011-01-23 19:58:49 +00001597 if (discard_thread_plans)
1598 {
1599 if (log)
1600 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1601 m_thread_list.DiscardThreadPlans();
1602 }
1603 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001604 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001605 if (catch_stop_event)
1606 {
1607 if (log)
1608 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1609 PausePrivateStateThread();
1610 paused_private_state_thread = true;
1611 }
1612
Greg Clayton4fb400f2010-09-27 21:07:38 +00001613 bool timed_out = false;
1614 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001615
Greg Clayton05e4d972012-03-29 01:55:41 +00001616 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001617 {
1618 if (timed_out)
1619 error.SetErrorString("timed out sending interrupt packet");
1620 else
1621 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001622 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001623 ResumePrivateStateThread();
1624 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001625 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001626
Greg Clayton72e1c782011-01-22 23:43:18 +00001627 if (catch_stop_event)
1628 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001629 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001630 TimeValue timeout_time;
1631 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001632 timeout_time.OffsetWithSeconds(5);
1633 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001634
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001635 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001636 if (log)
1637 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001638
Greg Clayton2860ba92011-01-23 19:58:49 +00001639 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001640 error.SetErrorString("unable to verify target stopped");
1641 }
1642
Greg Clayton68ca8232011-01-25 02:58:48 +00001643 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001644 {
1645 if (log)
1646 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001647 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001648 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001649 }
Chris Lattner24943d22010-06-08 16:52:24 +00001650 return error;
1651}
1652
Greg Clayton4fb400f2010-09-27 21:07:38 +00001653Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001654ProcessGDBRemote::WillDetach ()
1655{
Greg Clayton2860ba92011-01-23 19:58:49 +00001656 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1657 if (log)
1658 log->Printf ("ProcessGDBRemote::WillDetach()");
1659
Greg Clayton72e1c782011-01-22 23:43:18 +00001660 bool discard_thread_plans = true;
1661 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001662 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001663
1664 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1665 // needed. This shouldn't be a feature of a particular plugin.
1666
Greg Clayton68ca8232011-01-25 02:58:48 +00001667 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001668}
1669
1670Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001671ProcessGDBRemote::DoDetach()
1672{
1673 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001674 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001675 if (log)
1676 log->Printf ("ProcessGDBRemote::DoDetach()");
1677
1678 DisableAllBreakpointSites ();
1679
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001680 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001681
Greg Clayton516f0842012-04-11 00:24:49 +00001682 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001683 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001684 {
Greg Clayton516f0842012-04-11 00:24:49 +00001685 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001686 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1687 else
1688 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001689 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001690 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001691 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001692
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001693 SetPrivateState (eStateDetached);
1694 ResumePrivateStateThread();
1695
1696 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001697 return error;
1698}
Chris Lattner24943d22010-06-08 16:52:24 +00001699
Jim Ingham06b84492012-07-04 00:35:43 +00001700
Chris Lattner24943d22010-06-08 16:52:24 +00001701Error
1702ProcessGDBRemote::DoDestroy ()
1703{
1704 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001705 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001706 if (log)
1707 log->Printf ("ProcessGDBRemote::DoDestroy()");
1708
Jim Ingham06b84492012-07-04 00:35:43 +00001709 // There is a bug in older iOS debugservers where they don't shut down the process
1710 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1711 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1712 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1713 // destroy it again.
1714 //
1715 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1716 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1717 // the debugservers with this bug are equal. There really should be a better way to test this!
1718 //
1719 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1720 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1721 // just do the straight-forward kill.
1722 //
1723 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1724 // necessary (or helpful) to do any of this.
1725
1726 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1727 {
1728 PlatformSP platform_sp = GetTarget().GetPlatform();
1729
1730 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1731 if (platform_sp
1732 && platform_sp->GetName()
1733 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1734 {
1735 if (m_destroy_tried_resuming)
1736 {
1737 if (log)
1738 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1739 }
1740 else
1741 {
1742 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1743 // but we really need it to happen here and it doesn't matter if we do it twice.
1744 m_thread_list.DiscardThreadPlans();
1745 DisableAllBreakpointSites();
1746
1747 bool stop_looks_like_crash = false;
1748 ThreadList &threads = GetThreadList();
1749
1750 {
1751 Mutex::Locker(threads.GetMutex());
1752
1753 size_t num_threads = threads.GetSize();
1754 for (size_t i = 0; i < num_threads; i++)
1755 {
1756 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1757 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1758 StopReason reason = eStopReasonInvalid;
1759 if (stop_info_sp)
1760 reason = stop_info_sp->GetStopReason();
1761 if (reason == eStopReasonBreakpoint
1762 || reason == eStopReasonException)
1763 {
1764 if (log)
1765 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1766 thread_sp->GetID(),
1767 stop_info_sp->GetDescription());
1768 stop_looks_like_crash = true;
1769 break;
1770 }
1771 }
1772 }
1773
1774 if (stop_looks_like_crash)
1775 {
1776 if (log)
1777 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1778 m_destroy_tried_resuming = true;
1779
1780 // If we are going to run again before killing, it would be good to suspend all the threads
1781 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1782 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1783 // have to run the risk of letting those threads proceed a bit.
1784
1785 {
1786 Mutex::Locker(threads.GetMutex());
1787
1788 size_t num_threads = threads.GetSize();
1789 for (size_t i = 0; i < num_threads; i++)
1790 {
1791 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1792 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1793 StopReason reason = eStopReasonInvalid;
1794 if (stop_info_sp)
1795 reason = stop_info_sp->GetStopReason();
1796 if (reason != eStopReasonBreakpoint
1797 && reason != eStopReasonException)
1798 {
1799 if (log)
1800 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1801 thread_sp->GetID());
1802 thread_sp->SetResumeState(eStateSuspended);
1803 }
1804 }
1805 }
1806 Resume ();
1807 return Destroy();
1808 }
1809 }
1810 }
1811 }
1812
Chris Lattner24943d22010-06-08 16:52:24 +00001813 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001814 int exit_status = SIGABRT;
1815 std::string exit_string;
1816
Greg Claytona4881d02011-01-22 07:12:45 +00001817 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001818 {
Jim Ingham8226e942011-10-28 01:11:35 +00001819 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001820 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001821
1822 StringExtractorGDBRemote response;
1823 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001824 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001825 {
1826 char packet_cmd = response.GetChar(0);
1827
1828 if (packet_cmd == 'W' || packet_cmd == 'X')
1829 {
Greg Clayton06709002011-12-06 04:51:14 +00001830 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001831 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001832 exit_status = response.GetHexU8();
1833 }
1834 else
1835 {
1836 if (log)
1837 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1838 exit_string.assign("got unexpected response to k packet: ");
1839 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001840 }
1841 }
1842 else
1843 {
Jim Ingham8247e622012-06-06 00:32:39 +00001844 if (log)
1845 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1846 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001847 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001848 }
Jim Ingham8247e622012-06-06 00:32:39 +00001849 else
1850 {
1851 if (log)
1852 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1853 exit_string.assign ("killing while attaching.");
1854 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001855 }
Jim Ingham8247e622012-06-06 00:32:39 +00001856 else
1857 {
1858 // If we missed setting the exit status on the way out, do it here.
1859 // NB set exit status can be called multiple times, the first one sets the status.
1860 exit_string.assign("destroying when not connected to debugserver");
1861 }
1862
1863 SetExitStatus(exit_status, exit_string.c_str());
1864
Chris Lattner24943d22010-06-08 16:52:24 +00001865 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001866 KillDebugserverProcess ();
1867 return error;
1868}
1869
Chris Lattner24943d22010-06-08 16:52:24 +00001870//------------------------------------------------------------------
1871// Process Queries
1872//------------------------------------------------------------------
1873
1874bool
1875ProcessGDBRemote::IsAlive ()
1876{
Greg Clayton58e844b2010-12-08 05:08:21 +00001877 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001878}
1879
1880addr_t
1881ProcessGDBRemote::GetImageInfoAddress()
1882{
Greg Clayton516f0842012-04-11 00:24:49 +00001883 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001884}
1885
Chris Lattner24943d22010-06-08 16:52:24 +00001886//------------------------------------------------------------------
1887// Process Memory
1888//------------------------------------------------------------------
1889size_t
1890ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1891{
1892 if (size > m_max_memory_size)
1893 {
1894 // Keep memory read sizes down to a sane limit. This function will be
1895 // called multiple times in order to complete the task by
1896 // lldb_private::Process so it is ok to do this.
1897 size = m_max_memory_size;
1898 }
1899
1900 char packet[64];
1901 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1902 assert (packet_len + 1 < sizeof(packet));
1903 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001904 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001905 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001906 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001907 {
1908 error.Clear();
1909 return response.GetHexBytes(buf, size, '\xdd');
1910 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001911 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001912 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001913 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001914 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1915 else
1916 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1917 }
1918 else
1919 {
1920 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1921 }
1922 return 0;
1923}
1924
1925size_t
1926ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1927{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001928 if (size > m_max_memory_size)
1929 {
1930 // Keep memory read sizes down to a sane limit. This function will be
1931 // called multiple times in order to complete the task by
1932 // lldb_private::Process so it is ok to do this.
1933 size = m_max_memory_size;
1934 }
1935
Chris Lattner24943d22010-06-08 16:52:24 +00001936 StreamString packet;
1937 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001938 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001939 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001940 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001941 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001942 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001943 {
1944 error.Clear();
1945 return size;
1946 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001947 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001948 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001949 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001950 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1951 else
1952 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1953 }
1954 else
1955 {
1956 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1957 }
1958 return 0;
1959}
1960
1961lldb::addr_t
1962ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1963{
Greg Clayton989816b2011-05-14 01:50:35 +00001964 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1965
Greg Clayton2f085c62011-05-15 01:25:55 +00001966 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001967 switch (supported)
1968 {
1969 case eLazyBoolCalculate:
1970 case eLazyBoolYes:
1971 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1972 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1973 return allocated_addr;
1974
1975 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001976 // Call mmap() to create memory in the inferior..
1977 unsigned prot = 0;
1978 if (permissions & lldb::ePermissionsReadable)
1979 prot |= eMmapProtRead;
1980 if (permissions & lldb::ePermissionsWritable)
1981 prot |= eMmapProtWrite;
1982 if (permissions & lldb::ePermissionsExecutable)
1983 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001984
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001985 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1986 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1987 m_addr_to_mmap_size[allocated_addr] = size;
1988 else
1989 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001990 break;
1991 }
1992
Chris Lattner24943d22010-06-08 16:52:24 +00001993 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001994 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001995 else
1996 error.Clear();
1997 return allocated_addr;
1998}
1999
2000Error
Greg Claytona9385532011-11-18 07:03:08 +00002001ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2002 MemoryRegionInfo &region_info)
2003{
2004
2005 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2006 return error;
2007}
2008
2009Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002010ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2011{
2012
2013 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2014 return error;
2015}
2016
2017Error
Chris Lattner24943d22010-06-08 16:52:24 +00002018ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2019{
2020 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002021 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2022
2023 switch (supported)
2024 {
2025 case eLazyBoolCalculate:
2026 // We should never be deallocating memory without allocating memory
2027 // first so we should never get eLazyBoolCalculate
2028 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2029 break;
2030
2031 case eLazyBoolYes:
2032 if (!m_gdb_comm.DeallocateMemory (addr))
2033 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2034 break;
2035
2036 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002037 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002038 {
2039 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002040 if (pos != m_addr_to_mmap_size.end() &&
2041 InferiorCallMunmap(this, addr, pos->second))
2042 m_addr_to_mmap_size.erase (pos);
2043 else
2044 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002045 }
2046 break;
2047 }
2048
Chris Lattner24943d22010-06-08 16:52:24 +00002049 return error;
2050}
2051
2052
2053//------------------------------------------------------------------
2054// Process STDIO
2055//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002056size_t
2057ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2058{
2059 if (m_stdio_communication.IsConnected())
2060 {
2061 ConnectionStatus status;
2062 m_stdio_communication.Write(src, src_len, status, NULL);
2063 }
2064 return 0;
2065}
2066
2067Error
2068ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2069{
2070 Error error;
2071 assert (bp_site != NULL);
2072
Greg Claytone005f2c2010-11-06 01:53:30 +00002073 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002074 user_id_t site_id = bp_site->GetID();
2075 const addr_t addr = bp_site->GetLoadAddress();
2076 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002077 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002078
2079 if (bp_site->IsEnabled())
2080 {
2081 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002082 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 +00002083 return error;
2084 }
2085 else
2086 {
2087 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2088
2089 if (bp_site->HardwarePreferred())
2090 {
2091 // Try and set hardware breakpoint, and if that fails, fall through
2092 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002093 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002094 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002095 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002096 {
2097 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002098 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002099 return error;
2100 }
Chris Lattner24943d22010-06-08 16:52:24 +00002101 }
2102 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002103
2104 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002105 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002106 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2107 {
2108 bp_site->SetEnabled(true);
2109 bp_site->SetType (BreakpointSite::eExternal);
2110 return error;
2111 }
Chris Lattner24943d22010-06-08 16:52:24 +00002112 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002113
2114 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002115 }
2116
2117 if (log)
2118 {
2119 const char *err_string = error.AsCString();
2120 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2121 bp_site->GetLoadAddress(),
2122 err_string ? err_string : "NULL");
2123 }
2124 // We shouldn't reach here on a successful breakpoint enable...
2125 if (error.Success())
2126 error.SetErrorToGenericError();
2127 return error;
2128}
2129
2130Error
2131ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2132{
2133 Error error;
2134 assert (bp_site != NULL);
2135 addr_t addr = bp_site->GetLoadAddress();
2136 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002137 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002138 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002139 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002140
2141 if (bp_site->IsEnabled())
2142 {
2143 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2144
Greg Claytonb72d0f02011-04-12 05:54:46 +00002145 BreakpointSite::Type bp_type = bp_site->GetType();
2146 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002147 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002148 case BreakpointSite::eSoftware:
2149 error = DisableSoftwareBreakpoint (bp_site);
2150 break;
2151
2152 case BreakpointSite::eHardware:
2153 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2154 error.SetErrorToGenericError();
2155 break;
2156
2157 case BreakpointSite::eExternal:
2158 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2159 error.SetErrorToGenericError();
2160 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002161 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002162 if (error.Success())
2163 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002164 }
2165 else
2166 {
2167 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002168 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 +00002169 return error;
2170 }
2171
2172 if (error.Success())
2173 error.SetErrorToGenericError();
2174 return error;
2175}
2176
Johnny Chen21900fb2011-09-06 22:38:36 +00002177// Pre-requisite: wp != NULL.
2178static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002179GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002180{
2181 assert(wp);
2182 bool watch_read = wp->WatchpointRead();
2183 bool watch_write = wp->WatchpointWrite();
2184
2185 // watch_read and watch_write cannot both be false.
2186 assert(watch_read || watch_write);
2187 if (watch_read && watch_write)
2188 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002189 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002190 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002191 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002192 return eWatchpointWrite;
2193}
2194
Chris Lattner24943d22010-06-08 16:52:24 +00002195Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002196ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002197{
2198 Error error;
2199 if (wp)
2200 {
2201 user_id_t watchID = wp->GetID();
2202 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002203 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002204 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002205 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002206 if (wp->IsEnabled())
2207 {
2208 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002209 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002210 return error;
2211 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002212
2213 GDBStoppointType type = GetGDBStoppointType(wp);
2214 // Pass down an appropriate z/Z packet...
2215 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002216 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002217 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2218 {
2219 wp->SetEnabled(true);
2220 return error;
2221 }
2222 else
2223 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002224 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002225 else
2226 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002227 }
2228 else
2229 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002230 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002231 }
2232 if (error.Success())
2233 error.SetErrorToGenericError();
2234 return error;
2235}
2236
2237Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002238ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002239{
2240 Error error;
2241 if (wp)
2242 {
2243 user_id_t watchID = wp->GetID();
2244
Greg Claytone005f2c2010-11-06 01:53:30 +00002245 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002246
2247 addr_t addr = wp->GetLoadAddress();
2248 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002249 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002250
Johnny Chen21900fb2011-09-06 22:38:36 +00002251 if (!wp->IsEnabled())
2252 {
2253 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002254 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002255 return error;
2256 }
2257
Chris Lattner24943d22010-06-08 16:52:24 +00002258 if (wp->IsHardware())
2259 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002260 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002261 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002262 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2263 {
2264 wp->SetEnabled(false);
2265 return error;
2266 }
2267 else
2268 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002269 }
2270 // TODO: clear software watchpoints if we implement them
2271 }
2272 else
2273 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002274 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002275 }
2276 if (error.Success())
2277 error.SetErrorToGenericError();
2278 return error;
2279}
2280
2281void
2282ProcessGDBRemote::Clear()
2283{
2284 m_flags = 0;
2285 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002286}
2287
2288Error
2289ProcessGDBRemote::DoSignal (int signo)
2290{
2291 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002292 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002293 if (log)
2294 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2295
2296 if (!m_gdb_comm.SendAsyncSignal (signo))
2297 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2298 return error;
2299}
2300
Chris Lattner24943d22010-06-08 16:52:24 +00002301Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002302ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2303{
2304 ProcessLaunchInfo launch_info;
2305 return StartDebugserverProcess(debugserver_url, launch_info);
2306}
2307
2308Error
2309ProcessGDBRemote::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 +00002310{
2311 Error error;
2312 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2313 {
2314 // If we locate debugserver, keep that located version around
2315 static FileSpec g_debugserver_file_spec;
2316
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002317 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002318 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002319 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002320
2321 // Always check to see if we have an environment override for the path
2322 // to the debugserver to use and use it if we do.
2323 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2324 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002325 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002326 else
2327 debugserver_file_spec = g_debugserver_file_spec;
2328 bool debugserver_exists = debugserver_file_spec.Exists();
2329 if (!debugserver_exists)
2330 {
2331 // The debugserver binary is in the LLDB.framework/Resources
2332 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002333 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002334 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002335 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002336 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002337 if (debugserver_exists)
2338 {
2339 g_debugserver_file_spec = debugserver_file_spec;
2340 }
2341 else
2342 {
2343 g_debugserver_file_spec.Clear();
2344 debugserver_file_spec.Clear();
2345 }
Chris Lattner24943d22010-06-08 16:52:24 +00002346 }
2347 }
2348
2349 if (debugserver_exists)
2350 {
2351 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2352
2353 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002354
Greg Claytone005f2c2010-11-06 01:53:30 +00002355 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002356
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002357 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002358 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002359
Chris Lattner24943d22010-06-08 16:52:24 +00002360 // Start args with "debugserver /file/path -r --"
2361 debugserver_args.AppendArgument(debugserver_path);
2362 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002363 // use native registers, not the GDB registers
2364 debugserver_args.AppendArgument("--native-regs");
2365 // make debugserver run in its own session so signals generated by
2366 // special terminal key sequences (^C) don't affect debugserver
2367 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002368
Chris Lattner24943d22010-06-08 16:52:24 +00002369 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2370 if (env_debugserver_log_file)
2371 {
2372 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2373 debugserver_args.AppendArgument(arg_cstr);
2374 }
2375
2376 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2377 if (env_debugserver_log_flags)
2378 {
2379 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2380 debugserver_args.AppendArgument(arg_cstr);
2381 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002382// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002383// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002384
Greg Claytonb72d0f02011-04-12 05:54:46 +00002385 // We currently send down all arguments, attach pids, or attach
2386 // process names in dedicated GDB server packets, so we don't need
2387 // to pass them as arguments. This is currently because of all the
2388 // things we need to setup prior to launching: the environment,
2389 // current working dir, file actions, etc.
2390#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002391 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002392 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002393 {
Greg Claytona2f74232011-02-24 22:24:29 +00002394 // Terminate the debugserver args so we can now append the inferior args
2395 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002396
Greg Claytona2f74232011-02-24 22:24:29 +00002397 for (int i = 0; inferior_argv[i] != NULL; ++i)
2398 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002399 }
2400 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2401 {
2402 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2403 debugserver_args.AppendArgument (arg_cstr);
2404 }
2405 else if (attach_name && attach_name[0])
2406 {
2407 if (wait_for_launch)
2408 debugserver_args.AppendArgument ("--waitfor");
2409 else
2410 debugserver_args.AppendArgument ("--attach");
2411 debugserver_args.AppendArgument (attach_name);
2412 }
Chris Lattner24943d22010-06-08 16:52:24 +00002413#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002414
2415 ProcessLaunchInfo::FileAction file_action;
2416
2417 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2418 // to "/dev/null" if we run into any problems.
2419 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002420 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002421 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002422 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002423 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002424 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002425
2426 if (log)
2427 {
2428 StreamString strm;
2429 debugserver_args.Dump (&strm);
2430 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2431 }
2432
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002433 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2434 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002435
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002436 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002437
Greg Claytonb72d0f02011-04-12 05:54:46 +00002438 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002439 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002440 else
Chris Lattner24943d22010-06-08 16:52:24 +00002441 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2442
2443 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002444 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002445 }
2446 else
2447 {
Greg Clayton9c236732011-10-26 00:56:27 +00002448 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002449 }
2450
2451 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2452 StartAsyncThread ();
2453 }
2454 return error;
2455}
2456
2457bool
2458ProcessGDBRemote::MonitorDebugserverProcess
2459(
2460 void *callback_baton,
2461 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002462 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002463 int signo, // Zero for no signal
2464 int exit_status // Exit value of process if signal is zero
2465)
2466{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002467 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2468 // and might not exist anymore, so we need to carefully try to get the
2469 // target for this process first since we have a race condition when
2470 // we are done running between getting the notice that the inferior
2471 // process has died and the debugserver that was debugging this process.
2472 // In our test suite, we are also continually running process after
2473 // process, so we must be very careful to make sure:
2474 // 1 - process object hasn't been deleted already
2475 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002476
2477 // "debugserver_pid" argument passed in is the process ID for
2478 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002479 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002480
Greg Clayton75ccf502010-08-21 02:22:51 +00002481 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002482
Greg Clayton1c4642c2011-11-16 05:37:56 +00002483 // Get a shared pointer to the target that has a matching process pointer.
2484 // This target could be gone, or the target could already have a new process
2485 // object inside of it
2486 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2487
Greg Clayton72e1c782011-01-22 23:43:18 +00002488 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002489 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 +00002490
Greg Clayton1c4642c2011-11-16 05:37:56 +00002491 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002492 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002493 // We found a process in a target that matches, but another thread
2494 // might be in the process of launching a new process that will
2495 // soon replace it, so get a shared pointer to the process so we
2496 // can keep it alive.
2497 ProcessSP process_sp (target_sp->GetProcessSP());
2498 // Now we have a shared pointer to the process that can't go away on us
2499 // so we now make sure it was the same as the one passed in, and also make
2500 // sure that our previous "process *" didn't get deleted and have a new
2501 // "process *" created in its place with the same pointer. To verify this
2502 // we make sure the process has our debugserver process ID. If we pass all
2503 // of these tests, then we are sure that this process is the one we were
2504 // looking for.
2505 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002506 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002507 // Sleep for a half a second to make sure our inferior process has
2508 // time to set its exit status before we set it incorrectly when
2509 // both the debugserver and the inferior process shut down.
2510 usleep (500000);
2511 // If our process hasn't yet exited, debugserver might have died.
2512 // If the process did exit, the we are reaping it.
2513 const StateType state = process->GetState();
2514
2515 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2516 state != eStateInvalid &&
2517 state != eStateUnloaded &&
2518 state != eStateExited &&
2519 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002520 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002521 char error_str[1024];
2522 if (signo)
2523 {
2524 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2525 if (signal_cstr)
2526 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2527 else
2528 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2529 }
Chris Lattner24943d22010-06-08 16:52:24 +00002530 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002531 {
2532 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2533 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002534
Greg Clayton1c4642c2011-11-16 05:37:56 +00002535 process->SetExitStatus (-1, error_str);
2536 }
2537 // Debugserver has exited we need to let our ProcessGDBRemote
2538 // know that it no longer has a debugserver instance
2539 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002540 }
Chris Lattner24943d22010-06-08 16:52:24 +00002541 }
2542 return true;
2543}
2544
2545void
2546ProcessGDBRemote::KillDebugserverProcess ()
2547{
2548 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2549 {
2550 ::kill (m_debugserver_pid, SIGINT);
2551 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2552 }
2553}
2554
2555void
2556ProcessGDBRemote::Initialize()
2557{
2558 static bool g_initialized = false;
2559
2560 if (g_initialized == false)
2561 {
2562 g_initialized = true;
2563 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2564 GetPluginDescriptionStatic(),
2565 CreateInstance);
2566
2567 Log::Callbacks log_callbacks = {
2568 ProcessGDBRemoteLog::DisableLog,
2569 ProcessGDBRemoteLog::EnableLog,
2570 ProcessGDBRemoteLog::ListLogCategories
2571 };
2572
2573 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2574 }
2575}
2576
2577bool
Chris Lattner24943d22010-06-08 16:52:24 +00002578ProcessGDBRemote::StartAsyncThread ()
2579{
Greg Claytone005f2c2010-11-06 01:53:30 +00002580 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002581
2582 if (log)
2583 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2584
2585 // Create a thread that watches our internal state and controls which
2586 // events make it to clients (into the DCProcess event queue).
2587 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002588 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002589}
2590
2591void
2592ProcessGDBRemote::StopAsyncThread ()
2593{
Greg Claytone005f2c2010-11-06 01:53:30 +00002594 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002595
2596 if (log)
2597 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2598
2599 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002600
2601 // This will shut down the async thread.
2602 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002603
2604 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002605 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002606 {
2607 Host::ThreadJoin (m_async_thread, NULL, NULL);
2608 }
2609}
2610
2611
2612void *
2613ProcessGDBRemote::AsyncThread (void *arg)
2614{
2615 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2616
Greg Claytone005f2c2010-11-06 01:53:30 +00002617 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002618 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002619 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002620
2621 Listener listener ("ProcessGDBRemote::AsyncThread");
2622 EventSP event_sp;
2623 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2624 eBroadcastBitAsyncThreadShouldExit;
2625
2626 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2627 {
Greg Claytona2f74232011-02-24 22:24:29 +00002628 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2629
Chris Lattner24943d22010-06-08 16:52:24 +00002630 bool done = false;
2631 while (!done)
2632 {
2633 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002634 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002635 if (listener.WaitForEvent (NULL, event_sp))
2636 {
2637 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002638 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002639 {
Greg Claytona2f74232011-02-24 22:24:29 +00002640 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002641 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 +00002642
Greg Claytona2f74232011-02-24 22:24:29 +00002643 switch (event_type)
2644 {
2645 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002646 {
Greg Claytona2f74232011-02-24 22:24:29 +00002647 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002648
Greg Claytona2f74232011-02-24 22:24:29 +00002649 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002650 {
Greg Claytona2f74232011-02-24 22:24:29 +00002651 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2652 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2653 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002654 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002655
Greg Claytona2f74232011-02-24 22:24:29 +00002656 if (::strstr (continue_cstr, "vAttach") == NULL)
2657 process->SetPrivateState(eStateRunning);
2658 StringExtractorGDBRemote response;
2659 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002660
Greg Clayton67b402c2012-05-16 02:48:06 +00002661 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2662 // The thread ID list might be contained within the "response", or the stop reply packet that
2663 // caused the stop. So clear it now before we give the stop reply packet to the process
2664 // using the process->SetLastStopPacket()...
2665 process->ClearThreadIDList ();
2666
Greg Claytona2f74232011-02-24 22:24:29 +00002667 switch (stop_state)
2668 {
2669 case eStateStopped:
2670 case eStateCrashed:
2671 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002672 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002673 process->SetPrivateState (stop_state);
2674 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002675
Greg Claytona2f74232011-02-24 22:24:29 +00002676 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002677 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002678 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002679 response.SetFilePos(1);
2680 process->SetExitStatus(response.GetHexU8(), NULL);
2681 done = true;
2682 break;
2683
2684 case eStateInvalid:
2685 process->SetExitStatus(-1, "lost connection");
2686 break;
2687
2688 default:
2689 process->SetPrivateState (stop_state);
2690 break;
2691 }
Chris Lattner24943d22010-06-08 16:52:24 +00002692 }
2693 }
Greg Claytona2f74232011-02-24 22:24:29 +00002694 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002695
Greg Claytona2f74232011-02-24 22:24:29 +00002696 case eBroadcastBitAsyncThreadShouldExit:
2697 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002698 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002699 done = true;
2700 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002701
Greg Claytona2f74232011-02-24 22:24:29 +00002702 default:
2703 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002704 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 +00002705 done = true;
2706 break;
2707 }
2708 }
2709 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2710 {
2711 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2712 {
2713 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002714 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002715 }
Chris Lattner24943d22010-06-08 16:52:24 +00002716 }
2717 }
2718 else
2719 {
2720 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002721 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 +00002722 done = true;
2723 }
2724 }
2725 }
2726
2727 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002728 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002729
2730 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2731 return NULL;
2732}
2733
Chris Lattner24943d22010-06-08 16:52:24 +00002734const char *
2735ProcessGDBRemote::GetDispatchQueueNameForThread
2736(
2737 addr_t thread_dispatch_qaddr,
2738 std::string &dispatch_queue_name
2739)
2740{
2741 dispatch_queue_name.clear();
2742 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2743 {
2744 // Cache the dispatch_queue_offsets_addr value so we don't always have
2745 // to look it up
2746 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2747 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002748 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2749 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002750 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2751 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002752 if (module_sp)
2753 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2754
2755 if (dispatch_queue_offsets_symbol == NULL)
2756 {
Greg Clayton444fe992012-02-26 05:51:37 +00002757 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2758 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002759 if (module_sp)
2760 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2761 }
Chris Lattner24943d22010-06-08 16:52:24 +00002762 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002763 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002764
2765 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2766 return NULL;
2767 }
2768
2769 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002770 DataExtractor data (memory_buffer,
2771 sizeof(memory_buffer),
2772 m_target.GetArchitecture().GetByteOrder(),
2773 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002774
2775 // Excerpt from src/queue_private.h
2776 struct dispatch_queue_offsets_s
2777 {
2778 uint16_t dqo_version;
2779 uint16_t dqo_label;
2780 uint16_t dqo_label_size;
2781 } dispatch_queue_offsets;
2782
2783
2784 Error error;
2785 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2786 {
2787 uint32_t data_offset = 0;
2788 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2789 {
2790 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2791 {
2792 data_offset = 0;
2793 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2794 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2795 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2796 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2797 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2798 dispatch_queue_name.erase (bytes_read);
2799 }
2800 }
2801 }
2802 }
2803 if (dispatch_queue_name.empty())
2804 return NULL;
2805 return dispatch_queue_name.c_str();
2806}
2807
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002808//uint32_t
2809//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2810//{
2811// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2812// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2813// if (m_local_debugserver)
2814// {
2815// return Host::ListProcessesMatchingName (name, matches, pids);
2816// }
2817// else
2818// {
2819// // FIXME: Implement talking to the remote debugserver.
2820// return 0;
2821// }
2822//
2823//}
2824//
Jim Ingham55e01d82011-01-22 01:33:44 +00002825bool
2826ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2827 lldb_private::StoppointCallbackContext *context,
2828 lldb::user_id_t break_id,
2829 lldb::user_id_t break_loc_id)
2830{
2831 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2832 // run so I can stop it if that's what I want to do.
2833 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2834 if (log)
2835 log->Printf("Hit New Thread Notification breakpoint.");
2836 return false;
2837}
2838
2839
2840bool
2841ProcessGDBRemote::StartNoticingNewThreads()
2842{
Jim Ingham55e01d82011-01-22 01:33:44 +00002843 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002844 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002845 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002846 if (log && log->GetVerbose())
2847 log->Printf("Enabled noticing new thread breakpoint.");
2848 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002849 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002850 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002851 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002852 PlatformSP platform_sp (m_target.GetPlatform());
2853 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002854 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002855 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2856 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002857 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002858 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002859 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2860 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002861 }
2862 else
2863 {
2864 if (log)
2865 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002866 }
2867 }
2868 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002869 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002870}
2871
2872bool
2873ProcessGDBRemote::StopNoticingNewThreads()
2874{
Jim Inghamff276fe2011-02-08 05:19:01 +00002875 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002876 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002877 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002878
2879 if (m_thread_create_bp_sp)
2880 m_thread_create_bp_sp->SetEnabled(false);
2881
Jim Ingham55e01d82011-01-22 01:33:44 +00002882 return true;
2883}
2884
2885