blob: be5ccab7b903d4a033a9f3fb1f00c681b502bd64 [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');
Chris Lattner24943d22010-06-08 16:52:24 +0000732 return error;
733}
734
735void
736ProcessGDBRemote::DidLaunchOrAttach ()
737{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000738 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
739 if (log)
740 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000741 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000742 {
743 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
744
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000745 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000746
Chris Lattner24943d22010-06-08 16:52:24 +0000747 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000748
Greg Claytoncb8977d2011-03-23 00:09:55 +0000749 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
750 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000751 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000752 ArchSpec &target_arch = GetTarget().GetArchitecture();
753
754 if (target_arch.IsValid())
755 {
756 // If the remote host is ARM and we have apple as the vendor, then
757 // ARM executables and shared libraries can have mixed ARM architectures.
758 // You can have an armv6 executable, and if the host is armv7, then the
759 // system will load the best possible architecture for all shared libraries
760 // it has, so we really need to take the remote host architecture as our
761 // defacto architecture in this case.
762
763 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
764 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
765 {
766 target_arch = gdb_remote_arch;
767 }
768 else
769 {
770 // Fill in what is missing in the triple
771 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
772 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000773 if (target_triple.getVendorName().size() == 0)
774 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000775 target_triple.setVendor (remote_triple.getVendor());
776
Greg Clayton2f085c62011-05-15 01:25:55 +0000777 if (target_triple.getOSName().size() == 0)
778 {
779 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000780
Greg Clayton2f085c62011-05-15 01:25:55 +0000781 if (target_triple.getEnvironmentName().size() == 0)
782 target_triple.setEnvironment (remote_triple.getEnvironment());
783 }
784 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000785 }
786 }
787 else
788 {
789 // The target doesn't have a valid architecture yet, set it from
790 // the architecture we got from the remote GDB server
791 target_arch = gdb_remote_arch;
792 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000793 }
Chris Lattner24943d22010-06-08 16:52:24 +0000794 }
795}
796
797void
798ProcessGDBRemote::DidLaunch ()
799{
800 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000801}
802
803Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000804ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000805{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000806 ProcessAttachInfo attach_info;
807 return DoAttachToProcessWithID(attach_pid, attach_info);
808}
809
810Error
811ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
812{
Chris Lattner24943d22010-06-08 16:52:24 +0000813 Error error;
814 // Clear out and clean up from any current state
815 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000816 if (attach_pid != LLDB_INVALID_PROCESS_ID)
817 {
Greg Claytona2f74232011-02-24 22:24:29 +0000818 // Make sure we aren't already connected?
819 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000820 {
Greg Claytona2f74232011-02-24 22:24:29 +0000821 char host_port[128];
822 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
823 char connect_url[128];
824 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000825
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000826 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000827
828 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000829 {
Greg Claytona2f74232011-02-24 22:24:29 +0000830 const char *error_string = error.AsCString();
831 if (error_string == NULL)
832 error_string = "unable to launch " DEBUGSERVER_BASENAME;
833
834 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000835 }
Greg Claytona2f74232011-02-24 22:24:29 +0000836 else
837 {
838 error = ConnectToDebugserver (connect_url);
839 }
840 }
841
842 if (error.Success())
843 {
844 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000845 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000846 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000847 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000848 }
849 }
Chris Lattner24943d22010-06-08 16:52:24 +0000850 return error;
851}
852
853size_t
854ProcessGDBRemote::AttachInputReaderCallback
855(
856 void *baton,
857 InputReader *reader,
858 lldb::InputReaderAction notification,
859 const char *bytes,
860 size_t bytes_len
861)
862{
863 if (notification == eInputReaderGotToken)
864 {
865 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
866 if (gdb_process->m_waiting_for_attach)
867 gdb_process->m_waiting_for_attach = false;
868 reader->SetIsDone(true);
869 return 1;
870 }
871 return 0;
872}
873
874Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000875ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000876{
877 Error error;
878 // Clear out and clean up from any current state
879 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000880
Chris Lattner24943d22010-06-08 16:52:24 +0000881 if (process_name && process_name[0])
882 {
Greg Claytona2f74232011-02-24 22:24:29 +0000883 // Make sure we aren't already connected?
884 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000885 {
Greg Claytona2f74232011-02-24 22:24:29 +0000886 char host_port[128];
887 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
888 char connect_url[128];
889 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
890
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000891 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000892 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000893 {
Greg Claytona2f74232011-02-24 22:24:29 +0000894 const char *error_string = error.AsCString();
895 if (error_string == NULL)
896 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000897
Greg Claytona2f74232011-02-24 22:24:29 +0000898 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000899 }
Greg Claytona2f74232011-02-24 22:24:29 +0000900 else
901 {
902 error = ConnectToDebugserver (connect_url);
903 }
904 }
905
906 if (error.Success())
907 {
908 StreamString packet;
909
910 if (wait_for_launch)
911 packet.PutCString("vAttachWait");
912 else
913 packet.PutCString("vAttachName");
914 packet.PutChar(';');
915 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
916
917 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
918
Chris Lattner24943d22010-06-08 16:52:24 +0000919 }
920 }
Chris Lattner24943d22010-06-08 16:52:24 +0000921 return error;
922}
923
Chris Lattner24943d22010-06-08 16:52:24 +0000924
925void
926ProcessGDBRemote::DidAttach ()
927{
Greg Claytone71e2582011-02-04 01:58:07 +0000928 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000929}
930
931Error
932ProcessGDBRemote::WillResume ()
933{
Greg Claytonc1f45872011-02-12 06:28:37 +0000934 m_continue_c_tids.clear();
935 m_continue_C_tids.clear();
936 m_continue_s_tids.clear();
937 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000938 return Error();
939}
940
941Error
942ProcessGDBRemote::DoResume ()
943{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000944 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000945 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
946 if (log)
947 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000948
949 Listener listener ("gdb-remote.resume-packet-sent");
950 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
951 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000952 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
953
Greg Claytonc1f45872011-02-12 06:28:37 +0000954 StreamString continue_packet;
955 bool continue_packet_error = false;
956 if (m_gdb_comm.HasAnyVContSupport ())
957 {
958 continue_packet.PutCString ("vCont");
959
960 if (!m_continue_c_tids.empty())
961 {
962 if (m_gdb_comm.GetVContSupported ('c'))
963 {
964 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 +0000965 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000966 }
967 else
968 continue_packet_error = true;
969 }
970
971 if (!continue_packet_error && !m_continue_C_tids.empty())
972 {
973 if (m_gdb_comm.GetVContSupported ('C'))
974 {
975 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 +0000976 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000977 }
978 else
979 continue_packet_error = true;
980 }
Greg Claytonb749a262010-12-03 06:02:24 +0000981
Greg Claytonc1f45872011-02-12 06:28:37 +0000982 if (!continue_packet_error && !m_continue_s_tids.empty())
983 {
984 if (m_gdb_comm.GetVContSupported ('s'))
985 {
986 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 +0000987 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000988 }
989 else
990 continue_packet_error = true;
991 }
992
993 if (!continue_packet_error && !m_continue_S_tids.empty())
994 {
995 if (m_gdb_comm.GetVContSupported ('S'))
996 {
997 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 +0000998 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000999 }
1000 else
1001 continue_packet_error = true;
1002 }
1003
1004 if (continue_packet_error)
1005 continue_packet.GetString().clear();
1006 }
1007 else
1008 continue_packet_error = true;
1009
1010 if (continue_packet_error)
1011 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001012 // Either no vCont support, or we tried to use part of the vCont
1013 // packet that wasn't supported by the remote GDB server.
1014 // We need to try and make a simple packet that can do our continue
1015 const size_t num_threads = GetThreadList().GetSize();
1016 const size_t num_continue_c_tids = m_continue_c_tids.size();
1017 const size_t num_continue_C_tids = m_continue_C_tids.size();
1018 const size_t num_continue_s_tids = m_continue_s_tids.size();
1019 const size_t num_continue_S_tids = m_continue_S_tids.size();
1020 if (num_continue_c_tids > 0)
1021 {
1022 if (num_continue_c_tids == num_threads)
1023 {
1024 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001025 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001026 continue_packet.PutChar ('c');
1027 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001028 }
1029 else if (num_continue_c_tids == 1 &&
1030 num_continue_C_tids == 0 &&
1031 num_continue_s_tids == 0 &&
1032 num_continue_S_tids == 0 )
1033 {
1034 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001035 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001036 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001037 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001038 }
1039 }
1040
Greg Claytonde1dd812011-06-24 03:21:43 +00001041 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001042 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001043 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1044 num_continue_C_tids > 0 &&
1045 num_continue_s_tids == 0 &&
1046 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001047 {
1048 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001049 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001050 if (num_continue_C_tids > 1)
1051 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001052 // More that one thread with a signal, yet we don't have
1053 // vCont support and we are being asked to resume each
1054 // thread with a signal, we need to make sure they are
1055 // all the same signal, or we can't issue the continue
1056 // accurately with the current support...
1057 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001058 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001059 continue_packet_error = false;
1060 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1061 {
1062 if (m_continue_C_tids[i].second != continue_signo)
1063 continue_packet_error = true;
1064 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001065 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001066 if (!continue_packet_error)
1067 m_gdb_comm.SetCurrentThreadForRun (-1);
1068 }
1069 else
1070 {
1071 // Set the continue thread ID
1072 continue_packet_error = false;
1073 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001074 }
1075 if (!continue_packet_error)
1076 {
1077 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001078 continue_packet.Printf("C%2.2x", continue_signo);
1079 }
1080 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001081 }
1082
Greg Claytonde1dd812011-06-24 03:21:43 +00001083 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001084 {
1085 if (num_continue_s_tids == num_threads)
1086 {
1087 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001088 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001089 continue_packet.PutChar ('s');
1090 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001091 }
1092 else if (num_continue_c_tids == 0 &&
1093 num_continue_C_tids == 0 &&
1094 num_continue_s_tids == 1 &&
1095 num_continue_S_tids == 0 )
1096 {
1097 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001098 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001099 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001100 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001101 }
1102 }
1103
1104 if (!continue_packet_error && num_continue_S_tids > 0)
1105 {
1106 if (num_continue_S_tids == num_threads)
1107 {
1108 const int step_signo = m_continue_S_tids.front().second;
1109 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001110 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001111 if (num_continue_S_tids > 1)
1112 {
1113 for (size_t i=1; i<num_threads; ++i)
1114 {
1115 if (m_continue_S_tids[i].second != step_signo)
1116 continue_packet_error = true;
1117 }
1118 }
1119 if (!continue_packet_error)
1120 {
1121 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001122 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001123 continue_packet.Printf("S%2.2x", step_signo);
1124 }
1125 }
1126 else if (num_continue_c_tids == 0 &&
1127 num_continue_C_tids == 0 &&
1128 num_continue_s_tids == 0 &&
1129 num_continue_S_tids == 1 )
1130 {
1131 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001132 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001133 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001134 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001135 }
1136 }
1137 }
1138
1139 if (continue_packet_error)
1140 {
1141 error.SetErrorString ("can't make continue packet for this resume");
1142 }
1143 else
1144 {
1145 EventSP event_sp;
1146 TimeValue timeout;
1147 timeout = TimeValue::Now();
1148 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001149 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1150 {
1151 error.SetErrorString ("Trying to resume but the async thread is dead.");
1152 if (log)
1153 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1154 return error;
1155 }
1156
Greg Claytonc1f45872011-02-12 06:28:37 +00001157 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1158
1159 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001160 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001161 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001162 if (log)
1163 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1164 }
1165 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1166 {
1167 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1168 if (log)
1169 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1170 return error;
1171 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001172 }
Greg Claytonb749a262010-12-03 06:02:24 +00001173 }
1174
Jim Ingham3ae449a2010-11-17 02:32:00 +00001175 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001176}
1177
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001178void
1179ProcessGDBRemote::ClearThreadIDList ()
1180{
Greg Claytonff3448e2012-04-13 02:11:32 +00001181 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001182 m_thread_ids.clear();
1183}
1184
1185bool
1186ProcessGDBRemote::UpdateThreadIDList ()
1187{
Greg Claytonff3448e2012-04-13 02:11:32 +00001188 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001189 bool sequence_mutex_unavailable = false;
1190 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1191 if (sequence_mutex_unavailable)
1192 {
1193#if defined (LLDB_CONFIGURATION_DEBUG)
1194 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1195#endif
1196 return false; // We just didn't get the list
1197 }
1198 return true;
1199}
1200
Greg Claytonae932352012-04-10 00:18:59 +00001201bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001202ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001203{
1204 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001205 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001206 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001207 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001208
1209 size_t num_thread_ids = m_thread_ids.size();
1210 // The "m_thread_ids" thread ID list should always be updated after each stop
1211 // reply packet, but in case it isn't, update it here.
1212 if (num_thread_ids == 0)
1213 {
1214 if (!UpdateThreadIDList ())
1215 return false;
1216 num_thread_ids = m_thread_ids.size();
1217 }
Chris Lattner24943d22010-06-08 16:52:24 +00001218
Greg Clayton37f962e2011-08-22 02:49:39 +00001219 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001220 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001221 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001222 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001223 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001224 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1225 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001226 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001227 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001228 }
Chris Lattner24943d22010-06-08 16:52:24 +00001229 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001230
Greg Claytonae932352012-04-10 00:18:59 +00001231 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001232}
1233
1234
1235StateType
1236ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1237{
Greg Clayton261a18b2011-06-02 22:22:38 +00001238 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001239 const char stop_type = stop_packet.GetChar();
1240 switch (stop_type)
1241 {
1242 case 'T':
1243 case 'S':
1244 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001245 if (GetStopID() == 0)
1246 {
1247 // Our first stop, make sure we have a process ID, and also make
1248 // sure we know about our registers
1249 if (GetID() == LLDB_INVALID_PROCESS_ID)
1250 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001251 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001252 if (pid != LLDB_INVALID_PROCESS_ID)
1253 SetID (pid);
1254 }
1255 BuildDynamicRegisterInfo (true);
1256 }
Chris Lattner24943d22010-06-08 16:52:24 +00001257 // Stop with signal and thread info
1258 const uint8_t signo = stop_packet.GetHexU8();
1259 std::string name;
1260 std::string value;
1261 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001262 std::string reason;
1263 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001264 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001265 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001266 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1267 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001268 ThreadSP thread_sp;
1269
Chris Lattner24943d22010-06-08 16:52:24 +00001270 while (stop_packet.GetNameColonValue(name, value))
1271 {
1272 if (name.compare("metype") == 0)
1273 {
1274 // exception type in big endian hex
1275 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1276 }
1277 else if (name.compare("mecount") == 0)
1278 {
1279 // exception count in big endian hex
1280 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1281 }
1282 else if (name.compare("medata") == 0)
1283 {
1284 // exception data in big endian hex
1285 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1286 }
1287 else if (name.compare("thread") == 0)
1288 {
1289 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001290 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001291 // m_thread_list does have its own mutex, but we need to
1292 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1293 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001294 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001295 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001296 if (!thread_sp)
1297 {
1298 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001299 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001300 m_thread_list.AddThread(thread_sp);
1301 }
Chris Lattner24943d22010-06-08 16:52:24 +00001302 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001303 else if (name.compare("threads") == 0)
1304 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001305 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001306 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001307 // A comma separated list of all threads in the current
1308 // process that includes the thread for this stop reply
1309 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001310 size_t comma_pos;
1311 lldb::tid_t tid;
1312 while ((comma_pos = value.find(',')) != std::string::npos)
1313 {
1314 value[comma_pos] = '\0';
1315 // thread in big endian hex
1316 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1317 if (tid != LLDB_INVALID_THREAD_ID)
1318 m_thread_ids.push_back (tid);
1319 value.erase(0, comma_pos + 1);
1320
1321 }
1322 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1323 if (tid != LLDB_INVALID_THREAD_ID)
1324 m_thread_ids.push_back (tid);
1325 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001326 else if (name.compare("hexname") == 0)
1327 {
1328 StringExtractor name_extractor;
1329 // Swap "value" over into "name_extractor"
1330 name_extractor.GetStringRef().swap(value);
1331 // Now convert the HEX bytes into a string value
1332 name_extractor.GetHexByteString (value);
1333 thread_name.swap (value);
1334 }
Chris Lattner24943d22010-06-08 16:52:24 +00001335 else if (name.compare("name") == 0)
1336 {
1337 thread_name.swap (value);
1338 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001339 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001340 {
1341 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1342 }
Greg Clayton65611552011-06-04 01:26:29 +00001343 else if (name.compare("reason") == 0)
1344 {
1345 reason.swap(value);
1346 }
1347 else if (name.compare("description") == 0)
1348 {
1349 StringExtractor desc_extractor;
1350 // Swap "value" over into "name_extractor"
1351 desc_extractor.GetStringRef().swap(value);
1352 // Now convert the HEX bytes into a string value
1353 desc_extractor.GetHexByteString (thread_name);
1354 }
Greg Claytona875b642011-01-09 21:07:35 +00001355 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1356 {
1357 // We have a register number that contains an expedited
1358 // register value. Lets supply this register to our thread
1359 // so it won't have to go and read it.
1360 if (thread_sp)
1361 {
1362 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1363
1364 if (reg != UINT32_MAX)
1365 {
1366 StringExtractor reg_value_extractor;
1367 // Swap "value" over into "reg_value_extractor"
1368 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001369 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1370 {
1371 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1372 name.c_str(),
1373 reg,
1374 reg,
1375 reg_value_extractor.GetStringRef().c_str(),
1376 stop_packet.GetStringRef().c_str());
1377 }
Greg Claytona875b642011-01-09 21:07:35 +00001378 }
1379 }
1380 }
Chris Lattner24943d22010-06-08 16:52:24 +00001381 }
Chris Lattner24943d22010-06-08 16:52:24 +00001382
1383 if (thread_sp)
1384 {
1385 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1386
1387 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001388 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001389 if (exc_type != 0)
1390 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001391 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001392
1393 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1394 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001395 exc_data_size,
1396 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001397 exc_data_size >= 2 ? exc_data[1] : 0,
1398 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001399 }
Greg Clayton65611552011-06-04 01:26:29 +00001400 else
Chris Lattner24943d22010-06-08 16:52:24 +00001401 {
Greg Clayton65611552011-06-04 01:26:29 +00001402 bool handled = false;
1403 if (!reason.empty())
1404 {
1405 if (reason.compare("trace") == 0)
1406 {
1407 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1408 handled = true;
1409 }
1410 else if (reason.compare("breakpoint") == 0)
1411 {
1412 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001413 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001414 if (bp_site_sp)
1415 {
1416 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1417 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1418 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1419 if (bp_site_sp->ValidForThisThread (gdb_thread))
1420 {
1421 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1422 handled = true;
1423 }
1424 }
1425
1426 if (!handled)
1427 {
1428 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1429 }
1430 }
1431 else if (reason.compare("trap") == 0)
1432 {
1433 // Let the trap just use the standard signal stop reason below...
1434 }
1435 else if (reason.compare("watchpoint") == 0)
1436 {
1437 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1438 // TODO: locate the watchpoint somehow...
1439 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1440 handled = true;
1441 }
1442 else if (reason.compare("exception") == 0)
1443 {
1444 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1445 handled = true;
1446 }
1447 }
1448
1449 if (signo)
1450 {
1451 if (signo == SIGTRAP)
1452 {
1453 // Currently we are going to assume SIGTRAP means we are either
1454 // hitting a breakpoint or hardware single stepping.
1455 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001456 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001457 if (bp_site_sp)
1458 {
1459 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1460 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1461 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1462 if (bp_site_sp->ValidForThisThread (gdb_thread))
1463 {
1464 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1465 handled = true;
1466 }
1467 }
1468 if (!handled)
1469 {
1470 // TODO: check for breakpoint or trap opcode in case there is a hard
1471 // coded software trap
1472 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1473 handled = true;
1474 }
1475 }
1476 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001477 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001478 }
1479 else
1480 {
Greg Clayton643ee732010-08-04 01:40:35 +00001481 StopInfoSP invalid_stop_info_sp;
1482 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001483 }
Greg Clayton65611552011-06-04 01:26:29 +00001484
1485 if (!description.empty())
1486 {
1487 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1488 if (stop_info_sp)
1489 {
1490 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001491 }
Greg Clayton65611552011-06-04 01:26:29 +00001492 else
1493 {
1494 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1495 }
1496 }
1497 }
Chris Lattner24943d22010-06-08 16:52:24 +00001498 }
1499 return eStateStopped;
1500 }
1501 break;
1502
1503 case 'W':
1504 // process exited
1505 return eStateExited;
1506
1507 default:
1508 break;
1509 }
1510 return eStateInvalid;
1511}
1512
1513void
1514ProcessGDBRemote::RefreshStateAfterStop ()
1515{
Greg Claytonff3448e2012-04-13 02:11:32 +00001516 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001517 m_thread_ids.clear();
1518 // Set the thread stop info. It might have a "threads" key whose value is
1519 // a list of all thread IDs in the current process, so m_thread_ids might
1520 // get set.
1521 SetThreadStopInfo (m_last_stop_packet);
1522 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1523 if (m_thread_ids.empty())
1524 {
1525 // No, we need to fetch the thread list manually
1526 UpdateThreadIDList();
1527 }
1528
Chris Lattner24943d22010-06-08 16:52:24 +00001529 // Let all threads recover from stopping and do any clean up based
1530 // on the previous thread state (if any).
1531 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001532
Chris Lattner24943d22010-06-08 16:52:24 +00001533}
1534
1535Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001536ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001537{
1538 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001539
Greg Claytona4881d02011-01-22 07:12:45 +00001540 bool timed_out = false;
1541 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001542
1543 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001544 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001545 // We are being asked to halt during an attach. We need to just close
1546 // our file handle and debugserver will go away, and we can be done...
1547 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001548 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001549 else
1550 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001551 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001552 {
1553 if (timed_out)
1554 error.SetErrorString("timed out sending interrupt packet");
1555 else
1556 error.SetErrorString("unknown error sending interrupt packet");
1557 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001558
1559 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001560 }
Chris Lattner24943d22010-06-08 16:52:24 +00001561 return error;
1562}
1563
1564Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001565ProcessGDBRemote::InterruptIfRunning
1566(
1567 bool discard_thread_plans,
1568 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001569 EventSP &stop_event_sp
1570)
Chris Lattner24943d22010-06-08 16:52:24 +00001571{
1572 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001573
Greg Clayton2860ba92011-01-23 19:58:49 +00001574 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1575
Greg Clayton68ca8232011-01-25 02:58:48 +00001576 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001577 const bool is_running = m_gdb_comm.IsRunning();
1578 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001579 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001580 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001581 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001582 is_running);
1583
Greg Clayton2860ba92011-01-23 19:58:49 +00001584 if (discard_thread_plans)
1585 {
1586 if (log)
1587 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1588 m_thread_list.DiscardThreadPlans();
1589 }
1590 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001591 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001592 if (catch_stop_event)
1593 {
1594 if (log)
1595 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1596 PausePrivateStateThread();
1597 paused_private_state_thread = true;
1598 }
1599
Greg Clayton4fb400f2010-09-27 21:07:38 +00001600 bool timed_out = false;
1601 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001602
Greg Clayton05e4d972012-03-29 01:55:41 +00001603 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001604 {
1605 if (timed_out)
1606 error.SetErrorString("timed out sending interrupt packet");
1607 else
1608 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001609 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001610 ResumePrivateStateThread();
1611 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001612 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001613
Greg Clayton72e1c782011-01-22 23:43:18 +00001614 if (catch_stop_event)
1615 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001616 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001617 TimeValue timeout_time;
1618 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001619 timeout_time.OffsetWithSeconds(5);
1620 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001621
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001622 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001623 if (log)
1624 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001625
Greg Clayton2860ba92011-01-23 19:58:49 +00001626 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001627 error.SetErrorString("unable to verify target stopped");
1628 }
1629
Greg Clayton68ca8232011-01-25 02:58:48 +00001630 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001631 {
1632 if (log)
1633 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001634 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001635 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001636 }
Chris Lattner24943d22010-06-08 16:52:24 +00001637 return error;
1638}
1639
Greg Clayton4fb400f2010-09-27 21:07:38 +00001640Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001641ProcessGDBRemote::WillDetach ()
1642{
Greg Clayton2860ba92011-01-23 19:58:49 +00001643 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1644 if (log)
1645 log->Printf ("ProcessGDBRemote::WillDetach()");
1646
Greg Clayton72e1c782011-01-22 23:43:18 +00001647 bool discard_thread_plans = true;
1648 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001649 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001650
1651 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1652 // needed. This shouldn't be a feature of a particular plugin.
1653
Greg Clayton68ca8232011-01-25 02:58:48 +00001654 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001655}
1656
1657Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001658ProcessGDBRemote::DoDetach()
1659{
1660 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001661 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001662 if (log)
1663 log->Printf ("ProcessGDBRemote::DoDetach()");
1664
1665 DisableAllBreakpointSites ();
1666
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001667 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001668
Greg Clayton516f0842012-04-11 00:24:49 +00001669 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001670 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001671 {
Greg Clayton516f0842012-04-11 00:24:49 +00001672 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001673 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1674 else
1675 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001676 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001677 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001678 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001679
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001680 SetPrivateState (eStateDetached);
1681 ResumePrivateStateThread();
1682
1683 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001684 return error;
1685}
Chris Lattner24943d22010-06-08 16:52:24 +00001686
1687Error
1688ProcessGDBRemote::DoDestroy ()
1689{
1690 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001691 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001692 if (log)
1693 log->Printf ("ProcessGDBRemote::DoDestroy()");
1694
1695 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001696 int exit_status = SIGABRT;
1697 std::string exit_string;
1698
Greg Claytona4881d02011-01-22 07:12:45 +00001699 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001700 {
Jim Ingham8226e942011-10-28 01:11:35 +00001701 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001702 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001703
1704 StringExtractorGDBRemote response;
1705 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001706 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001707 {
1708 char packet_cmd = response.GetChar(0);
1709
1710 if (packet_cmd == 'W' || packet_cmd == 'X')
1711 {
Greg Clayton06709002011-12-06 04:51:14 +00001712 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001713 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001714 exit_status = response.GetHexU8();
1715 }
1716 else
1717 {
1718 if (log)
1719 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1720 exit_string.assign("got unexpected response to k packet: ");
1721 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001722 }
1723 }
1724 else
1725 {
Jim Ingham8247e622012-06-06 00:32:39 +00001726 if (log)
1727 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1728 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001729 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001730 }
Jim Ingham8247e622012-06-06 00:32:39 +00001731 else
1732 {
1733 if (log)
1734 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1735 exit_string.assign ("killing while attaching.");
1736 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001737 }
Jim Ingham8247e622012-06-06 00:32:39 +00001738 else
1739 {
1740 // If we missed setting the exit status on the way out, do it here.
1741 // NB set exit status can be called multiple times, the first one sets the status.
1742 exit_string.assign("destroying when not connected to debugserver");
1743 }
1744
1745 SetExitStatus(exit_status, exit_string.c_str());
1746
Chris Lattner24943d22010-06-08 16:52:24 +00001747 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001748 KillDebugserverProcess ();
1749 return error;
1750}
1751
Chris Lattner24943d22010-06-08 16:52:24 +00001752//------------------------------------------------------------------
1753// Process Queries
1754//------------------------------------------------------------------
1755
1756bool
1757ProcessGDBRemote::IsAlive ()
1758{
Greg Clayton58e844b2010-12-08 05:08:21 +00001759 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001760}
1761
1762addr_t
1763ProcessGDBRemote::GetImageInfoAddress()
1764{
Greg Clayton516f0842012-04-11 00:24:49 +00001765 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001766}
1767
Chris Lattner24943d22010-06-08 16:52:24 +00001768//------------------------------------------------------------------
1769// Process Memory
1770//------------------------------------------------------------------
1771size_t
1772ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1773{
1774 if (size > m_max_memory_size)
1775 {
1776 // Keep memory read sizes down to a sane limit. This function will be
1777 // called multiple times in order to complete the task by
1778 // lldb_private::Process so it is ok to do this.
1779 size = m_max_memory_size;
1780 }
1781
1782 char packet[64];
1783 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1784 assert (packet_len + 1 < sizeof(packet));
1785 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001786 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001787 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001788 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001789 {
1790 error.Clear();
1791 return response.GetHexBytes(buf, size, '\xdd');
1792 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001793 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001794 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001795 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001796 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1797 else
1798 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1799 }
1800 else
1801 {
1802 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1803 }
1804 return 0;
1805}
1806
1807size_t
1808ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1809{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001810 if (size > m_max_memory_size)
1811 {
1812 // Keep memory read sizes down to a sane limit. This function will be
1813 // called multiple times in order to complete the task by
1814 // lldb_private::Process so it is ok to do this.
1815 size = m_max_memory_size;
1816 }
1817
Chris Lattner24943d22010-06-08 16:52:24 +00001818 StreamString packet;
1819 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001820 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001821 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001822 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001823 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001824 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001825 {
1826 error.Clear();
1827 return size;
1828 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001829 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001830 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001831 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001832 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1833 else
1834 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1835 }
1836 else
1837 {
1838 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1839 }
1840 return 0;
1841}
1842
1843lldb::addr_t
1844ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1845{
Greg Clayton989816b2011-05-14 01:50:35 +00001846 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1847
Greg Clayton2f085c62011-05-15 01:25:55 +00001848 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001849 switch (supported)
1850 {
1851 case eLazyBoolCalculate:
1852 case eLazyBoolYes:
1853 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1854 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1855 return allocated_addr;
1856
1857 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001858 // Call mmap() to create memory in the inferior..
1859 unsigned prot = 0;
1860 if (permissions & lldb::ePermissionsReadable)
1861 prot |= eMmapProtRead;
1862 if (permissions & lldb::ePermissionsWritable)
1863 prot |= eMmapProtWrite;
1864 if (permissions & lldb::ePermissionsExecutable)
1865 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001866
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001867 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1868 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1869 m_addr_to_mmap_size[allocated_addr] = size;
1870 else
1871 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001872 break;
1873 }
1874
Chris Lattner24943d22010-06-08 16:52:24 +00001875 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001876 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001877 else
1878 error.Clear();
1879 return allocated_addr;
1880}
1881
1882Error
Greg Claytona9385532011-11-18 07:03:08 +00001883ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1884 MemoryRegionInfo &region_info)
1885{
1886
1887 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1888 return error;
1889}
1890
1891Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00001892ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
1893{
1894
1895 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
1896 return error;
1897}
1898
1899Error
Chris Lattner24943d22010-06-08 16:52:24 +00001900ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1901{
1902 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001903 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1904
1905 switch (supported)
1906 {
1907 case eLazyBoolCalculate:
1908 // We should never be deallocating memory without allocating memory
1909 // first so we should never get eLazyBoolCalculate
1910 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1911 break;
1912
1913 case eLazyBoolYes:
1914 if (!m_gdb_comm.DeallocateMemory (addr))
1915 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1916 break;
1917
1918 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001919 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001920 {
1921 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001922 if (pos != m_addr_to_mmap_size.end() &&
1923 InferiorCallMunmap(this, addr, pos->second))
1924 m_addr_to_mmap_size.erase (pos);
1925 else
1926 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001927 }
1928 break;
1929 }
1930
Chris Lattner24943d22010-06-08 16:52:24 +00001931 return error;
1932}
1933
1934
1935//------------------------------------------------------------------
1936// Process STDIO
1937//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001938size_t
1939ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1940{
1941 if (m_stdio_communication.IsConnected())
1942 {
1943 ConnectionStatus status;
1944 m_stdio_communication.Write(src, src_len, status, NULL);
1945 }
1946 return 0;
1947}
1948
1949Error
1950ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1951{
1952 Error error;
1953 assert (bp_site != NULL);
1954
Greg Claytone005f2c2010-11-06 01:53:30 +00001955 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001956 user_id_t site_id = bp_site->GetID();
1957 const addr_t addr = bp_site->GetLoadAddress();
1958 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001959 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001960
1961 if (bp_site->IsEnabled())
1962 {
1963 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001964 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 +00001965 return error;
1966 }
1967 else
1968 {
1969 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1970
1971 if (bp_site->HardwarePreferred())
1972 {
1973 // Try and set hardware breakpoint, and if that fails, fall through
1974 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001975 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001976 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001977 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001978 {
1979 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001980 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001981 return error;
1982 }
Chris Lattner24943d22010-06-08 16:52:24 +00001983 }
1984 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001985
1986 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001987 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001988 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1989 {
1990 bp_site->SetEnabled(true);
1991 bp_site->SetType (BreakpointSite::eExternal);
1992 return error;
1993 }
Chris Lattner24943d22010-06-08 16:52:24 +00001994 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001995
1996 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001997 }
1998
1999 if (log)
2000 {
2001 const char *err_string = error.AsCString();
2002 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2003 bp_site->GetLoadAddress(),
2004 err_string ? err_string : "NULL");
2005 }
2006 // We shouldn't reach here on a successful breakpoint enable...
2007 if (error.Success())
2008 error.SetErrorToGenericError();
2009 return error;
2010}
2011
2012Error
2013ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2014{
2015 Error error;
2016 assert (bp_site != NULL);
2017 addr_t addr = bp_site->GetLoadAddress();
2018 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002019 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002020 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002021 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002022
2023 if (bp_site->IsEnabled())
2024 {
2025 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2026
Greg Claytonb72d0f02011-04-12 05:54:46 +00002027 BreakpointSite::Type bp_type = bp_site->GetType();
2028 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002029 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002030 case BreakpointSite::eSoftware:
2031 error = DisableSoftwareBreakpoint (bp_site);
2032 break;
2033
2034 case BreakpointSite::eHardware:
2035 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2036 error.SetErrorToGenericError();
2037 break;
2038
2039 case BreakpointSite::eExternal:
2040 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2041 error.SetErrorToGenericError();
2042 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002043 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002044 if (error.Success())
2045 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002046 }
2047 else
2048 {
2049 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002050 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 +00002051 return error;
2052 }
2053
2054 if (error.Success())
2055 error.SetErrorToGenericError();
2056 return error;
2057}
2058
Johnny Chen21900fb2011-09-06 22:38:36 +00002059// Pre-requisite: wp != NULL.
2060static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002061GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002062{
2063 assert(wp);
2064 bool watch_read = wp->WatchpointRead();
2065 bool watch_write = wp->WatchpointWrite();
2066
2067 // watch_read and watch_write cannot both be false.
2068 assert(watch_read || watch_write);
2069 if (watch_read && watch_write)
2070 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002071 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002072 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002073 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002074 return eWatchpointWrite;
2075}
2076
Chris Lattner24943d22010-06-08 16:52:24 +00002077Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002078ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002079{
2080 Error error;
2081 if (wp)
2082 {
2083 user_id_t watchID = wp->GetID();
2084 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002085 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002086 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002087 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002088 if (wp->IsEnabled())
2089 {
2090 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002091 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002092 return error;
2093 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002094
2095 GDBStoppointType type = GetGDBStoppointType(wp);
2096 // Pass down an appropriate z/Z packet...
2097 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002098 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002099 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2100 {
2101 wp->SetEnabled(true);
2102 return error;
2103 }
2104 else
2105 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002106 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002107 else
2108 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002109 }
2110 else
2111 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002112 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002113 }
2114 if (error.Success())
2115 error.SetErrorToGenericError();
2116 return error;
2117}
2118
2119Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002120ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002121{
2122 Error error;
2123 if (wp)
2124 {
2125 user_id_t watchID = wp->GetID();
2126
Greg Claytone005f2c2010-11-06 01:53:30 +00002127 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002128
2129 addr_t addr = wp->GetLoadAddress();
2130 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002131 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002132
Johnny Chen21900fb2011-09-06 22:38:36 +00002133 if (!wp->IsEnabled())
2134 {
2135 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002136 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002137 return error;
2138 }
2139
Chris Lattner24943d22010-06-08 16:52:24 +00002140 if (wp->IsHardware())
2141 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002142 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002143 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002144 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2145 {
2146 wp->SetEnabled(false);
2147 return error;
2148 }
2149 else
2150 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002151 }
2152 // TODO: clear software watchpoints if we implement them
2153 }
2154 else
2155 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002156 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002157 }
2158 if (error.Success())
2159 error.SetErrorToGenericError();
2160 return error;
2161}
2162
2163void
2164ProcessGDBRemote::Clear()
2165{
2166 m_flags = 0;
2167 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002168}
2169
2170Error
2171ProcessGDBRemote::DoSignal (int signo)
2172{
2173 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002174 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002175 if (log)
2176 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2177
2178 if (!m_gdb_comm.SendAsyncSignal (signo))
2179 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2180 return error;
2181}
2182
Chris Lattner24943d22010-06-08 16:52:24 +00002183Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002184ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2185{
2186 ProcessLaunchInfo launch_info;
2187 return StartDebugserverProcess(debugserver_url, launch_info);
2188}
2189
2190Error
2191ProcessGDBRemote::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 +00002192{
2193 Error error;
2194 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2195 {
2196 // If we locate debugserver, keep that located version around
2197 static FileSpec g_debugserver_file_spec;
2198
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002199 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002200 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002201 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002202
2203 // Always check to see if we have an environment override for the path
2204 // to the debugserver to use and use it if we do.
2205 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2206 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002207 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002208 else
2209 debugserver_file_spec = g_debugserver_file_spec;
2210 bool debugserver_exists = debugserver_file_spec.Exists();
2211 if (!debugserver_exists)
2212 {
2213 // The debugserver binary is in the LLDB.framework/Resources
2214 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002215 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002216 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002217 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002218 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002219 if (debugserver_exists)
2220 {
2221 g_debugserver_file_spec = debugserver_file_spec;
2222 }
2223 else
2224 {
2225 g_debugserver_file_spec.Clear();
2226 debugserver_file_spec.Clear();
2227 }
Chris Lattner24943d22010-06-08 16:52:24 +00002228 }
2229 }
2230
2231 if (debugserver_exists)
2232 {
2233 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2234
2235 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002236
Greg Claytone005f2c2010-11-06 01:53:30 +00002237 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002238
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002239 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002240 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002241
Chris Lattner24943d22010-06-08 16:52:24 +00002242 // Start args with "debugserver /file/path -r --"
2243 debugserver_args.AppendArgument(debugserver_path);
2244 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002245 // use native registers, not the GDB registers
2246 debugserver_args.AppendArgument("--native-regs");
2247 // make debugserver run in its own session so signals generated by
2248 // special terminal key sequences (^C) don't affect debugserver
2249 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002250
Chris Lattner24943d22010-06-08 16:52:24 +00002251 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2252 if (env_debugserver_log_file)
2253 {
2254 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2255 debugserver_args.AppendArgument(arg_cstr);
2256 }
2257
2258 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2259 if (env_debugserver_log_flags)
2260 {
2261 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2262 debugserver_args.AppendArgument(arg_cstr);
2263 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002264// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002265// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002266
Greg Claytonb72d0f02011-04-12 05:54:46 +00002267 // We currently send down all arguments, attach pids, or attach
2268 // process names in dedicated GDB server packets, so we don't need
2269 // to pass them as arguments. This is currently because of all the
2270 // things we need to setup prior to launching: the environment,
2271 // current working dir, file actions, etc.
2272#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002273 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002274 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002275 {
Greg Claytona2f74232011-02-24 22:24:29 +00002276 // Terminate the debugserver args so we can now append the inferior args
2277 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002278
Greg Claytona2f74232011-02-24 22:24:29 +00002279 for (int i = 0; inferior_argv[i] != NULL; ++i)
2280 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002281 }
2282 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2283 {
2284 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2285 debugserver_args.AppendArgument (arg_cstr);
2286 }
2287 else if (attach_name && attach_name[0])
2288 {
2289 if (wait_for_launch)
2290 debugserver_args.AppendArgument ("--waitfor");
2291 else
2292 debugserver_args.AppendArgument ("--attach");
2293 debugserver_args.AppendArgument (attach_name);
2294 }
Chris Lattner24943d22010-06-08 16:52:24 +00002295#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002296
2297 ProcessLaunchInfo::FileAction file_action;
2298
2299 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2300 // to "/dev/null" if we run into any problems.
2301 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002302 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002303 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002304 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002305 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002306 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002307
2308 if (log)
2309 {
2310 StreamString strm;
2311 debugserver_args.Dump (&strm);
2312 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2313 }
2314
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002315 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2316 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002317
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002318 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002319
Greg Claytonb72d0f02011-04-12 05:54:46 +00002320 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002321 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002322 else
Chris Lattner24943d22010-06-08 16:52:24 +00002323 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2324
2325 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002326 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002327 }
2328 else
2329 {
Greg Clayton9c236732011-10-26 00:56:27 +00002330 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002331 }
2332
2333 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2334 StartAsyncThread ();
2335 }
2336 return error;
2337}
2338
2339bool
2340ProcessGDBRemote::MonitorDebugserverProcess
2341(
2342 void *callback_baton,
2343 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002344 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002345 int signo, // Zero for no signal
2346 int exit_status // Exit value of process if signal is zero
2347)
2348{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002349 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2350 // and might not exist anymore, so we need to carefully try to get the
2351 // target for this process first since we have a race condition when
2352 // we are done running between getting the notice that the inferior
2353 // process has died and the debugserver that was debugging this process.
2354 // In our test suite, we are also continually running process after
2355 // process, so we must be very careful to make sure:
2356 // 1 - process object hasn't been deleted already
2357 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002358
2359 // "debugserver_pid" argument passed in is the process ID for
2360 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002361 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002362
Greg Clayton75ccf502010-08-21 02:22:51 +00002363 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002364
Greg Clayton1c4642c2011-11-16 05:37:56 +00002365 // Get a shared pointer to the target that has a matching process pointer.
2366 // This target could be gone, or the target could already have a new process
2367 // object inside of it
2368 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2369
Greg Clayton72e1c782011-01-22 23:43:18 +00002370 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002371 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 +00002372
Greg Clayton1c4642c2011-11-16 05:37:56 +00002373 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002374 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002375 // We found a process in a target that matches, but another thread
2376 // might be in the process of launching a new process that will
2377 // soon replace it, so get a shared pointer to the process so we
2378 // can keep it alive.
2379 ProcessSP process_sp (target_sp->GetProcessSP());
2380 // Now we have a shared pointer to the process that can't go away on us
2381 // so we now make sure it was the same as the one passed in, and also make
2382 // sure that our previous "process *" didn't get deleted and have a new
2383 // "process *" created in its place with the same pointer. To verify this
2384 // we make sure the process has our debugserver process ID. If we pass all
2385 // of these tests, then we are sure that this process is the one we were
2386 // looking for.
2387 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002388 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002389 // Sleep for a half a second to make sure our inferior process has
2390 // time to set its exit status before we set it incorrectly when
2391 // both the debugserver and the inferior process shut down.
2392 usleep (500000);
2393 // If our process hasn't yet exited, debugserver might have died.
2394 // If the process did exit, the we are reaping it.
2395 const StateType state = process->GetState();
2396
2397 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2398 state != eStateInvalid &&
2399 state != eStateUnloaded &&
2400 state != eStateExited &&
2401 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002402 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002403 char error_str[1024];
2404 if (signo)
2405 {
2406 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2407 if (signal_cstr)
2408 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2409 else
2410 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2411 }
Chris Lattner24943d22010-06-08 16:52:24 +00002412 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002413 {
2414 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2415 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002416
Greg Clayton1c4642c2011-11-16 05:37:56 +00002417 process->SetExitStatus (-1, error_str);
2418 }
2419 // Debugserver has exited we need to let our ProcessGDBRemote
2420 // know that it no longer has a debugserver instance
2421 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002422 }
Chris Lattner24943d22010-06-08 16:52:24 +00002423 }
2424 return true;
2425}
2426
2427void
2428ProcessGDBRemote::KillDebugserverProcess ()
2429{
2430 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2431 {
2432 ::kill (m_debugserver_pid, SIGINT);
2433 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2434 }
2435}
2436
2437void
2438ProcessGDBRemote::Initialize()
2439{
2440 static bool g_initialized = false;
2441
2442 if (g_initialized == false)
2443 {
2444 g_initialized = true;
2445 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2446 GetPluginDescriptionStatic(),
2447 CreateInstance);
2448
2449 Log::Callbacks log_callbacks = {
2450 ProcessGDBRemoteLog::DisableLog,
2451 ProcessGDBRemoteLog::EnableLog,
2452 ProcessGDBRemoteLog::ListLogCategories
2453 };
2454
2455 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2456 }
2457}
2458
2459bool
Chris Lattner24943d22010-06-08 16:52:24 +00002460ProcessGDBRemote::StartAsyncThread ()
2461{
Greg Claytone005f2c2010-11-06 01:53:30 +00002462 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002463
2464 if (log)
2465 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2466
2467 // Create a thread that watches our internal state and controls which
2468 // events make it to clients (into the DCProcess event queue).
2469 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002470 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002471}
2472
2473void
2474ProcessGDBRemote::StopAsyncThread ()
2475{
Greg Claytone005f2c2010-11-06 01:53:30 +00002476 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002477
2478 if (log)
2479 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2480
2481 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002482
2483 // This will shut down the async thread.
2484 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002485
2486 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002487 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002488 {
2489 Host::ThreadJoin (m_async_thread, NULL, NULL);
2490 }
2491}
2492
2493
2494void *
2495ProcessGDBRemote::AsyncThread (void *arg)
2496{
2497 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2498
Greg Claytone005f2c2010-11-06 01:53:30 +00002499 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002500 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002501 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002502
2503 Listener listener ("ProcessGDBRemote::AsyncThread");
2504 EventSP event_sp;
2505 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2506 eBroadcastBitAsyncThreadShouldExit;
2507
2508 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2509 {
Greg Claytona2f74232011-02-24 22:24:29 +00002510 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2511
Chris Lattner24943d22010-06-08 16:52:24 +00002512 bool done = false;
2513 while (!done)
2514 {
2515 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002516 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002517 if (listener.WaitForEvent (NULL, event_sp))
2518 {
2519 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002520 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002521 {
Greg Claytona2f74232011-02-24 22:24:29 +00002522 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002523 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 +00002524
Greg Claytona2f74232011-02-24 22:24:29 +00002525 switch (event_type)
2526 {
2527 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002528 {
Greg Claytona2f74232011-02-24 22:24:29 +00002529 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002530
Greg Claytona2f74232011-02-24 22:24:29 +00002531 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002532 {
Greg Claytona2f74232011-02-24 22:24:29 +00002533 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2534 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2535 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002536 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002537
Greg Claytona2f74232011-02-24 22:24:29 +00002538 if (::strstr (continue_cstr, "vAttach") == NULL)
2539 process->SetPrivateState(eStateRunning);
2540 StringExtractorGDBRemote response;
2541 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002542
Greg Clayton67b402c2012-05-16 02:48:06 +00002543 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2544 // The thread ID list might be contained within the "response", or the stop reply packet that
2545 // caused the stop. So clear it now before we give the stop reply packet to the process
2546 // using the process->SetLastStopPacket()...
2547 process->ClearThreadIDList ();
2548
Greg Claytona2f74232011-02-24 22:24:29 +00002549 switch (stop_state)
2550 {
2551 case eStateStopped:
2552 case eStateCrashed:
2553 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002554 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002555 process->SetPrivateState (stop_state);
2556 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002557
Greg Claytona2f74232011-02-24 22:24:29 +00002558 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002559 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002560 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002561 response.SetFilePos(1);
2562 process->SetExitStatus(response.GetHexU8(), NULL);
2563 done = true;
2564 break;
2565
2566 case eStateInvalid:
2567 process->SetExitStatus(-1, "lost connection");
2568 break;
2569
2570 default:
2571 process->SetPrivateState (stop_state);
2572 break;
2573 }
Chris Lattner24943d22010-06-08 16:52:24 +00002574 }
2575 }
Greg Claytona2f74232011-02-24 22:24:29 +00002576 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002577
Greg Claytona2f74232011-02-24 22:24:29 +00002578 case eBroadcastBitAsyncThreadShouldExit:
2579 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002580 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002581 done = true;
2582 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002583
Greg Claytona2f74232011-02-24 22:24:29 +00002584 default:
2585 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002586 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 +00002587 done = true;
2588 break;
2589 }
2590 }
2591 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2592 {
2593 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2594 {
2595 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002596 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002597 }
Chris Lattner24943d22010-06-08 16:52:24 +00002598 }
2599 }
2600 else
2601 {
2602 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002603 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 +00002604 done = true;
2605 }
2606 }
2607 }
2608
2609 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002610 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002611
2612 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2613 return NULL;
2614}
2615
Chris Lattner24943d22010-06-08 16:52:24 +00002616const char *
2617ProcessGDBRemote::GetDispatchQueueNameForThread
2618(
2619 addr_t thread_dispatch_qaddr,
2620 std::string &dispatch_queue_name
2621)
2622{
2623 dispatch_queue_name.clear();
2624 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2625 {
2626 // Cache the dispatch_queue_offsets_addr value so we don't always have
2627 // to look it up
2628 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2629 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002630 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2631 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002632 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2633 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002634 if (module_sp)
2635 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2636
2637 if (dispatch_queue_offsets_symbol == NULL)
2638 {
Greg Clayton444fe992012-02-26 05:51:37 +00002639 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2640 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002641 if (module_sp)
2642 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2643 }
Chris Lattner24943d22010-06-08 16:52:24 +00002644 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002645 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002646
2647 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2648 return NULL;
2649 }
2650
2651 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002652 DataExtractor data (memory_buffer,
2653 sizeof(memory_buffer),
2654 m_target.GetArchitecture().GetByteOrder(),
2655 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002656
2657 // Excerpt from src/queue_private.h
2658 struct dispatch_queue_offsets_s
2659 {
2660 uint16_t dqo_version;
2661 uint16_t dqo_label;
2662 uint16_t dqo_label_size;
2663 } dispatch_queue_offsets;
2664
2665
2666 Error error;
2667 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2668 {
2669 uint32_t data_offset = 0;
2670 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2671 {
2672 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2673 {
2674 data_offset = 0;
2675 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2676 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2677 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2678 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2679 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2680 dispatch_queue_name.erase (bytes_read);
2681 }
2682 }
2683 }
2684 }
2685 if (dispatch_queue_name.empty())
2686 return NULL;
2687 return dispatch_queue_name.c_str();
2688}
2689
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002690//uint32_t
2691//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2692//{
2693// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2694// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2695// if (m_local_debugserver)
2696// {
2697// return Host::ListProcessesMatchingName (name, matches, pids);
2698// }
2699// else
2700// {
2701// // FIXME: Implement talking to the remote debugserver.
2702// return 0;
2703// }
2704//
2705//}
2706//
Jim Ingham55e01d82011-01-22 01:33:44 +00002707bool
2708ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2709 lldb_private::StoppointCallbackContext *context,
2710 lldb::user_id_t break_id,
2711 lldb::user_id_t break_loc_id)
2712{
2713 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2714 // run so I can stop it if that's what I want to do.
2715 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2716 if (log)
2717 log->Printf("Hit New Thread Notification breakpoint.");
2718 return false;
2719}
2720
2721
2722bool
2723ProcessGDBRemote::StartNoticingNewThreads()
2724{
Jim Ingham55e01d82011-01-22 01:33:44 +00002725 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002726 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002727 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002728 if (log && log->GetVerbose())
2729 log->Printf("Enabled noticing new thread breakpoint.");
2730 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002731 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002732 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002733 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002734 PlatformSP platform_sp (m_target.GetPlatform());
2735 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002736 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002737 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2738 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002739 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002740 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002741 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2742 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002743 }
2744 else
2745 {
2746 if (log)
2747 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002748 }
2749 }
2750 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002751 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002752}
2753
2754bool
2755ProcessGDBRemote::StopNoticingNewThreads()
2756{
Jim Inghamff276fe2011-02-08 05:19:01 +00002757 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002758 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002759 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002760
2761 if (m_thread_create_bp_sp)
2762 m_thread_create_bp_sp->SetEnabled(false);
2763
Jim Ingham55e01d82011-01-22 01:33:44 +00002764 return true;
2765}
2766
2767