blob: 7479d1e7d4ce472280bdfcebaad8a72da35d8362 [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.
1426 if (bp_site_sp->ValidForThisThread (gdb_thread))
1427 {
1428 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1429 handled = true;
1430 }
1431 }
1432
1433 if (!handled)
1434 {
1435 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1436 }
1437 }
1438 else if (reason.compare("trap") == 0)
1439 {
1440 // Let the trap just use the standard signal stop reason below...
1441 }
1442 else if (reason.compare("watchpoint") == 0)
1443 {
1444 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1445 // TODO: locate the watchpoint somehow...
1446 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1447 handled = true;
1448 }
1449 else if (reason.compare("exception") == 0)
1450 {
1451 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1452 handled = true;
1453 }
1454 }
1455
1456 if (signo)
1457 {
1458 if (signo == SIGTRAP)
1459 {
1460 // Currently we are going to assume SIGTRAP means we are either
1461 // hitting a breakpoint or hardware single stepping.
1462 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001463 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001464 if (bp_site_sp)
1465 {
1466 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1467 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1468 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1469 if (bp_site_sp->ValidForThisThread (gdb_thread))
1470 {
1471 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1472 handled = true;
1473 }
1474 }
1475 if (!handled)
1476 {
1477 // TODO: check for breakpoint or trap opcode in case there is a hard
1478 // coded software trap
1479 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1480 handled = true;
1481 }
1482 }
1483 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001484 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001485 }
1486 else
1487 {
Greg Clayton643ee732010-08-04 01:40:35 +00001488 StopInfoSP invalid_stop_info_sp;
1489 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001490 }
Greg Clayton65611552011-06-04 01:26:29 +00001491
1492 if (!description.empty())
1493 {
1494 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1495 if (stop_info_sp)
1496 {
1497 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001498 }
Greg Clayton65611552011-06-04 01:26:29 +00001499 else
1500 {
1501 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1502 }
1503 }
1504 }
Chris Lattner24943d22010-06-08 16:52:24 +00001505 }
1506 return eStateStopped;
1507 }
1508 break;
1509
1510 case 'W':
1511 // process exited
1512 return eStateExited;
1513
1514 default:
1515 break;
1516 }
1517 return eStateInvalid;
1518}
1519
1520void
1521ProcessGDBRemote::RefreshStateAfterStop ()
1522{
Greg Claytonff3448e2012-04-13 02:11:32 +00001523 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001524 m_thread_ids.clear();
1525 // Set the thread stop info. It might have a "threads" key whose value is
1526 // a list of all thread IDs in the current process, so m_thread_ids might
1527 // get set.
1528 SetThreadStopInfo (m_last_stop_packet);
1529 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1530 if (m_thread_ids.empty())
1531 {
1532 // No, we need to fetch the thread list manually
1533 UpdateThreadIDList();
1534 }
1535
Chris Lattner24943d22010-06-08 16:52:24 +00001536 // Let all threads recover from stopping and do any clean up based
1537 // on the previous thread state (if any).
1538 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001539
Chris Lattner24943d22010-06-08 16:52:24 +00001540}
1541
1542Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001543ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001544{
1545 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001546
Greg Claytona4881d02011-01-22 07:12:45 +00001547 bool timed_out = false;
1548 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001549
1550 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001551 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001552 // We are being asked to halt during an attach. We need to just close
1553 // our file handle and debugserver will go away, and we can be done...
1554 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001555 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001556 else
1557 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001558 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001559 {
1560 if (timed_out)
1561 error.SetErrorString("timed out sending interrupt packet");
1562 else
1563 error.SetErrorString("unknown error sending interrupt packet");
1564 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001565
1566 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001567 }
Chris Lattner24943d22010-06-08 16:52:24 +00001568 return error;
1569}
1570
1571Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001572ProcessGDBRemote::InterruptIfRunning
1573(
1574 bool discard_thread_plans,
1575 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001576 EventSP &stop_event_sp
1577)
Chris Lattner24943d22010-06-08 16:52:24 +00001578{
1579 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001580
Greg Clayton2860ba92011-01-23 19:58:49 +00001581 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1582
Greg Clayton68ca8232011-01-25 02:58:48 +00001583 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001584 const bool is_running = m_gdb_comm.IsRunning();
1585 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001586 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001587 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001588 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001589 is_running);
1590
Greg Clayton2860ba92011-01-23 19:58:49 +00001591 if (discard_thread_plans)
1592 {
1593 if (log)
1594 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1595 m_thread_list.DiscardThreadPlans();
1596 }
1597 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001598 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001599 if (catch_stop_event)
1600 {
1601 if (log)
1602 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1603 PausePrivateStateThread();
1604 paused_private_state_thread = true;
1605 }
1606
Greg Clayton4fb400f2010-09-27 21:07:38 +00001607 bool timed_out = false;
1608 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001609
Greg Clayton05e4d972012-03-29 01:55:41 +00001610 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001611 {
1612 if (timed_out)
1613 error.SetErrorString("timed out sending interrupt packet");
1614 else
1615 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001616 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001617 ResumePrivateStateThread();
1618 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001619 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001620
Greg Clayton72e1c782011-01-22 23:43:18 +00001621 if (catch_stop_event)
1622 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001623 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001624 TimeValue timeout_time;
1625 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001626 timeout_time.OffsetWithSeconds(5);
1627 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001628
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001629 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001630 if (log)
1631 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001632
Greg Clayton2860ba92011-01-23 19:58:49 +00001633 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001634 error.SetErrorString("unable to verify target stopped");
1635 }
1636
Greg Clayton68ca8232011-01-25 02:58:48 +00001637 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001638 {
1639 if (log)
1640 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001641 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001642 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001643 }
Chris Lattner24943d22010-06-08 16:52:24 +00001644 return error;
1645}
1646
Greg Clayton4fb400f2010-09-27 21:07:38 +00001647Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001648ProcessGDBRemote::WillDetach ()
1649{
Greg Clayton2860ba92011-01-23 19:58:49 +00001650 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1651 if (log)
1652 log->Printf ("ProcessGDBRemote::WillDetach()");
1653
Greg Clayton72e1c782011-01-22 23:43:18 +00001654 bool discard_thread_plans = true;
1655 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001656 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001657
1658 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1659 // needed. This shouldn't be a feature of a particular plugin.
1660
Greg Clayton68ca8232011-01-25 02:58:48 +00001661 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001662}
1663
1664Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001665ProcessGDBRemote::DoDetach()
1666{
1667 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001668 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001669 if (log)
1670 log->Printf ("ProcessGDBRemote::DoDetach()");
1671
1672 DisableAllBreakpointSites ();
1673
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001674 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001675
Greg Clayton516f0842012-04-11 00:24:49 +00001676 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001677 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001678 {
Greg Clayton516f0842012-04-11 00:24:49 +00001679 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001680 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1681 else
1682 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001683 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001684 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001685 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001686
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001687 SetPrivateState (eStateDetached);
1688 ResumePrivateStateThread();
1689
1690 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001691 return error;
1692}
Chris Lattner24943d22010-06-08 16:52:24 +00001693
Jim Ingham06b84492012-07-04 00:35:43 +00001694
Chris Lattner24943d22010-06-08 16:52:24 +00001695Error
1696ProcessGDBRemote::DoDestroy ()
1697{
1698 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001699 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001700 if (log)
1701 log->Printf ("ProcessGDBRemote::DoDestroy()");
1702
Jim Ingham06b84492012-07-04 00:35:43 +00001703 // There is a bug in older iOS debugservers where they don't shut down the process
1704 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1705 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1706 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1707 // destroy it again.
1708 //
1709 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1710 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1711 // the debugservers with this bug are equal. There really should be a better way to test this!
1712 //
1713 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1714 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1715 // just do the straight-forward kill.
1716 //
1717 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1718 // necessary (or helpful) to do any of this.
1719
1720 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1721 {
1722 PlatformSP platform_sp = GetTarget().GetPlatform();
1723
1724 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1725 if (platform_sp
1726 && platform_sp->GetName()
1727 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1728 {
1729 if (m_destroy_tried_resuming)
1730 {
1731 if (log)
1732 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1733 }
1734 else
1735 {
1736 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1737 // but we really need it to happen here and it doesn't matter if we do it twice.
1738 m_thread_list.DiscardThreadPlans();
1739 DisableAllBreakpointSites();
1740
1741 bool stop_looks_like_crash = false;
1742 ThreadList &threads = GetThreadList();
1743
1744 {
1745 Mutex::Locker(threads.GetMutex());
1746
1747 size_t num_threads = threads.GetSize();
1748 for (size_t i = 0; i < num_threads; i++)
1749 {
1750 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1751 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1752 StopReason reason = eStopReasonInvalid;
1753 if (stop_info_sp)
1754 reason = stop_info_sp->GetStopReason();
1755 if (reason == eStopReasonBreakpoint
1756 || reason == eStopReasonException)
1757 {
1758 if (log)
1759 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1760 thread_sp->GetID(),
1761 stop_info_sp->GetDescription());
1762 stop_looks_like_crash = true;
1763 break;
1764 }
1765 }
1766 }
1767
1768 if (stop_looks_like_crash)
1769 {
1770 if (log)
1771 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1772 m_destroy_tried_resuming = true;
1773
1774 // If we are going to run again before killing, it would be good to suspend all the threads
1775 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1776 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1777 // have to run the risk of letting those threads proceed a bit.
1778
1779 {
1780 Mutex::Locker(threads.GetMutex());
1781
1782 size_t num_threads = threads.GetSize();
1783 for (size_t i = 0; i < num_threads; i++)
1784 {
1785 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1786 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1787 StopReason reason = eStopReasonInvalid;
1788 if (stop_info_sp)
1789 reason = stop_info_sp->GetStopReason();
1790 if (reason != eStopReasonBreakpoint
1791 && reason != eStopReasonException)
1792 {
1793 if (log)
1794 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1795 thread_sp->GetID());
1796 thread_sp->SetResumeState(eStateSuspended);
1797 }
1798 }
1799 }
1800 Resume ();
1801 return Destroy();
1802 }
1803 }
1804 }
1805 }
1806
Chris Lattner24943d22010-06-08 16:52:24 +00001807 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001808 int exit_status = SIGABRT;
1809 std::string exit_string;
1810
Greg Claytona4881d02011-01-22 07:12:45 +00001811 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001812 {
Jim Ingham8226e942011-10-28 01:11:35 +00001813 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001814 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001815
1816 StringExtractorGDBRemote response;
1817 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001818 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001819 {
1820 char packet_cmd = response.GetChar(0);
1821
1822 if (packet_cmd == 'W' || packet_cmd == 'X')
1823 {
Greg Clayton06709002011-12-06 04:51:14 +00001824 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001825 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001826 exit_status = response.GetHexU8();
1827 }
1828 else
1829 {
1830 if (log)
1831 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1832 exit_string.assign("got unexpected response to k packet: ");
1833 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001834 }
1835 }
1836 else
1837 {
Jim Ingham8247e622012-06-06 00:32:39 +00001838 if (log)
1839 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1840 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001841 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001842 }
Jim Ingham8247e622012-06-06 00:32:39 +00001843 else
1844 {
1845 if (log)
1846 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1847 exit_string.assign ("killing while attaching.");
1848 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001849 }
Jim Ingham8247e622012-06-06 00:32:39 +00001850 else
1851 {
1852 // If we missed setting the exit status on the way out, do it here.
1853 // NB set exit status can be called multiple times, the first one sets the status.
1854 exit_string.assign("destroying when not connected to debugserver");
1855 }
1856
1857 SetExitStatus(exit_status, exit_string.c_str());
1858
Chris Lattner24943d22010-06-08 16:52:24 +00001859 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001860 KillDebugserverProcess ();
1861 return error;
1862}
1863
Chris Lattner24943d22010-06-08 16:52:24 +00001864//------------------------------------------------------------------
1865// Process Queries
1866//------------------------------------------------------------------
1867
1868bool
1869ProcessGDBRemote::IsAlive ()
1870{
Greg Clayton58e844b2010-12-08 05:08:21 +00001871 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001872}
1873
1874addr_t
1875ProcessGDBRemote::GetImageInfoAddress()
1876{
Greg Clayton516f0842012-04-11 00:24:49 +00001877 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001878}
1879
Chris Lattner24943d22010-06-08 16:52:24 +00001880//------------------------------------------------------------------
1881// Process Memory
1882//------------------------------------------------------------------
1883size_t
1884ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1885{
1886 if (size > m_max_memory_size)
1887 {
1888 // Keep memory read sizes down to a sane limit. This function will be
1889 // called multiple times in order to complete the task by
1890 // lldb_private::Process so it is ok to do this.
1891 size = m_max_memory_size;
1892 }
1893
1894 char packet[64];
1895 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1896 assert (packet_len + 1 < sizeof(packet));
1897 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001898 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001899 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001900 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001901 {
1902 error.Clear();
1903 return response.GetHexBytes(buf, size, '\xdd');
1904 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001905 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001906 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001907 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001908 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1909 else
1910 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1911 }
1912 else
1913 {
1914 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1915 }
1916 return 0;
1917}
1918
1919size_t
1920ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1921{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001922 if (size > m_max_memory_size)
1923 {
1924 // Keep memory read sizes down to a sane limit. This function will be
1925 // called multiple times in order to complete the task by
1926 // lldb_private::Process so it is ok to do this.
1927 size = m_max_memory_size;
1928 }
1929
Chris Lattner24943d22010-06-08 16:52:24 +00001930 StreamString packet;
1931 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001932 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001933 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001934 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001935 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001936 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001937 {
1938 error.Clear();
1939 return size;
1940 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001941 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001942 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001943 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001944 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1945 else
1946 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1947 }
1948 else
1949 {
1950 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1951 }
1952 return 0;
1953}
1954
1955lldb::addr_t
1956ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1957{
Greg Clayton989816b2011-05-14 01:50:35 +00001958 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1959
Greg Clayton2f085c62011-05-15 01:25:55 +00001960 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001961 switch (supported)
1962 {
1963 case eLazyBoolCalculate:
1964 case eLazyBoolYes:
1965 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1966 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1967 return allocated_addr;
1968
1969 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001970 // Call mmap() to create memory in the inferior..
1971 unsigned prot = 0;
1972 if (permissions & lldb::ePermissionsReadable)
1973 prot |= eMmapProtRead;
1974 if (permissions & lldb::ePermissionsWritable)
1975 prot |= eMmapProtWrite;
1976 if (permissions & lldb::ePermissionsExecutable)
1977 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001978
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001979 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1980 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1981 m_addr_to_mmap_size[allocated_addr] = size;
1982 else
1983 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001984 break;
1985 }
1986
Chris Lattner24943d22010-06-08 16:52:24 +00001987 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001988 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001989 else
1990 error.Clear();
1991 return allocated_addr;
1992}
1993
1994Error
Greg Claytona9385532011-11-18 07:03:08 +00001995ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1996 MemoryRegionInfo &region_info)
1997{
1998
1999 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2000 return error;
2001}
2002
2003Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002004ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2005{
2006
2007 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2008 return error;
2009}
2010
2011Error
Chris Lattner24943d22010-06-08 16:52:24 +00002012ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2013{
2014 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002015 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2016
2017 switch (supported)
2018 {
2019 case eLazyBoolCalculate:
2020 // We should never be deallocating memory without allocating memory
2021 // first so we should never get eLazyBoolCalculate
2022 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2023 break;
2024
2025 case eLazyBoolYes:
2026 if (!m_gdb_comm.DeallocateMemory (addr))
2027 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2028 break;
2029
2030 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002031 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002032 {
2033 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002034 if (pos != m_addr_to_mmap_size.end() &&
2035 InferiorCallMunmap(this, addr, pos->second))
2036 m_addr_to_mmap_size.erase (pos);
2037 else
2038 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002039 }
2040 break;
2041 }
2042
Chris Lattner24943d22010-06-08 16:52:24 +00002043 return error;
2044}
2045
2046
2047//------------------------------------------------------------------
2048// Process STDIO
2049//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002050size_t
2051ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2052{
2053 if (m_stdio_communication.IsConnected())
2054 {
2055 ConnectionStatus status;
2056 m_stdio_communication.Write(src, src_len, status, NULL);
2057 }
2058 return 0;
2059}
2060
2061Error
2062ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2063{
2064 Error error;
2065 assert (bp_site != NULL);
2066
Greg Claytone005f2c2010-11-06 01:53:30 +00002067 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002068 user_id_t site_id = bp_site->GetID();
2069 const addr_t addr = bp_site->GetLoadAddress();
2070 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002071 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002072
2073 if (bp_site->IsEnabled())
2074 {
2075 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002076 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 +00002077 return error;
2078 }
2079 else
2080 {
2081 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2082
2083 if (bp_site->HardwarePreferred())
2084 {
2085 // Try and set hardware breakpoint, and if that fails, fall through
2086 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002087 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002088 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002089 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002090 {
2091 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002092 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002093 return error;
2094 }
Chris Lattner24943d22010-06-08 16:52:24 +00002095 }
2096 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002097
2098 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002099 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002100 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2101 {
2102 bp_site->SetEnabled(true);
2103 bp_site->SetType (BreakpointSite::eExternal);
2104 return error;
2105 }
Chris Lattner24943d22010-06-08 16:52:24 +00002106 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002107
2108 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002109 }
2110
2111 if (log)
2112 {
2113 const char *err_string = error.AsCString();
2114 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2115 bp_site->GetLoadAddress(),
2116 err_string ? err_string : "NULL");
2117 }
2118 // We shouldn't reach here on a successful breakpoint enable...
2119 if (error.Success())
2120 error.SetErrorToGenericError();
2121 return error;
2122}
2123
2124Error
2125ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2126{
2127 Error error;
2128 assert (bp_site != NULL);
2129 addr_t addr = bp_site->GetLoadAddress();
2130 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002131 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002132 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002133 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002134
2135 if (bp_site->IsEnabled())
2136 {
2137 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2138
Greg Claytonb72d0f02011-04-12 05:54:46 +00002139 BreakpointSite::Type bp_type = bp_site->GetType();
2140 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002141 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002142 case BreakpointSite::eSoftware:
2143 error = DisableSoftwareBreakpoint (bp_site);
2144 break;
2145
2146 case BreakpointSite::eHardware:
2147 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2148 error.SetErrorToGenericError();
2149 break;
2150
2151 case BreakpointSite::eExternal:
2152 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2153 error.SetErrorToGenericError();
2154 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002155 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002156 if (error.Success())
2157 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002158 }
2159 else
2160 {
2161 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002162 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 +00002163 return error;
2164 }
2165
2166 if (error.Success())
2167 error.SetErrorToGenericError();
2168 return error;
2169}
2170
Johnny Chen21900fb2011-09-06 22:38:36 +00002171// Pre-requisite: wp != NULL.
2172static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002173GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002174{
2175 assert(wp);
2176 bool watch_read = wp->WatchpointRead();
2177 bool watch_write = wp->WatchpointWrite();
2178
2179 // watch_read and watch_write cannot both be false.
2180 assert(watch_read || watch_write);
2181 if (watch_read && watch_write)
2182 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002183 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002184 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002185 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002186 return eWatchpointWrite;
2187}
2188
Chris Lattner24943d22010-06-08 16:52:24 +00002189Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002190ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002191{
2192 Error error;
2193 if (wp)
2194 {
2195 user_id_t watchID = wp->GetID();
2196 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002197 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002198 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002199 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002200 if (wp->IsEnabled())
2201 {
2202 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002203 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002204 return error;
2205 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002206
2207 GDBStoppointType type = GetGDBStoppointType(wp);
2208 // Pass down an appropriate z/Z packet...
2209 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002210 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002211 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2212 {
2213 wp->SetEnabled(true);
2214 return error;
2215 }
2216 else
2217 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002218 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002219 else
2220 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002221 }
2222 else
2223 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002224 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002225 }
2226 if (error.Success())
2227 error.SetErrorToGenericError();
2228 return error;
2229}
2230
2231Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002232ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002233{
2234 Error error;
2235 if (wp)
2236 {
2237 user_id_t watchID = wp->GetID();
2238
Greg Claytone005f2c2010-11-06 01:53:30 +00002239 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002240
2241 addr_t addr = wp->GetLoadAddress();
2242 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002243 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002244
Johnny Chen21900fb2011-09-06 22:38:36 +00002245 if (!wp->IsEnabled())
2246 {
2247 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002248 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002249 return error;
2250 }
2251
Chris Lattner24943d22010-06-08 16:52:24 +00002252 if (wp->IsHardware())
2253 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002254 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002255 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002256 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2257 {
2258 wp->SetEnabled(false);
2259 return error;
2260 }
2261 else
2262 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002263 }
2264 // TODO: clear software watchpoints if we implement them
2265 }
2266 else
2267 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002268 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002269 }
2270 if (error.Success())
2271 error.SetErrorToGenericError();
2272 return error;
2273}
2274
2275void
2276ProcessGDBRemote::Clear()
2277{
2278 m_flags = 0;
2279 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002280}
2281
2282Error
2283ProcessGDBRemote::DoSignal (int signo)
2284{
2285 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002286 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002287 if (log)
2288 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2289
2290 if (!m_gdb_comm.SendAsyncSignal (signo))
2291 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2292 return error;
2293}
2294
Chris Lattner24943d22010-06-08 16:52:24 +00002295Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002296ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2297{
2298 ProcessLaunchInfo launch_info;
2299 return StartDebugserverProcess(debugserver_url, launch_info);
2300}
2301
2302Error
2303ProcessGDBRemote::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 +00002304{
2305 Error error;
2306 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2307 {
2308 // If we locate debugserver, keep that located version around
2309 static FileSpec g_debugserver_file_spec;
2310
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002311 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002312 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002313 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002314
2315 // Always check to see if we have an environment override for the path
2316 // to the debugserver to use and use it if we do.
2317 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2318 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002319 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002320 else
2321 debugserver_file_spec = g_debugserver_file_spec;
2322 bool debugserver_exists = debugserver_file_spec.Exists();
2323 if (!debugserver_exists)
2324 {
2325 // The debugserver binary is in the LLDB.framework/Resources
2326 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002327 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002328 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002329 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002330 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002331 if (debugserver_exists)
2332 {
2333 g_debugserver_file_spec = debugserver_file_spec;
2334 }
2335 else
2336 {
2337 g_debugserver_file_spec.Clear();
2338 debugserver_file_spec.Clear();
2339 }
Chris Lattner24943d22010-06-08 16:52:24 +00002340 }
2341 }
2342
2343 if (debugserver_exists)
2344 {
2345 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2346
2347 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002348
Greg Claytone005f2c2010-11-06 01:53:30 +00002349 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002350
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002351 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002352 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002353
Chris Lattner24943d22010-06-08 16:52:24 +00002354 // Start args with "debugserver /file/path -r --"
2355 debugserver_args.AppendArgument(debugserver_path);
2356 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002357 // use native registers, not the GDB registers
2358 debugserver_args.AppendArgument("--native-regs");
2359 // make debugserver run in its own session so signals generated by
2360 // special terminal key sequences (^C) don't affect debugserver
2361 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002362
Chris Lattner24943d22010-06-08 16:52:24 +00002363 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2364 if (env_debugserver_log_file)
2365 {
2366 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2367 debugserver_args.AppendArgument(arg_cstr);
2368 }
2369
2370 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2371 if (env_debugserver_log_flags)
2372 {
2373 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2374 debugserver_args.AppendArgument(arg_cstr);
2375 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002376// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002377// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002378
Greg Claytonb72d0f02011-04-12 05:54:46 +00002379 // We currently send down all arguments, attach pids, or attach
2380 // process names in dedicated GDB server packets, so we don't need
2381 // to pass them as arguments. This is currently because of all the
2382 // things we need to setup prior to launching: the environment,
2383 // current working dir, file actions, etc.
2384#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002385 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002386 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002387 {
Greg Claytona2f74232011-02-24 22:24:29 +00002388 // Terminate the debugserver args so we can now append the inferior args
2389 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002390
Greg Claytona2f74232011-02-24 22:24:29 +00002391 for (int i = 0; inferior_argv[i] != NULL; ++i)
2392 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002393 }
2394 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2395 {
2396 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2397 debugserver_args.AppendArgument (arg_cstr);
2398 }
2399 else if (attach_name && attach_name[0])
2400 {
2401 if (wait_for_launch)
2402 debugserver_args.AppendArgument ("--waitfor");
2403 else
2404 debugserver_args.AppendArgument ("--attach");
2405 debugserver_args.AppendArgument (attach_name);
2406 }
Chris Lattner24943d22010-06-08 16:52:24 +00002407#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002408
2409 ProcessLaunchInfo::FileAction file_action;
2410
2411 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2412 // to "/dev/null" if we run into any problems.
2413 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002414 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002415 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002416 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002417 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002418 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002419
2420 if (log)
2421 {
2422 StreamString strm;
2423 debugserver_args.Dump (&strm);
2424 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2425 }
2426
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002427 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2428 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002429
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002430 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002431
Greg Claytonb72d0f02011-04-12 05:54:46 +00002432 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002433 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002434 else
Chris Lattner24943d22010-06-08 16:52:24 +00002435 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2436
2437 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002438 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002439 }
2440 else
2441 {
Greg Clayton9c236732011-10-26 00:56:27 +00002442 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002443 }
2444
2445 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2446 StartAsyncThread ();
2447 }
2448 return error;
2449}
2450
2451bool
2452ProcessGDBRemote::MonitorDebugserverProcess
2453(
2454 void *callback_baton,
2455 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002456 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002457 int signo, // Zero for no signal
2458 int exit_status // Exit value of process if signal is zero
2459)
2460{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002461 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2462 // and might not exist anymore, so we need to carefully try to get the
2463 // target for this process first since we have a race condition when
2464 // we are done running between getting the notice that the inferior
2465 // process has died and the debugserver that was debugging this process.
2466 // In our test suite, we are also continually running process after
2467 // process, so we must be very careful to make sure:
2468 // 1 - process object hasn't been deleted already
2469 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002470
2471 // "debugserver_pid" argument passed in is the process ID for
2472 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002473 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002474
Greg Clayton75ccf502010-08-21 02:22:51 +00002475 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002476
Greg Clayton1c4642c2011-11-16 05:37:56 +00002477 // Get a shared pointer to the target that has a matching process pointer.
2478 // This target could be gone, or the target could already have a new process
2479 // object inside of it
2480 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2481
Greg Clayton72e1c782011-01-22 23:43:18 +00002482 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002483 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 +00002484
Greg Clayton1c4642c2011-11-16 05:37:56 +00002485 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002486 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002487 // We found a process in a target that matches, but another thread
2488 // might be in the process of launching a new process that will
2489 // soon replace it, so get a shared pointer to the process so we
2490 // can keep it alive.
2491 ProcessSP process_sp (target_sp->GetProcessSP());
2492 // Now we have a shared pointer to the process that can't go away on us
2493 // so we now make sure it was the same as the one passed in, and also make
2494 // sure that our previous "process *" didn't get deleted and have a new
2495 // "process *" created in its place with the same pointer. To verify this
2496 // we make sure the process has our debugserver process ID. If we pass all
2497 // of these tests, then we are sure that this process is the one we were
2498 // looking for.
2499 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002500 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002501 // Sleep for a half a second to make sure our inferior process has
2502 // time to set its exit status before we set it incorrectly when
2503 // both the debugserver and the inferior process shut down.
2504 usleep (500000);
2505 // If our process hasn't yet exited, debugserver might have died.
2506 // If the process did exit, the we are reaping it.
2507 const StateType state = process->GetState();
2508
2509 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2510 state != eStateInvalid &&
2511 state != eStateUnloaded &&
2512 state != eStateExited &&
2513 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002514 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002515 char error_str[1024];
2516 if (signo)
2517 {
2518 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2519 if (signal_cstr)
2520 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2521 else
2522 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2523 }
Chris Lattner24943d22010-06-08 16:52:24 +00002524 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002525 {
2526 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2527 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002528
Greg Clayton1c4642c2011-11-16 05:37:56 +00002529 process->SetExitStatus (-1, error_str);
2530 }
2531 // Debugserver has exited we need to let our ProcessGDBRemote
2532 // know that it no longer has a debugserver instance
2533 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002534 }
Chris Lattner24943d22010-06-08 16:52:24 +00002535 }
2536 return true;
2537}
2538
2539void
2540ProcessGDBRemote::KillDebugserverProcess ()
2541{
2542 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2543 {
2544 ::kill (m_debugserver_pid, SIGINT);
2545 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2546 }
2547}
2548
2549void
2550ProcessGDBRemote::Initialize()
2551{
2552 static bool g_initialized = false;
2553
2554 if (g_initialized == false)
2555 {
2556 g_initialized = true;
2557 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2558 GetPluginDescriptionStatic(),
2559 CreateInstance);
2560
2561 Log::Callbacks log_callbacks = {
2562 ProcessGDBRemoteLog::DisableLog,
2563 ProcessGDBRemoteLog::EnableLog,
2564 ProcessGDBRemoteLog::ListLogCategories
2565 };
2566
2567 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2568 }
2569}
2570
2571bool
Chris Lattner24943d22010-06-08 16:52:24 +00002572ProcessGDBRemote::StartAsyncThread ()
2573{
Greg Claytone005f2c2010-11-06 01:53:30 +00002574 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002575
2576 if (log)
2577 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2578
2579 // Create a thread that watches our internal state and controls which
2580 // events make it to clients (into the DCProcess event queue).
2581 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002582 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002583}
2584
2585void
2586ProcessGDBRemote::StopAsyncThread ()
2587{
Greg Claytone005f2c2010-11-06 01:53:30 +00002588 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002589
2590 if (log)
2591 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2592
2593 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002594
2595 // This will shut down the async thread.
2596 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002597
2598 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002599 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002600 {
2601 Host::ThreadJoin (m_async_thread, NULL, NULL);
2602 }
2603}
2604
2605
2606void *
2607ProcessGDBRemote::AsyncThread (void *arg)
2608{
2609 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2610
Greg Claytone005f2c2010-11-06 01:53:30 +00002611 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002612 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002613 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002614
2615 Listener listener ("ProcessGDBRemote::AsyncThread");
2616 EventSP event_sp;
2617 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2618 eBroadcastBitAsyncThreadShouldExit;
2619
2620 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2621 {
Greg Claytona2f74232011-02-24 22:24:29 +00002622 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2623
Chris Lattner24943d22010-06-08 16:52:24 +00002624 bool done = false;
2625 while (!done)
2626 {
2627 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002628 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002629 if (listener.WaitForEvent (NULL, event_sp))
2630 {
2631 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002632 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002633 {
Greg Claytona2f74232011-02-24 22:24:29 +00002634 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002635 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 +00002636
Greg Claytona2f74232011-02-24 22:24:29 +00002637 switch (event_type)
2638 {
2639 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002640 {
Greg Claytona2f74232011-02-24 22:24:29 +00002641 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002642
Greg Claytona2f74232011-02-24 22:24:29 +00002643 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002644 {
Greg Claytona2f74232011-02-24 22:24:29 +00002645 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2646 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2647 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002648 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002649
Greg Claytona2f74232011-02-24 22:24:29 +00002650 if (::strstr (continue_cstr, "vAttach") == NULL)
2651 process->SetPrivateState(eStateRunning);
2652 StringExtractorGDBRemote response;
2653 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002654
Greg Clayton67b402c2012-05-16 02:48:06 +00002655 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2656 // The thread ID list might be contained within the "response", or the stop reply packet that
2657 // caused the stop. So clear it now before we give the stop reply packet to the process
2658 // using the process->SetLastStopPacket()...
2659 process->ClearThreadIDList ();
2660
Greg Claytona2f74232011-02-24 22:24:29 +00002661 switch (stop_state)
2662 {
2663 case eStateStopped:
2664 case eStateCrashed:
2665 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002666 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002667 process->SetPrivateState (stop_state);
2668 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002669
Greg Claytona2f74232011-02-24 22:24:29 +00002670 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002671 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002672 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002673 response.SetFilePos(1);
2674 process->SetExitStatus(response.GetHexU8(), NULL);
2675 done = true;
2676 break;
2677
2678 case eStateInvalid:
2679 process->SetExitStatus(-1, "lost connection");
2680 break;
2681
2682 default:
2683 process->SetPrivateState (stop_state);
2684 break;
2685 }
Chris Lattner24943d22010-06-08 16:52:24 +00002686 }
2687 }
Greg Claytona2f74232011-02-24 22:24:29 +00002688 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002689
Greg Claytona2f74232011-02-24 22:24:29 +00002690 case eBroadcastBitAsyncThreadShouldExit:
2691 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002692 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002693 done = true;
2694 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002695
Greg Claytona2f74232011-02-24 22:24:29 +00002696 default:
2697 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002698 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 +00002699 done = true;
2700 break;
2701 }
2702 }
2703 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2704 {
2705 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2706 {
2707 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002708 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002709 }
Chris Lattner24943d22010-06-08 16:52:24 +00002710 }
2711 }
2712 else
2713 {
2714 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002715 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 +00002716 done = true;
2717 }
2718 }
2719 }
2720
2721 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002722 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002723
2724 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2725 return NULL;
2726}
2727
Chris Lattner24943d22010-06-08 16:52:24 +00002728const char *
2729ProcessGDBRemote::GetDispatchQueueNameForThread
2730(
2731 addr_t thread_dispatch_qaddr,
2732 std::string &dispatch_queue_name
2733)
2734{
2735 dispatch_queue_name.clear();
2736 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2737 {
2738 // Cache the dispatch_queue_offsets_addr value so we don't always have
2739 // to look it up
2740 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2741 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002742 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2743 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002744 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2745 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002746 if (module_sp)
2747 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2748
2749 if (dispatch_queue_offsets_symbol == NULL)
2750 {
Greg Clayton444fe992012-02-26 05:51:37 +00002751 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2752 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002753 if (module_sp)
2754 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2755 }
Chris Lattner24943d22010-06-08 16:52:24 +00002756 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002757 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002758
2759 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2760 return NULL;
2761 }
2762
2763 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002764 DataExtractor data (memory_buffer,
2765 sizeof(memory_buffer),
2766 m_target.GetArchitecture().GetByteOrder(),
2767 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002768
2769 // Excerpt from src/queue_private.h
2770 struct dispatch_queue_offsets_s
2771 {
2772 uint16_t dqo_version;
2773 uint16_t dqo_label;
2774 uint16_t dqo_label_size;
2775 } dispatch_queue_offsets;
2776
2777
2778 Error error;
2779 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2780 {
2781 uint32_t data_offset = 0;
2782 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2783 {
2784 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2785 {
2786 data_offset = 0;
2787 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2788 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2789 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2790 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2791 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2792 dispatch_queue_name.erase (bytes_read);
2793 }
2794 }
2795 }
2796 }
2797 if (dispatch_queue_name.empty())
2798 return NULL;
2799 return dispatch_queue_name.c_str();
2800}
2801
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002802//uint32_t
2803//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2804//{
2805// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2806// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2807// if (m_local_debugserver)
2808// {
2809// return Host::ListProcessesMatchingName (name, matches, pids);
2810// }
2811// else
2812// {
2813// // FIXME: Implement talking to the remote debugserver.
2814// return 0;
2815// }
2816//
2817//}
2818//
Jim Ingham55e01d82011-01-22 01:33:44 +00002819bool
2820ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2821 lldb_private::StoppointCallbackContext *context,
2822 lldb::user_id_t break_id,
2823 lldb::user_id_t break_loc_id)
2824{
2825 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2826 // run so I can stop it if that's what I want to do.
2827 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2828 if (log)
2829 log->Printf("Hit New Thread Notification breakpoint.");
2830 return false;
2831}
2832
2833
2834bool
2835ProcessGDBRemote::StartNoticingNewThreads()
2836{
Jim Ingham55e01d82011-01-22 01:33:44 +00002837 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002838 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002839 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002840 if (log && log->GetVerbose())
2841 log->Printf("Enabled noticing new thread breakpoint.");
2842 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002843 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002844 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002845 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002846 PlatformSP platform_sp (m_target.GetPlatform());
2847 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002848 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002849 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2850 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002851 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002852 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002853 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2854 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002855 }
2856 else
2857 {
2858 if (log)
2859 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002860 }
2861 }
2862 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002863 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002864}
2865
2866bool
2867ProcessGDBRemote::StopNoticingNewThreads()
2868{
Jim Inghamff276fe2011-02-08 05:19:01 +00002869 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002870 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002871 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002872
2873 if (m_thread_create_bp_sp)
2874 m_thread_create_bp_sp->SetEnabled(false);
2875
Jim Ingham55e01d82011-01-22 01:33:44 +00002876 return true;
2877}
2878
2879