blob: e48c058d7aba287885d81aba934421231fbab6e2 [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"
Greg Clayton54e7afa2010-07-09 20:39:50 +000050#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000051#include "GDBRemoteRegisterContext.h"
52#include "ProcessGDBRemote.h"
53#include "ProcessGDBRemoteLog.h"
54#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000055#include "StopInfoMachException.h"
56
Greg Clayton451fa822012-04-09 22:46:21 +000057namespace lldb
58{
59 // Provide a function that can easily dump the packet history if we know a
60 // ProcessGDBRemote * value (which we can get from logs or from debugging).
61 // We need the function in the lldb namespace so it makes it into the final
62 // executable since the LLDB shared library only exports stuff in the lldb
63 // namespace. This allows you to attach with a debugger and call this
64 // function and get the packet history dumped to a file.
65 void
66 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
67 {
Greg Clayton33559462012-04-13 21:24:18 +000068 lldb_private::StreamFile strm;
69 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
70 if (error.Success())
71 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000072 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000073}
Chris Lattner24943d22010-06-08 16:52:24 +000074
Chris Lattner24943d22010-06-08 16:52:24 +000075
76#define DEBUGSERVER_BASENAME "debugserver"
77using namespace lldb;
78using namespace lldb_private;
79
Jim Inghamf9600482011-03-29 21:45:47 +000080static bool rand_initialized = false;
81
Chris Lattner24943d22010-06-08 16:52:24 +000082static inline uint16_t
83get_random_port ()
84{
Jim Inghamf9600482011-03-29 21:45:47 +000085 if (!rand_initialized)
86 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000087 time_t seed = time(NULL);
88
Jim Inghamf9600482011-03-29 21:45:47 +000089 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000090 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000091 }
Stephen Wilson50daf772011-03-25 18:16:28 +000092 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000093}
94
95
96const char *
97ProcessGDBRemote::GetPluginNameStatic()
98{
Greg Claytonb1888f22011-03-19 01:12:21 +000099 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000100}
101
102const char *
103ProcessGDBRemote::GetPluginDescriptionStatic()
104{
105 return "GDB Remote protocol based debugging plug-in.";
106}
107
108void
109ProcessGDBRemote::Terminate()
110{
111 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
112}
113
114
Greg Clayton46c9a352012-02-09 06:16:32 +0000115lldb::ProcessSP
116ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000117{
Greg Clayton46c9a352012-02-09 06:16:32 +0000118 lldb::ProcessSP process_sp;
119 if (crash_file_path == NULL)
120 process_sp.reset (new ProcessGDBRemote (target, listener));
121 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000122}
123
124bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000125ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000126{
Greg Clayton61ddf562011-10-21 21:41:45 +0000127 if (plugin_specified_by_name)
128 return true;
129
Chris Lattner24943d22010-06-08 16:52:24 +0000130 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000131 Module *exe_module = target.GetExecutableModulePointer();
132 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000133 {
134 ObjectFile *exe_objfile = exe_module->GetObjectFile();
135 // We can't debug core files...
136 switch (exe_objfile->GetType())
137 {
138 case ObjectFile::eTypeInvalid:
139 case ObjectFile::eTypeCoreFile:
140 case ObjectFile::eTypeDebugInfo:
141 case ObjectFile::eTypeObjectFile:
142 case ObjectFile::eTypeSharedLibrary:
143 case ObjectFile::eTypeStubLibrary:
144 return false;
145 case ObjectFile::eTypeExecutable:
146 case ObjectFile::eTypeDynamicLinker:
147 case ObjectFile::eTypeUnknown:
148 break;
149 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000150 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000151 }
Jim Ingham7508e732010-08-09 23:31:02 +0000152 // However, if there is no executable module, we return true since we might be preparing to attach.
153 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000154}
155
156//----------------------------------------------------------------------
157// ProcessGDBRemote constructor
158//----------------------------------------------------------------------
159ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
160 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000161 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000162 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000163 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000164 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000165 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000166 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000167 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000168 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000169 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000170 m_continue_c_tids (),
171 m_continue_C_tids (),
172 m_continue_s_tids (),
173 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000174 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000175 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000176 m_addr_to_mmap_size (),
177 m_thread_create_bp_sp (),
178 m_waiting_for_attach (false)
Chris Lattner24943d22010-06-08 16:52:24 +0000179{
Greg Claytonff39f742011-04-01 00:29:43 +0000180 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
181 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000182 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000183}
184
185//----------------------------------------------------------------------
186// Destructor
187//----------------------------------------------------------------------
188ProcessGDBRemote::~ProcessGDBRemote()
189{
190 // m_mach_process.UnregisterNotificationCallbacks (this);
191 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000192 // We need to call finalize on the process before destroying ourselves
193 // to make sure all of the broadcaster cleanup goes as planned. If we
194 // destruct this class, then Process::~Process() might have problems
195 // trying to fully destroy the broadcaster.
196 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000197}
198
199//----------------------------------------------------------------------
200// PluginInterface
201//----------------------------------------------------------------------
202const char *
203ProcessGDBRemote::GetPluginName()
204{
205 return "Process debugging plug-in that uses the GDB remote protocol";
206}
207
208const char *
209ProcessGDBRemote::GetShortPluginName()
210{
211 return GetPluginNameStatic();
212}
213
214uint32_t
215ProcessGDBRemote::GetPluginVersion()
216{
217 return 1;
218}
219
220void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000221ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000222{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000223 if (!force && m_register_info.GetNumRegisters() > 0)
224 return;
225
226 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000227 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000228 uint32_t reg_offset = 0;
229 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000230 StringExtractorGDBRemote::ResponseType response_type;
231 for (response_type = StringExtractorGDBRemote::eResponse;
232 response_type == StringExtractorGDBRemote::eResponse;
233 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000234 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000235 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
236 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000237 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000238 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000239 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000240 response_type = response.GetResponseType();
241 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000242 {
243 std::string name;
244 std::string value;
245 ConstString reg_name;
246 ConstString alt_name;
247 ConstString set_name;
248 RegisterInfo reg_info = { NULL, // Name
249 NULL, // Alt name
250 0, // byte size
251 reg_offset, // offset
252 eEncodingUint, // encoding
253 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000254 {
255 LLDB_INVALID_REGNUM, // GCC reg num
256 LLDB_INVALID_REGNUM, // DWARF reg num
257 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000258 reg_num, // GDB reg num
259 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000260 },
261 NULL,
262 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000263 };
264
265 while (response.GetNameColonValue(name, value))
266 {
267 if (name.compare("name") == 0)
268 {
269 reg_name.SetCString(value.c_str());
270 }
271 else if (name.compare("alt-name") == 0)
272 {
273 alt_name.SetCString(value.c_str());
274 }
275 else if (name.compare("bitsize") == 0)
276 {
277 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
278 }
279 else if (name.compare("offset") == 0)
280 {
281 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000282 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000283 {
284 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000285 }
286 }
287 else if (name.compare("encoding") == 0)
288 {
289 if (value.compare("uint") == 0)
290 reg_info.encoding = eEncodingUint;
291 else if (value.compare("sint") == 0)
292 reg_info.encoding = eEncodingSint;
293 else if (value.compare("ieee754") == 0)
294 reg_info.encoding = eEncodingIEEE754;
295 else if (value.compare("vector") == 0)
296 reg_info.encoding = eEncodingVector;
297 }
298 else if (name.compare("format") == 0)
299 {
300 if (value.compare("binary") == 0)
301 reg_info.format = eFormatBinary;
302 else if (value.compare("decimal") == 0)
303 reg_info.format = eFormatDecimal;
304 else if (value.compare("hex") == 0)
305 reg_info.format = eFormatHex;
306 else if (value.compare("float") == 0)
307 reg_info.format = eFormatFloat;
308 else if (value.compare("vector-sint8") == 0)
309 reg_info.format = eFormatVectorOfSInt8;
310 else if (value.compare("vector-uint8") == 0)
311 reg_info.format = eFormatVectorOfUInt8;
312 else if (value.compare("vector-sint16") == 0)
313 reg_info.format = eFormatVectorOfSInt16;
314 else if (value.compare("vector-uint16") == 0)
315 reg_info.format = eFormatVectorOfUInt16;
316 else if (value.compare("vector-sint32") == 0)
317 reg_info.format = eFormatVectorOfSInt32;
318 else if (value.compare("vector-uint32") == 0)
319 reg_info.format = eFormatVectorOfUInt32;
320 else if (value.compare("vector-float32") == 0)
321 reg_info.format = eFormatVectorOfFloat32;
322 else if (value.compare("vector-uint128") == 0)
323 reg_info.format = eFormatVectorOfUInt128;
324 }
325 else if (name.compare("set") == 0)
326 {
327 set_name.SetCString(value.c_str());
328 }
329 else if (name.compare("gcc") == 0)
330 {
331 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
332 }
333 else if (name.compare("dwarf") == 0)
334 {
335 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
336 }
337 else if (name.compare("generic") == 0)
338 {
339 if (value.compare("pc") == 0)
340 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
341 else if (value.compare("sp") == 0)
342 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
343 else if (value.compare("fp") == 0)
344 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
345 else if (value.compare("ra") == 0)
346 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
347 else if (value.compare("flags") == 0)
348 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000349 else if (value.find("arg") == 0)
350 {
351 if (value.size() == 4)
352 {
353 switch (value[3])
354 {
355 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
356 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
357 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
358 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
359 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
360 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
361 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
362 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
363 }
364 }
365 }
Chris Lattner24943d22010-06-08 16:52:24 +0000366 }
367 }
368
Jason Molenda53d96862010-06-11 23:44:18 +0000369 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000370 assert (reg_info.byte_size != 0);
371 reg_offset += reg_info.byte_size;
372 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
373 }
374 }
375 else
376 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000377 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000378 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000379 }
380 }
381
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000382 // We didn't get anything if the accumulated reg_num is zero. See if we are
383 // debugging ARM and fill with a hard coded register set until we can get an
384 // updated debugserver down on the devices.
385 // On the other hand, if the accumulated reg_num is positive, see if we can
386 // add composite registers to the existing primordial ones.
387 bool from_scratch = (reg_num == 0);
388
389 const ArchSpec &target_arch = GetTarget().GetArchitecture();
390 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
391 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000392 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000393 if (remote_arch.IsValid()
394 && remote_arch.GetMachine() == llvm::Triple::arm
395 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
396 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000397 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000398 else if (target_arch.GetMachine() == llvm::Triple::arm)
399 {
400 m_register_info.HardcodeARMRegisters(from_scratch);
401 }
402
Johnny Chend2e30662012-05-22 00:57:05 +0000403 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000404 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
405 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000406 m_register_info.Addx86_64ConvenienceRegisters();
407
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000408 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000409 m_register_info.Finalize ();
410}
411
412Error
413ProcessGDBRemote::WillLaunch (Module* module)
414{
415 return WillLaunchOrAttach ();
416}
417
418Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000419ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000420{
421 return WillLaunchOrAttach ();
422}
423
424Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000425ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000426{
427 return WillLaunchOrAttach ();
428}
429
430Error
Greg Claytone71e2582011-02-04 01:58:07 +0000431ProcessGDBRemote::DoConnectRemote (const char *remote_url)
432{
433 Error error (WillLaunchOrAttach ());
434
435 if (error.Fail())
436 return error;
437
Greg Clayton180546b2011-04-30 01:09:13 +0000438 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000439
440 if (error.Fail())
441 return error;
442 StartAsyncThread ();
443
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000444 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000445 if (pid == LLDB_INVALID_PROCESS_ID)
446 {
447 // We don't have a valid process ID, so note that we are connected
448 // and could now request to launch or attach, or get remote process
449 // listings...
450 SetPrivateState (eStateConnected);
451 }
452 else
453 {
454 // We have a valid process
455 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000456 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000457 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000458 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000459 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000460 if (state == eStateStopped)
461 {
462 SetPrivateState (state);
463 }
464 else
Greg Claytond9919d32011-12-01 23:28:38 +0000465 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 +0000466 }
467 else
Greg Claytond9919d32011-12-01 23:28:38 +0000468 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 +0000469 }
Jason Molendacb740b32012-05-03 22:37:30 +0000470
471 if (error.Success()
472 && !GetTarget().GetArchitecture().IsValid()
473 && m_gdb_comm.GetHostArchitecture().IsValid())
474 {
475 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
476 }
477
Greg Claytone71e2582011-02-04 01:58:07 +0000478 return error;
479}
480
481Error
Chris Lattner24943d22010-06-08 16:52:24 +0000482ProcessGDBRemote::WillLaunchOrAttach ()
483{
484 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000485 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000486 return error;
487}
488
489//----------------------------------------------------------------------
490// Process Control
491//----------------------------------------------------------------------
492Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000493ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000494{
Greg Clayton4b407112010-09-30 21:49:03 +0000495 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000496
497 uint32_t launch_flags = launch_info.GetFlags().Get();
498 const char *stdin_path = NULL;
499 const char *stdout_path = NULL;
500 const char *stderr_path = NULL;
501 const char *working_dir = launch_info.GetWorkingDirectory();
502
503 const ProcessLaunchInfo::FileAction *file_action;
504 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
505 if (file_action)
506 {
507 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
508 stdin_path = file_action->GetPath();
509 }
510 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
511 if (file_action)
512 {
513 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
514 stdout_path = file_action->GetPath();
515 }
516 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
517 if (file_action)
518 {
519 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
520 stderr_path = file_action->GetPath();
521 }
522
Chris Lattner24943d22010-06-08 16:52:24 +0000523 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
524 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
525 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000526 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000527
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000528 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000529 if (object_file)
530 {
Chris Lattner24943d22010-06-08 16:52:24 +0000531 char host_port[128];
532 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000533 char connect_url[128];
534 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000535
Greg Claytona2f74232011-02-24 22:24:29 +0000536 // Make sure we aren't already connected?
537 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000538 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000539 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000540 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000541 {
Johnny Chenc143d622011-08-09 18:56:45 +0000542 if (log)
543 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000544 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000545 }
Chris Lattner24943d22010-06-08 16:52:24 +0000546
Greg Claytone71e2582011-02-04 01:58:07 +0000547 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000548 }
549
550 if (error.Success())
551 {
552 lldb_utility::PseudoTerminal pty;
553 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000554
555 // If the debugserver is local and we aren't disabling STDIO, lets use
556 // a pseudo terminal to instead of relying on the 'O' packets for stdio
557 // since 'O' packets can really slow down debugging if the inferior
558 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000559 PlatformSP platform_sp (m_target.GetPlatform());
560 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000561 {
562 const char *slave_name = NULL;
563 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000564 {
Greg Claytona2f74232011-02-24 22:24:29 +0000565 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
566 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000567 }
Greg Claytona2f74232011-02-24 22:24:29 +0000568 if (stdin_path == NULL)
569 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000570
Greg Claytona2f74232011-02-24 22:24:29 +0000571 if (stdout_path == NULL)
572 stdout_path = slave_name;
573
574 if (stderr_path == NULL)
575 stderr_path = slave_name;
576 }
577
Greg Claytonafb81862011-03-02 21:34:46 +0000578 // Set STDIN to /dev/null if we want STDIO disabled or if either
579 // STDOUT or STDERR have been set to something and STDIN hasn't
580 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000581 stdin_path = "/dev/null";
582
Greg Claytonafb81862011-03-02 21:34:46 +0000583 // Set STDOUT to /dev/null if we want STDIO disabled or if either
584 // STDIN or STDERR have been set to something and STDOUT hasn't
585 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000586 stdout_path = "/dev/null";
587
Greg Claytonafb81862011-03-02 21:34:46 +0000588 // Set STDERR to /dev/null if we want STDIO disabled or if either
589 // STDIN or STDOUT have been set to something and STDERR hasn't
590 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000591 stderr_path = "/dev/null";
592
593 if (stdin_path)
594 m_gdb_comm.SetSTDIN (stdin_path);
595 if (stdout_path)
596 m_gdb_comm.SetSTDOUT (stdout_path);
597 if (stderr_path)
598 m_gdb_comm.SetSTDERR (stderr_path);
599
600 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
601
Greg Claytona4582402011-05-08 04:53:50 +0000602 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000603
604 if (working_dir && working_dir[0])
605 {
606 m_gdb_comm.SetWorkingDir (working_dir);
607 }
608
609 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000610 const Args &environment = launch_info.GetEnvironmentEntries();
611 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000612 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000613 size_t num_environment_entries = environment.GetArgumentCount();
614 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000615 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000616 const char *env_entry = environment.GetArgumentAtIndex(i);
617 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000618 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000619 }
Greg Claytona2f74232011-02-24 22:24:29 +0000620 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000621
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000622 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000623 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000624 if (arg_packet_err == 0)
625 {
626 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000627 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000628 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000629 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000630 }
631 else
632 {
Greg Claytona2f74232011-02-24 22:24:29 +0000633 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000634 }
Greg Claytona2f74232011-02-24 22:24:29 +0000635 }
636 else
637 {
Greg Clayton9c236732011-10-26 00:56:27 +0000638 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000639 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000640
641 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000642
Greg Claytona2f74232011-02-24 22:24:29 +0000643 if (GetID() == LLDB_INVALID_PROCESS_ID)
644 {
Johnny Chenc143d622011-08-09 18:56:45 +0000645 if (log)
646 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000647 KillDebugserverProcess ();
648 return error;
649 }
650
Greg Clayton261a18b2011-06-02 22:22:38 +0000651 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000652 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000653 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000654
655 if (!disable_stdio)
656 {
657 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000658 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000659 }
Chris Lattner24943d22010-06-08 16:52:24 +0000660 }
661 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000662 else
663 {
Johnny Chenc143d622011-08-09 18:56:45 +0000664 if (log)
665 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000666 }
Chris Lattner24943d22010-06-08 16:52:24 +0000667 }
668 else
669 {
670 // Set our user ID to an invalid process ID.
671 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000672 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
673 exe_module->GetFileSpec().GetFilename().AsCString(),
674 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000675 }
Chris Lattner24943d22010-06-08 16:52:24 +0000676 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000677
Chris Lattner24943d22010-06-08 16:52:24 +0000678}
679
680
681Error
Greg Claytone71e2582011-02-04 01:58:07 +0000682ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000683{
684 Error error;
685 // Sleep and wait a bit for debugserver to start to listen...
686 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
687 if (conn_ap.get())
688 {
Chris Lattner24943d22010-06-08 16:52:24 +0000689 const uint32_t max_retry_count = 50;
690 uint32_t retry_count = 0;
691 while (!m_gdb_comm.IsConnected())
692 {
Greg Claytone71e2582011-02-04 01:58:07 +0000693 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000694 {
695 m_gdb_comm.SetConnection (conn_ap.release());
696 break;
697 }
698 retry_count++;
699
700 if (retry_count >= max_retry_count)
701 break;
702
703 usleep (100000);
704 }
705 }
706
707 if (!m_gdb_comm.IsConnected())
708 {
709 if (error.Success())
710 error.SetErrorString("not connected to remote gdb server");
711 return error;
712 }
713
Greg Clayton24bc5d92011-03-30 18:16:51 +0000714 // We always seem to be able to open a connection to a local port
715 // so we need to make sure we can then send data to it. If we can't
716 // then we aren't actually connected to anything, so try and do the
717 // handshake with the remote GDB server and make sure that goes
718 // alright.
719 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000720 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000721 m_gdb_comm.Disconnect();
722 if (error.Success())
723 error.SetErrorString("not connected to remote gdb server");
724 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000725 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000726 m_gdb_comm.ResetDiscoverableSettings();
727 m_gdb_comm.QueryNoAckModeSupported ();
728 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000729 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000730 m_gdb_comm.GetHostInfo ();
731 m_gdb_comm.GetVContSupported ('c');
Jim Ingham86827fb2012-07-02 05:40:07 +0000732
733 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
734 for (size_t idx = 0; idx < num_cmds; idx++)
735 {
736 StringExtractorGDBRemote response;
737 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx));
738 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
739 }
Chris Lattner24943d22010-06-08 16:52:24 +0000740 return error;
741}
742
743void
744ProcessGDBRemote::DidLaunchOrAttach ()
745{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000746 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
747 if (log)
748 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000749 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000750 {
751 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
752
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000753 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000754
Chris Lattner24943d22010-06-08 16:52:24 +0000755 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000756
Greg Claytoncb8977d2011-03-23 00:09:55 +0000757 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
758 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000759 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000760 ArchSpec &target_arch = GetTarget().GetArchitecture();
761
762 if (target_arch.IsValid())
763 {
764 // If the remote host is ARM and we have apple as the vendor, then
765 // ARM executables and shared libraries can have mixed ARM architectures.
766 // You can have an armv6 executable, and if the host is armv7, then the
767 // system will load the best possible architecture for all shared libraries
768 // it has, so we really need to take the remote host architecture as our
769 // defacto architecture in this case.
770
771 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
772 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
773 {
774 target_arch = gdb_remote_arch;
775 }
776 else
777 {
778 // Fill in what is missing in the triple
779 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
780 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000781 if (target_triple.getVendorName().size() == 0)
782 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000783 target_triple.setVendor (remote_triple.getVendor());
784
Greg Clayton2f085c62011-05-15 01:25:55 +0000785 if (target_triple.getOSName().size() == 0)
786 {
787 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000788
Greg Clayton2f085c62011-05-15 01:25:55 +0000789 if (target_triple.getEnvironmentName().size() == 0)
790 target_triple.setEnvironment (remote_triple.getEnvironment());
791 }
792 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000793 }
794 }
795 else
796 {
797 // The target doesn't have a valid architecture yet, set it from
798 // the architecture we got from the remote GDB server
799 target_arch = gdb_remote_arch;
800 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000801 }
Chris Lattner24943d22010-06-08 16:52:24 +0000802 }
803}
804
805void
806ProcessGDBRemote::DidLaunch ()
807{
808 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000809}
810
811Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000812ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000813{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000814 ProcessAttachInfo attach_info;
815 return DoAttachToProcessWithID(attach_pid, attach_info);
816}
817
818Error
819ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
820{
Chris Lattner24943d22010-06-08 16:52:24 +0000821 Error error;
822 // Clear out and clean up from any current state
823 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000824 if (attach_pid != LLDB_INVALID_PROCESS_ID)
825 {
Greg Claytona2f74232011-02-24 22:24:29 +0000826 // Make sure we aren't already connected?
827 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000828 {
Greg Claytona2f74232011-02-24 22:24:29 +0000829 char host_port[128];
830 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
831 char connect_url[128];
832 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000833
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000834 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000835
836 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000837 {
Greg Claytona2f74232011-02-24 22:24:29 +0000838 const char *error_string = error.AsCString();
839 if (error_string == NULL)
840 error_string = "unable to launch " DEBUGSERVER_BASENAME;
841
842 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000843 }
Greg Claytona2f74232011-02-24 22:24:29 +0000844 else
845 {
846 error = ConnectToDebugserver (connect_url);
847 }
848 }
849
850 if (error.Success())
851 {
852 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000853 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000854 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000855 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000856 }
857 }
Chris Lattner24943d22010-06-08 16:52:24 +0000858 return error;
859}
860
861size_t
862ProcessGDBRemote::AttachInputReaderCallback
863(
864 void *baton,
865 InputReader *reader,
866 lldb::InputReaderAction notification,
867 const char *bytes,
868 size_t bytes_len
869)
870{
871 if (notification == eInputReaderGotToken)
872 {
873 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
874 if (gdb_process->m_waiting_for_attach)
875 gdb_process->m_waiting_for_attach = false;
876 reader->SetIsDone(true);
877 return 1;
878 }
879 return 0;
880}
881
882Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000883ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000884{
885 Error error;
886 // Clear out and clean up from any current state
887 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000888
Chris Lattner24943d22010-06-08 16:52:24 +0000889 if (process_name && process_name[0])
890 {
Greg Claytona2f74232011-02-24 22:24:29 +0000891 // Make sure we aren't already connected?
892 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000893 {
Greg Claytona2f74232011-02-24 22:24:29 +0000894 char host_port[128];
895 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
896 char connect_url[128];
897 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
898
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000899 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000900 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000901 {
Greg Claytona2f74232011-02-24 22:24:29 +0000902 const char *error_string = error.AsCString();
903 if (error_string == NULL)
904 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000905
Greg Claytona2f74232011-02-24 22:24:29 +0000906 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000907 }
Greg Claytona2f74232011-02-24 22:24:29 +0000908 else
909 {
910 error = ConnectToDebugserver (connect_url);
911 }
912 }
913
914 if (error.Success())
915 {
916 StreamString packet;
917
918 if (wait_for_launch)
919 packet.PutCString("vAttachWait");
920 else
921 packet.PutCString("vAttachName");
922 packet.PutChar(';');
923 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
924
925 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
926
Chris Lattner24943d22010-06-08 16:52:24 +0000927 }
928 }
Chris Lattner24943d22010-06-08 16:52:24 +0000929 return error;
930}
931
Chris Lattner24943d22010-06-08 16:52:24 +0000932
933void
934ProcessGDBRemote::DidAttach ()
935{
Greg Claytone71e2582011-02-04 01:58:07 +0000936 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000937}
938
939Error
940ProcessGDBRemote::WillResume ()
941{
Greg Claytonc1f45872011-02-12 06:28:37 +0000942 m_continue_c_tids.clear();
943 m_continue_C_tids.clear();
944 m_continue_s_tids.clear();
945 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000946 return Error();
947}
948
949Error
950ProcessGDBRemote::DoResume ()
951{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000952 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000953 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
954 if (log)
955 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000956
957 Listener listener ("gdb-remote.resume-packet-sent");
958 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
959 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000960 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
961
Greg Claytonc1f45872011-02-12 06:28:37 +0000962 StreamString continue_packet;
963 bool continue_packet_error = false;
964 if (m_gdb_comm.HasAnyVContSupport ())
965 {
966 continue_packet.PutCString ("vCont");
967
968 if (!m_continue_c_tids.empty())
969 {
970 if (m_gdb_comm.GetVContSupported ('c'))
971 {
972 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 +0000973 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000974 }
975 else
976 continue_packet_error = true;
977 }
978
979 if (!continue_packet_error && !m_continue_C_tids.empty())
980 {
981 if (m_gdb_comm.GetVContSupported ('C'))
982 {
983 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 +0000984 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000985 }
986 else
987 continue_packet_error = true;
988 }
Greg Claytonb749a262010-12-03 06:02:24 +0000989
Greg Claytonc1f45872011-02-12 06:28:37 +0000990 if (!continue_packet_error && !m_continue_s_tids.empty())
991 {
992 if (m_gdb_comm.GetVContSupported ('s'))
993 {
994 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 +0000995 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000996 }
997 else
998 continue_packet_error = true;
999 }
1000
1001 if (!continue_packet_error && !m_continue_S_tids.empty())
1002 {
1003 if (m_gdb_comm.GetVContSupported ('S'))
1004 {
1005 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 +00001006 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001007 }
1008 else
1009 continue_packet_error = true;
1010 }
1011
1012 if (continue_packet_error)
1013 continue_packet.GetString().clear();
1014 }
1015 else
1016 continue_packet_error = true;
1017
1018 if (continue_packet_error)
1019 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001020 // Either no vCont support, or we tried to use part of the vCont
1021 // packet that wasn't supported by the remote GDB server.
1022 // We need to try and make a simple packet that can do our continue
1023 const size_t num_threads = GetThreadList().GetSize();
1024 const size_t num_continue_c_tids = m_continue_c_tids.size();
1025 const size_t num_continue_C_tids = m_continue_C_tids.size();
1026 const size_t num_continue_s_tids = m_continue_s_tids.size();
1027 const size_t num_continue_S_tids = m_continue_S_tids.size();
1028 if (num_continue_c_tids > 0)
1029 {
1030 if (num_continue_c_tids == num_threads)
1031 {
1032 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001033 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001034 continue_packet.PutChar ('c');
1035 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001036 }
1037 else if (num_continue_c_tids == 1 &&
1038 num_continue_C_tids == 0 &&
1039 num_continue_s_tids == 0 &&
1040 num_continue_S_tids == 0 )
1041 {
1042 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001043 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001044 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001045 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001046 }
1047 }
1048
Greg Claytonde1dd812011-06-24 03:21:43 +00001049 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001050 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001051 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1052 num_continue_C_tids > 0 &&
1053 num_continue_s_tids == 0 &&
1054 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001055 {
1056 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001057 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001058 if (num_continue_C_tids > 1)
1059 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001060 // More that one thread with a signal, yet we don't have
1061 // vCont support and we are being asked to resume each
1062 // thread with a signal, we need to make sure they are
1063 // all the same signal, or we can't issue the continue
1064 // accurately with the current support...
1065 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001066 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001067 continue_packet_error = false;
1068 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1069 {
1070 if (m_continue_C_tids[i].second != continue_signo)
1071 continue_packet_error = true;
1072 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001073 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001074 if (!continue_packet_error)
1075 m_gdb_comm.SetCurrentThreadForRun (-1);
1076 }
1077 else
1078 {
1079 // Set the continue thread ID
1080 continue_packet_error = false;
1081 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001082 }
1083 if (!continue_packet_error)
1084 {
1085 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001086 continue_packet.Printf("C%2.2x", continue_signo);
1087 }
1088 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001089 }
1090
Greg Claytonde1dd812011-06-24 03:21:43 +00001091 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001092 {
1093 if (num_continue_s_tids == num_threads)
1094 {
1095 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001096 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001097 continue_packet.PutChar ('s');
1098 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001099 }
1100 else if (num_continue_c_tids == 0 &&
1101 num_continue_C_tids == 0 &&
1102 num_continue_s_tids == 1 &&
1103 num_continue_S_tids == 0 )
1104 {
1105 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001106 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001107 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001108 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001109 }
1110 }
1111
1112 if (!continue_packet_error && num_continue_S_tids > 0)
1113 {
1114 if (num_continue_S_tids == num_threads)
1115 {
1116 const int step_signo = m_continue_S_tids.front().second;
1117 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001118 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001119 if (num_continue_S_tids > 1)
1120 {
1121 for (size_t i=1; i<num_threads; ++i)
1122 {
1123 if (m_continue_S_tids[i].second != step_signo)
1124 continue_packet_error = true;
1125 }
1126 }
1127 if (!continue_packet_error)
1128 {
1129 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001130 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001131 continue_packet.Printf("S%2.2x", step_signo);
1132 }
1133 }
1134 else if (num_continue_c_tids == 0 &&
1135 num_continue_C_tids == 0 &&
1136 num_continue_s_tids == 0 &&
1137 num_continue_S_tids == 1 )
1138 {
1139 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001140 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001141 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001142 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001143 }
1144 }
1145 }
1146
1147 if (continue_packet_error)
1148 {
1149 error.SetErrorString ("can't make continue packet for this resume");
1150 }
1151 else
1152 {
1153 EventSP event_sp;
1154 TimeValue timeout;
1155 timeout = TimeValue::Now();
1156 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001157 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1158 {
1159 error.SetErrorString ("Trying to resume but the async thread is dead.");
1160 if (log)
1161 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1162 return error;
1163 }
1164
Greg Claytonc1f45872011-02-12 06:28:37 +00001165 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1166
1167 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001168 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001169 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001170 if (log)
1171 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1172 }
1173 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1174 {
1175 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1176 if (log)
1177 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1178 return error;
1179 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001180 }
Greg Claytonb749a262010-12-03 06:02:24 +00001181 }
1182
Jim Ingham3ae449a2010-11-17 02:32:00 +00001183 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001184}
1185
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001186void
1187ProcessGDBRemote::ClearThreadIDList ()
1188{
Greg Claytonff3448e2012-04-13 02:11:32 +00001189 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001190 m_thread_ids.clear();
1191}
1192
1193bool
1194ProcessGDBRemote::UpdateThreadIDList ()
1195{
Greg Claytonff3448e2012-04-13 02:11:32 +00001196 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001197 bool sequence_mutex_unavailable = false;
1198 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1199 if (sequence_mutex_unavailable)
1200 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001201 return false; // We just didn't get the list
1202 }
1203 return true;
1204}
1205
Greg Claytonae932352012-04-10 00:18:59 +00001206bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001207ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001208{
1209 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001210 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001211 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001212 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001213
1214 size_t num_thread_ids = m_thread_ids.size();
1215 // The "m_thread_ids" thread ID list should always be updated after each stop
1216 // reply packet, but in case it isn't, update it here.
1217 if (num_thread_ids == 0)
1218 {
1219 if (!UpdateThreadIDList ())
1220 return false;
1221 num_thread_ids = m_thread_ids.size();
1222 }
Chris Lattner24943d22010-06-08 16:52:24 +00001223
Greg Clayton37f962e2011-08-22 02:49:39 +00001224 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001225 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001226 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001227 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001228 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001229 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1230 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001231 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001232 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001233 }
Chris Lattner24943d22010-06-08 16:52:24 +00001234 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001235
Greg Claytonae932352012-04-10 00:18:59 +00001236 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001237}
1238
1239
1240StateType
1241ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1242{
Greg Clayton261a18b2011-06-02 22:22:38 +00001243 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001244 const char stop_type = stop_packet.GetChar();
1245 switch (stop_type)
1246 {
1247 case 'T':
1248 case 'S':
1249 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001250 if (GetStopID() == 0)
1251 {
1252 // Our first stop, make sure we have a process ID, and also make
1253 // sure we know about our registers
1254 if (GetID() == LLDB_INVALID_PROCESS_ID)
1255 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001256 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001257 if (pid != LLDB_INVALID_PROCESS_ID)
1258 SetID (pid);
1259 }
1260 BuildDynamicRegisterInfo (true);
1261 }
Chris Lattner24943d22010-06-08 16:52:24 +00001262 // Stop with signal and thread info
1263 const uint8_t signo = stop_packet.GetHexU8();
1264 std::string name;
1265 std::string value;
1266 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001267 std::string reason;
1268 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001269 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001270 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001271 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1272 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001273 ThreadSP thread_sp;
1274
Chris Lattner24943d22010-06-08 16:52:24 +00001275 while (stop_packet.GetNameColonValue(name, value))
1276 {
1277 if (name.compare("metype") == 0)
1278 {
1279 // exception type in big endian hex
1280 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1281 }
1282 else if (name.compare("mecount") == 0)
1283 {
1284 // exception count in big endian hex
1285 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1286 }
1287 else if (name.compare("medata") == 0)
1288 {
1289 // exception data in big endian hex
1290 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1291 }
1292 else if (name.compare("thread") == 0)
1293 {
1294 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001295 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001296 // m_thread_list does have its own mutex, but we need to
1297 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1298 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001299 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001300 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001301 if (!thread_sp)
1302 {
1303 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001304 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001305 m_thread_list.AddThread(thread_sp);
1306 }
Chris Lattner24943d22010-06-08 16:52:24 +00001307 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001308 else if (name.compare("threads") == 0)
1309 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001310 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001311 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001312 // A comma separated list of all threads in the current
1313 // process that includes the thread for this stop reply
1314 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001315 size_t comma_pos;
1316 lldb::tid_t tid;
1317 while ((comma_pos = value.find(',')) != std::string::npos)
1318 {
1319 value[comma_pos] = '\0';
1320 // thread in big endian hex
1321 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1322 if (tid != LLDB_INVALID_THREAD_ID)
1323 m_thread_ids.push_back (tid);
1324 value.erase(0, comma_pos + 1);
1325
1326 }
1327 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1328 if (tid != LLDB_INVALID_THREAD_ID)
1329 m_thread_ids.push_back (tid);
1330 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001331 else if (name.compare("hexname") == 0)
1332 {
1333 StringExtractor name_extractor;
1334 // Swap "value" over into "name_extractor"
1335 name_extractor.GetStringRef().swap(value);
1336 // Now convert the HEX bytes into a string value
1337 name_extractor.GetHexByteString (value);
1338 thread_name.swap (value);
1339 }
Chris Lattner24943d22010-06-08 16:52:24 +00001340 else if (name.compare("name") == 0)
1341 {
1342 thread_name.swap (value);
1343 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001344 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001345 {
1346 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1347 }
Greg Clayton65611552011-06-04 01:26:29 +00001348 else if (name.compare("reason") == 0)
1349 {
1350 reason.swap(value);
1351 }
1352 else if (name.compare("description") == 0)
1353 {
1354 StringExtractor desc_extractor;
1355 // Swap "value" over into "name_extractor"
1356 desc_extractor.GetStringRef().swap(value);
1357 // Now convert the HEX bytes into a string value
1358 desc_extractor.GetHexByteString (thread_name);
1359 }
Greg Claytona875b642011-01-09 21:07:35 +00001360 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1361 {
1362 // We have a register number that contains an expedited
1363 // register value. Lets supply this register to our thread
1364 // so it won't have to go and read it.
1365 if (thread_sp)
1366 {
1367 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1368
1369 if (reg != UINT32_MAX)
1370 {
1371 StringExtractor reg_value_extractor;
1372 // Swap "value" over into "reg_value_extractor"
1373 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001374 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1375 {
1376 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1377 name.c_str(),
1378 reg,
1379 reg,
1380 reg_value_extractor.GetStringRef().c_str(),
1381 stop_packet.GetStringRef().c_str());
1382 }
Greg Claytona875b642011-01-09 21:07:35 +00001383 }
1384 }
1385 }
Chris Lattner24943d22010-06-08 16:52:24 +00001386 }
Chris Lattner24943d22010-06-08 16:52:24 +00001387
1388 if (thread_sp)
1389 {
1390 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1391
1392 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001393 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001394 if (exc_type != 0)
1395 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001396 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001397
1398 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1399 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001400 exc_data_size,
1401 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001402 exc_data_size >= 2 ? exc_data[1] : 0,
1403 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001404 }
Greg Clayton65611552011-06-04 01:26:29 +00001405 else
Chris Lattner24943d22010-06-08 16:52:24 +00001406 {
Greg Clayton65611552011-06-04 01:26:29 +00001407 bool handled = false;
1408 if (!reason.empty())
1409 {
1410 if (reason.compare("trace") == 0)
1411 {
1412 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1413 handled = true;
1414 }
1415 else if (reason.compare("breakpoint") == 0)
1416 {
1417 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001418 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001419 if (bp_site_sp)
1420 {
1421 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1422 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1423 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1424 if (bp_site_sp->ValidForThisThread (gdb_thread))
1425 {
1426 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1427 handled = true;
1428 }
1429 }
1430
1431 if (!handled)
1432 {
1433 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1434 }
1435 }
1436 else if (reason.compare("trap") == 0)
1437 {
1438 // Let the trap just use the standard signal stop reason below...
1439 }
1440 else if (reason.compare("watchpoint") == 0)
1441 {
1442 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1443 // TODO: locate the watchpoint somehow...
1444 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1445 handled = true;
1446 }
1447 else if (reason.compare("exception") == 0)
1448 {
1449 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1450 handled = true;
1451 }
1452 }
1453
1454 if (signo)
1455 {
1456 if (signo == SIGTRAP)
1457 {
1458 // Currently we are going to assume SIGTRAP means we are either
1459 // hitting a breakpoint or hardware single stepping.
1460 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001461 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001462 if (bp_site_sp)
1463 {
1464 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1465 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1466 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1467 if (bp_site_sp->ValidForThisThread (gdb_thread))
1468 {
1469 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1470 handled = true;
1471 }
1472 }
1473 if (!handled)
1474 {
1475 // TODO: check for breakpoint or trap opcode in case there is a hard
1476 // coded software trap
1477 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1478 handled = true;
1479 }
1480 }
1481 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001482 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001483 }
1484 else
1485 {
Greg Clayton643ee732010-08-04 01:40:35 +00001486 StopInfoSP invalid_stop_info_sp;
1487 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001488 }
Greg Clayton65611552011-06-04 01:26:29 +00001489
1490 if (!description.empty())
1491 {
1492 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1493 if (stop_info_sp)
1494 {
1495 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001496 }
Greg Clayton65611552011-06-04 01:26:29 +00001497 else
1498 {
1499 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1500 }
1501 }
1502 }
Chris Lattner24943d22010-06-08 16:52:24 +00001503 }
1504 return eStateStopped;
1505 }
1506 break;
1507
1508 case 'W':
1509 // process exited
1510 return eStateExited;
1511
1512 default:
1513 break;
1514 }
1515 return eStateInvalid;
1516}
1517
1518void
1519ProcessGDBRemote::RefreshStateAfterStop ()
1520{
Greg Claytonff3448e2012-04-13 02:11:32 +00001521 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001522 m_thread_ids.clear();
1523 // Set the thread stop info. It might have a "threads" key whose value is
1524 // a list of all thread IDs in the current process, so m_thread_ids might
1525 // get set.
1526 SetThreadStopInfo (m_last_stop_packet);
1527 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1528 if (m_thread_ids.empty())
1529 {
1530 // No, we need to fetch the thread list manually
1531 UpdateThreadIDList();
1532 }
1533
Chris Lattner24943d22010-06-08 16:52:24 +00001534 // Let all threads recover from stopping and do any clean up based
1535 // on the previous thread state (if any).
1536 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001537
Chris Lattner24943d22010-06-08 16:52:24 +00001538}
1539
1540Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001541ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001542{
1543 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001544
Greg Claytona4881d02011-01-22 07:12:45 +00001545 bool timed_out = false;
1546 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001547
1548 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001549 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001550 // We are being asked to halt during an attach. We need to just close
1551 // our file handle and debugserver will go away, and we can be done...
1552 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001553 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001554 else
1555 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001556 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001557 {
1558 if (timed_out)
1559 error.SetErrorString("timed out sending interrupt packet");
1560 else
1561 error.SetErrorString("unknown error sending interrupt packet");
1562 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001563
1564 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001565 }
Chris Lattner24943d22010-06-08 16:52:24 +00001566 return error;
1567}
1568
1569Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001570ProcessGDBRemote::InterruptIfRunning
1571(
1572 bool discard_thread_plans,
1573 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001574 EventSP &stop_event_sp
1575)
Chris Lattner24943d22010-06-08 16:52:24 +00001576{
1577 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001578
Greg Clayton2860ba92011-01-23 19:58:49 +00001579 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1580
Greg Clayton68ca8232011-01-25 02:58:48 +00001581 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001582 const bool is_running = m_gdb_comm.IsRunning();
1583 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001584 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001585 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001586 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001587 is_running);
1588
Greg Clayton2860ba92011-01-23 19:58:49 +00001589 if (discard_thread_plans)
1590 {
1591 if (log)
1592 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1593 m_thread_list.DiscardThreadPlans();
1594 }
1595 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001596 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001597 if (catch_stop_event)
1598 {
1599 if (log)
1600 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1601 PausePrivateStateThread();
1602 paused_private_state_thread = true;
1603 }
1604
Greg Clayton4fb400f2010-09-27 21:07:38 +00001605 bool timed_out = false;
1606 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001607
Greg Clayton05e4d972012-03-29 01:55:41 +00001608 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001609 {
1610 if (timed_out)
1611 error.SetErrorString("timed out sending interrupt packet");
1612 else
1613 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001614 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001615 ResumePrivateStateThread();
1616 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001617 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001618
Greg Clayton72e1c782011-01-22 23:43:18 +00001619 if (catch_stop_event)
1620 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001621 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001622 TimeValue timeout_time;
1623 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001624 timeout_time.OffsetWithSeconds(5);
1625 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001626
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001627 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001628 if (log)
1629 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001630
Greg Clayton2860ba92011-01-23 19:58:49 +00001631 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001632 error.SetErrorString("unable to verify target stopped");
1633 }
1634
Greg Clayton68ca8232011-01-25 02:58:48 +00001635 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001636 {
1637 if (log)
1638 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001639 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001640 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001641 }
Chris Lattner24943d22010-06-08 16:52:24 +00001642 return error;
1643}
1644
Greg Clayton4fb400f2010-09-27 21:07:38 +00001645Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001646ProcessGDBRemote::WillDetach ()
1647{
Greg Clayton2860ba92011-01-23 19:58:49 +00001648 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1649 if (log)
1650 log->Printf ("ProcessGDBRemote::WillDetach()");
1651
Greg Clayton72e1c782011-01-22 23:43:18 +00001652 bool discard_thread_plans = true;
1653 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001654 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001655
1656 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1657 // needed. This shouldn't be a feature of a particular plugin.
1658
Greg Clayton68ca8232011-01-25 02:58:48 +00001659 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001660}
1661
1662Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001663ProcessGDBRemote::DoDetach()
1664{
1665 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001666 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001667 if (log)
1668 log->Printf ("ProcessGDBRemote::DoDetach()");
1669
1670 DisableAllBreakpointSites ();
1671
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001672 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001673
Greg Clayton516f0842012-04-11 00:24:49 +00001674 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001675 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001676 {
Greg Clayton516f0842012-04-11 00:24:49 +00001677 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001678 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1679 else
1680 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001681 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001682 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001683 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001684
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001685 SetPrivateState (eStateDetached);
1686 ResumePrivateStateThread();
1687
1688 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001689 return error;
1690}
Chris Lattner24943d22010-06-08 16:52:24 +00001691
1692Error
1693ProcessGDBRemote::DoDestroy ()
1694{
1695 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001696 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001697 if (log)
1698 log->Printf ("ProcessGDBRemote::DoDestroy()");
1699
1700 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001701 int exit_status = SIGABRT;
1702 std::string exit_string;
1703
Greg Claytona4881d02011-01-22 07:12:45 +00001704 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001705 {
Jim Ingham8226e942011-10-28 01:11:35 +00001706 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001707 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001708
1709 StringExtractorGDBRemote response;
1710 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001711 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001712 {
1713 char packet_cmd = response.GetChar(0);
1714
1715 if (packet_cmd == 'W' || packet_cmd == 'X')
1716 {
Greg Clayton06709002011-12-06 04:51:14 +00001717 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001718 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001719 exit_status = response.GetHexU8();
1720 }
1721 else
1722 {
1723 if (log)
1724 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1725 exit_string.assign("got unexpected response to k packet: ");
1726 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001727 }
1728 }
1729 else
1730 {
Jim Ingham8247e622012-06-06 00:32:39 +00001731 if (log)
1732 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1733 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001734 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001735 }
Jim Ingham8247e622012-06-06 00:32:39 +00001736 else
1737 {
1738 if (log)
1739 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1740 exit_string.assign ("killing while attaching.");
1741 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001742 }
Jim Ingham8247e622012-06-06 00:32:39 +00001743 else
1744 {
1745 // If we missed setting the exit status on the way out, do it here.
1746 // NB set exit status can be called multiple times, the first one sets the status.
1747 exit_string.assign("destroying when not connected to debugserver");
1748 }
1749
1750 SetExitStatus(exit_status, exit_string.c_str());
1751
Chris Lattner24943d22010-06-08 16:52:24 +00001752 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001753 KillDebugserverProcess ();
1754 return error;
1755}
1756
Chris Lattner24943d22010-06-08 16:52:24 +00001757//------------------------------------------------------------------
1758// Process Queries
1759//------------------------------------------------------------------
1760
1761bool
1762ProcessGDBRemote::IsAlive ()
1763{
Greg Clayton58e844b2010-12-08 05:08:21 +00001764 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001765}
1766
1767addr_t
1768ProcessGDBRemote::GetImageInfoAddress()
1769{
Greg Clayton516f0842012-04-11 00:24:49 +00001770 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001771}
1772
Chris Lattner24943d22010-06-08 16:52:24 +00001773//------------------------------------------------------------------
1774// Process Memory
1775//------------------------------------------------------------------
1776size_t
1777ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1778{
1779 if (size > m_max_memory_size)
1780 {
1781 // Keep memory read sizes down to a sane limit. This function will be
1782 // called multiple times in order to complete the task by
1783 // lldb_private::Process so it is ok to do this.
1784 size = m_max_memory_size;
1785 }
1786
1787 char packet[64];
1788 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1789 assert (packet_len + 1 < sizeof(packet));
1790 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001791 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001792 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001793 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001794 {
1795 error.Clear();
1796 return response.GetHexBytes(buf, size, '\xdd');
1797 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001798 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001799 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001800 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001801 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1802 else
1803 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1804 }
1805 else
1806 {
1807 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1808 }
1809 return 0;
1810}
1811
1812size_t
1813ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1814{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001815 if (size > m_max_memory_size)
1816 {
1817 // Keep memory read sizes down to a sane limit. This function will be
1818 // called multiple times in order to complete the task by
1819 // lldb_private::Process so it is ok to do this.
1820 size = m_max_memory_size;
1821 }
1822
Chris Lattner24943d22010-06-08 16:52:24 +00001823 StreamString packet;
1824 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001825 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001826 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001827 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001828 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001829 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001830 {
1831 error.Clear();
1832 return size;
1833 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001834 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001835 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001836 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001837 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1838 else
1839 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1840 }
1841 else
1842 {
1843 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1844 }
1845 return 0;
1846}
1847
1848lldb::addr_t
1849ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1850{
Greg Clayton989816b2011-05-14 01:50:35 +00001851 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1852
Greg Clayton2f085c62011-05-15 01:25:55 +00001853 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001854 switch (supported)
1855 {
1856 case eLazyBoolCalculate:
1857 case eLazyBoolYes:
1858 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1859 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1860 return allocated_addr;
1861
1862 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001863 // Call mmap() to create memory in the inferior..
1864 unsigned prot = 0;
1865 if (permissions & lldb::ePermissionsReadable)
1866 prot |= eMmapProtRead;
1867 if (permissions & lldb::ePermissionsWritable)
1868 prot |= eMmapProtWrite;
1869 if (permissions & lldb::ePermissionsExecutable)
1870 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001871
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001872 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1873 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1874 m_addr_to_mmap_size[allocated_addr] = size;
1875 else
1876 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001877 break;
1878 }
1879
Chris Lattner24943d22010-06-08 16:52:24 +00001880 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001881 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001882 else
1883 error.Clear();
1884 return allocated_addr;
1885}
1886
1887Error
Greg Claytona9385532011-11-18 07:03:08 +00001888ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1889 MemoryRegionInfo &region_info)
1890{
1891
1892 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1893 return error;
1894}
1895
1896Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00001897ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
1898{
1899
1900 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
1901 return error;
1902}
1903
1904Error
Chris Lattner24943d22010-06-08 16:52:24 +00001905ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1906{
1907 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001908 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1909
1910 switch (supported)
1911 {
1912 case eLazyBoolCalculate:
1913 // We should never be deallocating memory without allocating memory
1914 // first so we should never get eLazyBoolCalculate
1915 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1916 break;
1917
1918 case eLazyBoolYes:
1919 if (!m_gdb_comm.DeallocateMemory (addr))
1920 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1921 break;
1922
1923 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001924 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001925 {
1926 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001927 if (pos != m_addr_to_mmap_size.end() &&
1928 InferiorCallMunmap(this, addr, pos->second))
1929 m_addr_to_mmap_size.erase (pos);
1930 else
1931 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001932 }
1933 break;
1934 }
1935
Chris Lattner24943d22010-06-08 16:52:24 +00001936 return error;
1937}
1938
1939
1940//------------------------------------------------------------------
1941// Process STDIO
1942//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001943size_t
1944ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1945{
1946 if (m_stdio_communication.IsConnected())
1947 {
1948 ConnectionStatus status;
1949 m_stdio_communication.Write(src, src_len, status, NULL);
1950 }
1951 return 0;
1952}
1953
1954Error
1955ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1956{
1957 Error error;
1958 assert (bp_site != NULL);
1959
Greg Claytone005f2c2010-11-06 01:53:30 +00001960 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001961 user_id_t site_id = bp_site->GetID();
1962 const addr_t addr = bp_site->GetLoadAddress();
1963 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001964 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001965
1966 if (bp_site->IsEnabled())
1967 {
1968 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001969 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 +00001970 return error;
1971 }
1972 else
1973 {
1974 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1975
1976 if (bp_site->HardwarePreferred())
1977 {
1978 // Try and set hardware breakpoint, and if that fails, fall through
1979 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001980 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001981 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001982 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001983 {
1984 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001985 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001986 return error;
1987 }
Chris Lattner24943d22010-06-08 16:52:24 +00001988 }
1989 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001990
1991 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001992 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001993 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1994 {
1995 bp_site->SetEnabled(true);
1996 bp_site->SetType (BreakpointSite::eExternal);
1997 return error;
1998 }
Chris Lattner24943d22010-06-08 16:52:24 +00001999 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002000
2001 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002002 }
2003
2004 if (log)
2005 {
2006 const char *err_string = error.AsCString();
2007 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2008 bp_site->GetLoadAddress(),
2009 err_string ? err_string : "NULL");
2010 }
2011 // We shouldn't reach here on a successful breakpoint enable...
2012 if (error.Success())
2013 error.SetErrorToGenericError();
2014 return error;
2015}
2016
2017Error
2018ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2019{
2020 Error error;
2021 assert (bp_site != NULL);
2022 addr_t addr = bp_site->GetLoadAddress();
2023 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002024 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002025 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002026 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002027
2028 if (bp_site->IsEnabled())
2029 {
2030 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2031
Greg Claytonb72d0f02011-04-12 05:54:46 +00002032 BreakpointSite::Type bp_type = bp_site->GetType();
2033 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002034 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002035 case BreakpointSite::eSoftware:
2036 error = DisableSoftwareBreakpoint (bp_site);
2037 break;
2038
2039 case BreakpointSite::eHardware:
2040 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2041 error.SetErrorToGenericError();
2042 break;
2043
2044 case BreakpointSite::eExternal:
2045 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2046 error.SetErrorToGenericError();
2047 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002048 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002049 if (error.Success())
2050 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002051 }
2052 else
2053 {
2054 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002055 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 +00002056 return error;
2057 }
2058
2059 if (error.Success())
2060 error.SetErrorToGenericError();
2061 return error;
2062}
2063
Johnny Chen21900fb2011-09-06 22:38:36 +00002064// Pre-requisite: wp != NULL.
2065static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002066GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002067{
2068 assert(wp);
2069 bool watch_read = wp->WatchpointRead();
2070 bool watch_write = wp->WatchpointWrite();
2071
2072 // watch_read and watch_write cannot both be false.
2073 assert(watch_read || watch_write);
2074 if (watch_read && watch_write)
2075 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002076 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002077 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002078 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002079 return eWatchpointWrite;
2080}
2081
Chris Lattner24943d22010-06-08 16:52:24 +00002082Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002083ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002084{
2085 Error error;
2086 if (wp)
2087 {
2088 user_id_t watchID = wp->GetID();
2089 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002090 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002091 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002092 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002093 if (wp->IsEnabled())
2094 {
2095 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002096 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002097 return error;
2098 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002099
2100 GDBStoppointType type = GetGDBStoppointType(wp);
2101 // Pass down an appropriate z/Z packet...
2102 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002103 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002104 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2105 {
2106 wp->SetEnabled(true);
2107 return error;
2108 }
2109 else
2110 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002111 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002112 else
2113 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002114 }
2115 else
2116 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002117 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002118 }
2119 if (error.Success())
2120 error.SetErrorToGenericError();
2121 return error;
2122}
2123
2124Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002125ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002126{
2127 Error error;
2128 if (wp)
2129 {
2130 user_id_t watchID = wp->GetID();
2131
Greg Claytone005f2c2010-11-06 01:53:30 +00002132 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002133
2134 addr_t addr = wp->GetLoadAddress();
2135 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002136 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002137
Johnny Chen21900fb2011-09-06 22:38:36 +00002138 if (!wp->IsEnabled())
2139 {
2140 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002141 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002142 return error;
2143 }
2144
Chris Lattner24943d22010-06-08 16:52:24 +00002145 if (wp->IsHardware())
2146 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002147 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002148 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002149 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2150 {
2151 wp->SetEnabled(false);
2152 return error;
2153 }
2154 else
2155 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002156 }
2157 // TODO: clear software watchpoints if we implement them
2158 }
2159 else
2160 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002161 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002162 }
2163 if (error.Success())
2164 error.SetErrorToGenericError();
2165 return error;
2166}
2167
2168void
2169ProcessGDBRemote::Clear()
2170{
2171 m_flags = 0;
2172 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002173}
2174
2175Error
2176ProcessGDBRemote::DoSignal (int signo)
2177{
2178 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002179 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002180 if (log)
2181 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2182
2183 if (!m_gdb_comm.SendAsyncSignal (signo))
2184 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2185 return error;
2186}
2187
Chris Lattner24943d22010-06-08 16:52:24 +00002188Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002189ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2190{
2191 ProcessLaunchInfo launch_info;
2192 return StartDebugserverProcess(debugserver_url, launch_info);
2193}
2194
2195Error
2196ProcessGDBRemote::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 +00002197{
2198 Error error;
2199 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2200 {
2201 // If we locate debugserver, keep that located version around
2202 static FileSpec g_debugserver_file_spec;
2203
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002204 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002205 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002206 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002207
2208 // Always check to see if we have an environment override for the path
2209 // to the debugserver to use and use it if we do.
2210 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2211 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002212 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002213 else
2214 debugserver_file_spec = g_debugserver_file_spec;
2215 bool debugserver_exists = debugserver_file_spec.Exists();
2216 if (!debugserver_exists)
2217 {
2218 // The debugserver binary is in the LLDB.framework/Resources
2219 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002220 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002221 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002222 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002223 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002224 if (debugserver_exists)
2225 {
2226 g_debugserver_file_spec = debugserver_file_spec;
2227 }
2228 else
2229 {
2230 g_debugserver_file_spec.Clear();
2231 debugserver_file_spec.Clear();
2232 }
Chris Lattner24943d22010-06-08 16:52:24 +00002233 }
2234 }
2235
2236 if (debugserver_exists)
2237 {
2238 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2239
2240 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002241
Greg Claytone005f2c2010-11-06 01:53:30 +00002242 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002243
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002244 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002245 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002246
Chris Lattner24943d22010-06-08 16:52:24 +00002247 // Start args with "debugserver /file/path -r --"
2248 debugserver_args.AppendArgument(debugserver_path);
2249 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002250 // use native registers, not the GDB registers
2251 debugserver_args.AppendArgument("--native-regs");
2252 // make debugserver run in its own session so signals generated by
2253 // special terminal key sequences (^C) don't affect debugserver
2254 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002255
Chris Lattner24943d22010-06-08 16:52:24 +00002256 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2257 if (env_debugserver_log_file)
2258 {
2259 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2260 debugserver_args.AppendArgument(arg_cstr);
2261 }
2262
2263 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2264 if (env_debugserver_log_flags)
2265 {
2266 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2267 debugserver_args.AppendArgument(arg_cstr);
2268 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002269// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002270// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002271
Greg Claytonb72d0f02011-04-12 05:54:46 +00002272 // We currently send down all arguments, attach pids, or attach
2273 // process names in dedicated GDB server packets, so we don't need
2274 // to pass them as arguments. This is currently because of all the
2275 // things we need to setup prior to launching: the environment,
2276 // current working dir, file actions, etc.
2277#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002278 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002279 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002280 {
Greg Claytona2f74232011-02-24 22:24:29 +00002281 // Terminate the debugserver args so we can now append the inferior args
2282 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002283
Greg Claytona2f74232011-02-24 22:24:29 +00002284 for (int i = 0; inferior_argv[i] != NULL; ++i)
2285 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002286 }
2287 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2288 {
2289 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2290 debugserver_args.AppendArgument (arg_cstr);
2291 }
2292 else if (attach_name && attach_name[0])
2293 {
2294 if (wait_for_launch)
2295 debugserver_args.AppendArgument ("--waitfor");
2296 else
2297 debugserver_args.AppendArgument ("--attach");
2298 debugserver_args.AppendArgument (attach_name);
2299 }
Chris Lattner24943d22010-06-08 16:52:24 +00002300#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002301
2302 ProcessLaunchInfo::FileAction file_action;
2303
2304 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2305 // to "/dev/null" if we run into any problems.
2306 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002307 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002308 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002309 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002310 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002311 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002312
2313 if (log)
2314 {
2315 StreamString strm;
2316 debugserver_args.Dump (&strm);
2317 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2318 }
2319
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002320 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2321 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002322
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002323 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002324
Greg Claytonb72d0f02011-04-12 05:54:46 +00002325 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002326 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002327 else
Chris Lattner24943d22010-06-08 16:52:24 +00002328 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2329
2330 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002331 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002332 }
2333 else
2334 {
Greg Clayton9c236732011-10-26 00:56:27 +00002335 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002336 }
2337
2338 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2339 StartAsyncThread ();
2340 }
2341 return error;
2342}
2343
2344bool
2345ProcessGDBRemote::MonitorDebugserverProcess
2346(
2347 void *callback_baton,
2348 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002349 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002350 int signo, // Zero for no signal
2351 int exit_status // Exit value of process if signal is zero
2352)
2353{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002354 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2355 // and might not exist anymore, so we need to carefully try to get the
2356 // target for this process first since we have a race condition when
2357 // we are done running between getting the notice that the inferior
2358 // process has died and the debugserver that was debugging this process.
2359 // In our test suite, we are also continually running process after
2360 // process, so we must be very careful to make sure:
2361 // 1 - process object hasn't been deleted already
2362 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002363
2364 // "debugserver_pid" argument passed in is the process ID for
2365 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002366 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002367
Greg Clayton75ccf502010-08-21 02:22:51 +00002368 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002369
Greg Clayton1c4642c2011-11-16 05:37:56 +00002370 // Get a shared pointer to the target that has a matching process pointer.
2371 // This target could be gone, or the target could already have a new process
2372 // object inside of it
2373 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2374
Greg Clayton72e1c782011-01-22 23:43:18 +00002375 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002376 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 +00002377
Greg Clayton1c4642c2011-11-16 05:37:56 +00002378 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002379 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002380 // We found a process in a target that matches, but another thread
2381 // might be in the process of launching a new process that will
2382 // soon replace it, so get a shared pointer to the process so we
2383 // can keep it alive.
2384 ProcessSP process_sp (target_sp->GetProcessSP());
2385 // Now we have a shared pointer to the process that can't go away on us
2386 // so we now make sure it was the same as the one passed in, and also make
2387 // sure that our previous "process *" didn't get deleted and have a new
2388 // "process *" created in its place with the same pointer. To verify this
2389 // we make sure the process has our debugserver process ID. If we pass all
2390 // of these tests, then we are sure that this process is the one we were
2391 // looking for.
2392 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002393 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002394 // Sleep for a half a second to make sure our inferior process has
2395 // time to set its exit status before we set it incorrectly when
2396 // both the debugserver and the inferior process shut down.
2397 usleep (500000);
2398 // If our process hasn't yet exited, debugserver might have died.
2399 // If the process did exit, the we are reaping it.
2400 const StateType state = process->GetState();
2401
2402 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2403 state != eStateInvalid &&
2404 state != eStateUnloaded &&
2405 state != eStateExited &&
2406 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002407 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002408 char error_str[1024];
2409 if (signo)
2410 {
2411 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2412 if (signal_cstr)
2413 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2414 else
2415 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2416 }
Chris Lattner24943d22010-06-08 16:52:24 +00002417 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002418 {
2419 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2420 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002421
Greg Clayton1c4642c2011-11-16 05:37:56 +00002422 process->SetExitStatus (-1, error_str);
2423 }
2424 // Debugserver has exited we need to let our ProcessGDBRemote
2425 // know that it no longer has a debugserver instance
2426 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002427 }
Chris Lattner24943d22010-06-08 16:52:24 +00002428 }
2429 return true;
2430}
2431
2432void
2433ProcessGDBRemote::KillDebugserverProcess ()
2434{
2435 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2436 {
2437 ::kill (m_debugserver_pid, SIGINT);
2438 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2439 }
2440}
2441
2442void
2443ProcessGDBRemote::Initialize()
2444{
2445 static bool g_initialized = false;
2446
2447 if (g_initialized == false)
2448 {
2449 g_initialized = true;
2450 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2451 GetPluginDescriptionStatic(),
2452 CreateInstance);
2453
2454 Log::Callbacks log_callbacks = {
2455 ProcessGDBRemoteLog::DisableLog,
2456 ProcessGDBRemoteLog::EnableLog,
2457 ProcessGDBRemoteLog::ListLogCategories
2458 };
2459
2460 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2461 }
2462}
2463
2464bool
Chris Lattner24943d22010-06-08 16:52:24 +00002465ProcessGDBRemote::StartAsyncThread ()
2466{
Greg Claytone005f2c2010-11-06 01:53:30 +00002467 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002468
2469 if (log)
2470 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2471
2472 // Create a thread that watches our internal state and controls which
2473 // events make it to clients (into the DCProcess event queue).
2474 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002475 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002476}
2477
2478void
2479ProcessGDBRemote::StopAsyncThread ()
2480{
Greg Claytone005f2c2010-11-06 01:53:30 +00002481 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002482
2483 if (log)
2484 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2485
2486 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002487
2488 // This will shut down the async thread.
2489 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002490
2491 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002492 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002493 {
2494 Host::ThreadJoin (m_async_thread, NULL, NULL);
2495 }
2496}
2497
2498
2499void *
2500ProcessGDBRemote::AsyncThread (void *arg)
2501{
2502 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2503
Greg Claytone005f2c2010-11-06 01:53:30 +00002504 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002505 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002506 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002507
2508 Listener listener ("ProcessGDBRemote::AsyncThread");
2509 EventSP event_sp;
2510 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2511 eBroadcastBitAsyncThreadShouldExit;
2512
2513 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2514 {
Greg Claytona2f74232011-02-24 22:24:29 +00002515 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2516
Chris Lattner24943d22010-06-08 16:52:24 +00002517 bool done = false;
2518 while (!done)
2519 {
2520 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002521 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002522 if (listener.WaitForEvent (NULL, event_sp))
2523 {
2524 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002525 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002526 {
Greg Claytona2f74232011-02-24 22:24:29 +00002527 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002528 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 +00002529
Greg Claytona2f74232011-02-24 22:24:29 +00002530 switch (event_type)
2531 {
2532 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002533 {
Greg Claytona2f74232011-02-24 22:24:29 +00002534 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002535
Greg Claytona2f74232011-02-24 22:24:29 +00002536 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002537 {
Greg Claytona2f74232011-02-24 22:24:29 +00002538 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2539 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2540 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002541 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002542
Greg Claytona2f74232011-02-24 22:24:29 +00002543 if (::strstr (continue_cstr, "vAttach") == NULL)
2544 process->SetPrivateState(eStateRunning);
2545 StringExtractorGDBRemote response;
2546 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002547
Greg Clayton67b402c2012-05-16 02:48:06 +00002548 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2549 // The thread ID list might be contained within the "response", or the stop reply packet that
2550 // caused the stop. So clear it now before we give the stop reply packet to the process
2551 // using the process->SetLastStopPacket()...
2552 process->ClearThreadIDList ();
2553
Greg Claytona2f74232011-02-24 22:24:29 +00002554 switch (stop_state)
2555 {
2556 case eStateStopped:
2557 case eStateCrashed:
2558 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002559 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002560 process->SetPrivateState (stop_state);
2561 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002562
Greg Claytona2f74232011-02-24 22:24:29 +00002563 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002564 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002565 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002566 response.SetFilePos(1);
2567 process->SetExitStatus(response.GetHexU8(), NULL);
2568 done = true;
2569 break;
2570
2571 case eStateInvalid:
2572 process->SetExitStatus(-1, "lost connection");
2573 break;
2574
2575 default:
2576 process->SetPrivateState (stop_state);
2577 break;
2578 }
Chris Lattner24943d22010-06-08 16:52:24 +00002579 }
2580 }
Greg Claytona2f74232011-02-24 22:24:29 +00002581 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002582
Greg Claytona2f74232011-02-24 22:24:29 +00002583 case eBroadcastBitAsyncThreadShouldExit:
2584 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002585 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002586 done = true;
2587 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002588
Greg Claytona2f74232011-02-24 22:24:29 +00002589 default:
2590 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002591 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 +00002592 done = true;
2593 break;
2594 }
2595 }
2596 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2597 {
2598 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2599 {
2600 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002601 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002602 }
Chris Lattner24943d22010-06-08 16:52:24 +00002603 }
2604 }
2605 else
2606 {
2607 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002608 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 +00002609 done = true;
2610 }
2611 }
2612 }
2613
2614 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002615 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002616
2617 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2618 return NULL;
2619}
2620
Chris Lattner24943d22010-06-08 16:52:24 +00002621const char *
2622ProcessGDBRemote::GetDispatchQueueNameForThread
2623(
2624 addr_t thread_dispatch_qaddr,
2625 std::string &dispatch_queue_name
2626)
2627{
2628 dispatch_queue_name.clear();
2629 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2630 {
2631 // Cache the dispatch_queue_offsets_addr value so we don't always have
2632 // to look it up
2633 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2634 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002635 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2636 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002637 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2638 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002639 if (module_sp)
2640 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2641
2642 if (dispatch_queue_offsets_symbol == NULL)
2643 {
Greg Clayton444fe992012-02-26 05:51:37 +00002644 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2645 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002646 if (module_sp)
2647 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2648 }
Chris Lattner24943d22010-06-08 16:52:24 +00002649 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002650 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002651
2652 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2653 return NULL;
2654 }
2655
2656 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002657 DataExtractor data (memory_buffer,
2658 sizeof(memory_buffer),
2659 m_target.GetArchitecture().GetByteOrder(),
2660 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002661
2662 // Excerpt from src/queue_private.h
2663 struct dispatch_queue_offsets_s
2664 {
2665 uint16_t dqo_version;
2666 uint16_t dqo_label;
2667 uint16_t dqo_label_size;
2668 } dispatch_queue_offsets;
2669
2670
2671 Error error;
2672 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2673 {
2674 uint32_t data_offset = 0;
2675 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2676 {
2677 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2678 {
2679 data_offset = 0;
2680 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2681 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2682 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2683 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2684 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2685 dispatch_queue_name.erase (bytes_read);
2686 }
2687 }
2688 }
2689 }
2690 if (dispatch_queue_name.empty())
2691 return NULL;
2692 return dispatch_queue_name.c_str();
2693}
2694
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002695//uint32_t
2696//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2697//{
2698// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2699// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2700// if (m_local_debugserver)
2701// {
2702// return Host::ListProcessesMatchingName (name, matches, pids);
2703// }
2704// else
2705// {
2706// // FIXME: Implement talking to the remote debugserver.
2707// return 0;
2708// }
2709//
2710//}
2711//
Jim Ingham55e01d82011-01-22 01:33:44 +00002712bool
2713ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2714 lldb_private::StoppointCallbackContext *context,
2715 lldb::user_id_t break_id,
2716 lldb::user_id_t break_loc_id)
2717{
2718 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2719 // run so I can stop it if that's what I want to do.
2720 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2721 if (log)
2722 log->Printf("Hit New Thread Notification breakpoint.");
2723 return false;
2724}
2725
2726
2727bool
2728ProcessGDBRemote::StartNoticingNewThreads()
2729{
Jim Ingham55e01d82011-01-22 01:33:44 +00002730 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002731 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002732 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002733 if (log && log->GetVerbose())
2734 log->Printf("Enabled noticing new thread breakpoint.");
2735 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002736 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002737 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002738 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002739 PlatformSP platform_sp (m_target.GetPlatform());
2740 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002741 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002742 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2743 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002744 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002745 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002746 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2747 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002748 }
2749 else
2750 {
2751 if (log)
2752 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002753 }
2754 }
2755 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002756 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002757}
2758
2759bool
2760ProcessGDBRemote::StopNoticingNewThreads()
2761{
Jim Inghamff276fe2011-02-08 05:19:01 +00002762 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002763 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002764 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002765
2766 if (m_thread_create_bp_sp)
2767 m_thread_create_bp_sp->SetEnabled(false);
2768
Jim Ingham55e01d82011-01-22 01:33:44 +00002769 return true;
2770}
2771
2772