blob: caf3461048de0250fc208b7f3d352cb7529e8842 [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.
404 if (target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
405 m_register_info.Addx86_64ConvenienceRegisters();
406
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000407 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000408 m_register_info.Finalize ();
409}
410
411Error
412ProcessGDBRemote::WillLaunch (Module* module)
413{
414 return WillLaunchOrAttach ();
415}
416
417Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000418ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000419{
420 return WillLaunchOrAttach ();
421}
422
423Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000424ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000425{
426 return WillLaunchOrAttach ();
427}
428
429Error
Greg Claytone71e2582011-02-04 01:58:07 +0000430ProcessGDBRemote::DoConnectRemote (const char *remote_url)
431{
432 Error error (WillLaunchOrAttach ());
433
434 if (error.Fail())
435 return error;
436
Greg Clayton180546b2011-04-30 01:09:13 +0000437 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000438
439 if (error.Fail())
440 return error;
441 StartAsyncThread ();
442
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000443 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000444 if (pid == LLDB_INVALID_PROCESS_ID)
445 {
446 // We don't have a valid process ID, so note that we are connected
447 // and could now request to launch or attach, or get remote process
448 // listings...
449 SetPrivateState (eStateConnected);
450 }
451 else
452 {
453 // We have a valid process
454 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000455 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000456 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000457 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000458 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000459 if (state == eStateStopped)
460 {
461 SetPrivateState (state);
462 }
463 else
Greg Claytond9919d32011-12-01 23:28:38 +0000464 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 +0000465 }
466 else
Greg Claytond9919d32011-12-01 23:28:38 +0000467 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 +0000468 }
Jason Molendacb740b32012-05-03 22:37:30 +0000469
470 if (error.Success()
471 && !GetTarget().GetArchitecture().IsValid()
472 && m_gdb_comm.GetHostArchitecture().IsValid())
473 {
474 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
475 }
476
Greg Claytone71e2582011-02-04 01:58:07 +0000477 return error;
478}
479
480Error
Chris Lattner24943d22010-06-08 16:52:24 +0000481ProcessGDBRemote::WillLaunchOrAttach ()
482{
483 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000484 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000485 return error;
486}
487
488//----------------------------------------------------------------------
489// Process Control
490//----------------------------------------------------------------------
491Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000492ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000493{
Greg Clayton4b407112010-09-30 21:49:03 +0000494 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000495
496 uint32_t launch_flags = launch_info.GetFlags().Get();
497 const char *stdin_path = NULL;
498 const char *stdout_path = NULL;
499 const char *stderr_path = NULL;
500 const char *working_dir = launch_info.GetWorkingDirectory();
501
502 const ProcessLaunchInfo::FileAction *file_action;
503 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
504 if (file_action)
505 {
506 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
507 stdin_path = file_action->GetPath();
508 }
509 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
510 if (file_action)
511 {
512 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
513 stdout_path = file_action->GetPath();
514 }
515 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
516 if (file_action)
517 {
518 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
519 stderr_path = file_action->GetPath();
520 }
521
Chris Lattner24943d22010-06-08 16:52:24 +0000522 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
523 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
524 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000525 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000526
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000527 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000528 if (object_file)
529 {
Chris Lattner24943d22010-06-08 16:52:24 +0000530 char host_port[128];
531 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000532 char connect_url[128];
533 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000534
Greg Claytona2f74232011-02-24 22:24:29 +0000535 // Make sure we aren't already connected?
536 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000537 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000538 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000539 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000540 {
Johnny Chenc143d622011-08-09 18:56:45 +0000541 if (log)
542 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000543 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000544 }
Chris Lattner24943d22010-06-08 16:52:24 +0000545
Greg Claytone71e2582011-02-04 01:58:07 +0000546 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000547 }
548
549 if (error.Success())
550 {
551 lldb_utility::PseudoTerminal pty;
552 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000553
554 // If the debugserver is local and we aren't disabling STDIO, lets use
555 // a pseudo terminal to instead of relying on the 'O' packets for stdio
556 // since 'O' packets can really slow down debugging if the inferior
557 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000558 PlatformSP platform_sp (m_target.GetPlatform());
559 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000560 {
561 const char *slave_name = NULL;
562 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000563 {
Greg Claytona2f74232011-02-24 22:24:29 +0000564 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
565 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000566 }
Greg Claytona2f74232011-02-24 22:24:29 +0000567 if (stdin_path == NULL)
568 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000569
Greg Claytona2f74232011-02-24 22:24:29 +0000570 if (stdout_path == NULL)
571 stdout_path = slave_name;
572
573 if (stderr_path == NULL)
574 stderr_path = slave_name;
575 }
576
Greg Claytonafb81862011-03-02 21:34:46 +0000577 // Set STDIN to /dev/null if we want STDIO disabled or if either
578 // STDOUT or STDERR have been set to something and STDIN hasn't
579 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000580 stdin_path = "/dev/null";
581
Greg Claytonafb81862011-03-02 21:34:46 +0000582 // Set STDOUT to /dev/null if we want STDIO disabled or if either
583 // STDIN or STDERR have been set to something and STDOUT hasn't
584 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000585 stdout_path = "/dev/null";
586
Greg Claytonafb81862011-03-02 21:34:46 +0000587 // Set STDERR to /dev/null if we want STDIO disabled or if either
588 // STDIN or STDOUT have been set to something and STDERR hasn't
589 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000590 stderr_path = "/dev/null";
591
592 if (stdin_path)
593 m_gdb_comm.SetSTDIN (stdin_path);
594 if (stdout_path)
595 m_gdb_comm.SetSTDOUT (stdout_path);
596 if (stderr_path)
597 m_gdb_comm.SetSTDERR (stderr_path);
598
599 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
600
Greg Claytona4582402011-05-08 04:53:50 +0000601 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000602
603 if (working_dir && working_dir[0])
604 {
605 m_gdb_comm.SetWorkingDir (working_dir);
606 }
607
608 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000609 const Args &environment = launch_info.GetEnvironmentEntries();
610 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000611 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000612 size_t num_environment_entries = environment.GetArgumentCount();
613 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000614 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000615 const char *env_entry = environment.GetArgumentAtIndex(i);
616 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000617 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000618 }
Greg Claytona2f74232011-02-24 22:24:29 +0000619 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000620
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000621 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000622 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000623 if (arg_packet_err == 0)
624 {
625 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000626 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000627 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000628 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000629 }
630 else
631 {
Greg Claytona2f74232011-02-24 22:24:29 +0000632 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000633 }
Greg Claytona2f74232011-02-24 22:24:29 +0000634 }
635 else
636 {
Greg Clayton9c236732011-10-26 00:56:27 +0000637 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000638 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000639
640 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000641
Greg Claytona2f74232011-02-24 22:24:29 +0000642 if (GetID() == LLDB_INVALID_PROCESS_ID)
643 {
Johnny Chenc143d622011-08-09 18:56:45 +0000644 if (log)
645 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000646 KillDebugserverProcess ();
647 return error;
648 }
649
Greg Clayton261a18b2011-06-02 22:22:38 +0000650 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000651 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000652 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000653
654 if (!disable_stdio)
655 {
656 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000657 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000658 }
Chris Lattner24943d22010-06-08 16:52:24 +0000659 }
660 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000661 else
662 {
Johnny Chenc143d622011-08-09 18:56:45 +0000663 if (log)
664 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000665 }
Chris Lattner24943d22010-06-08 16:52:24 +0000666 }
667 else
668 {
669 // Set our user ID to an invalid process ID.
670 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000671 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
672 exe_module->GetFileSpec().GetFilename().AsCString(),
673 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000674 }
Chris Lattner24943d22010-06-08 16:52:24 +0000675 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000676
Chris Lattner24943d22010-06-08 16:52:24 +0000677}
678
679
680Error
Greg Claytone71e2582011-02-04 01:58:07 +0000681ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000682{
683 Error error;
684 // Sleep and wait a bit for debugserver to start to listen...
685 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
686 if (conn_ap.get())
687 {
Chris Lattner24943d22010-06-08 16:52:24 +0000688 const uint32_t max_retry_count = 50;
689 uint32_t retry_count = 0;
690 while (!m_gdb_comm.IsConnected())
691 {
Greg Claytone71e2582011-02-04 01:58:07 +0000692 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000693 {
694 m_gdb_comm.SetConnection (conn_ap.release());
695 break;
696 }
697 retry_count++;
698
699 if (retry_count >= max_retry_count)
700 break;
701
702 usleep (100000);
703 }
704 }
705
706 if (!m_gdb_comm.IsConnected())
707 {
708 if (error.Success())
709 error.SetErrorString("not connected to remote gdb server");
710 return error;
711 }
712
Greg Clayton24bc5d92011-03-30 18:16:51 +0000713 // We always seem to be able to open a connection to a local port
714 // so we need to make sure we can then send data to it. If we can't
715 // then we aren't actually connected to anything, so try and do the
716 // handshake with the remote GDB server and make sure that goes
717 // alright.
718 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000719 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000720 m_gdb_comm.Disconnect();
721 if (error.Success())
722 error.SetErrorString("not connected to remote gdb server");
723 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000724 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000725 m_gdb_comm.ResetDiscoverableSettings();
726 m_gdb_comm.QueryNoAckModeSupported ();
727 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000728 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000729 m_gdb_comm.GetHostInfo ();
730 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000731 return error;
732}
733
734void
735ProcessGDBRemote::DidLaunchOrAttach ()
736{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000737 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
738 if (log)
739 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000740 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000741 {
742 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
743
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000744 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000745
Chris Lattner24943d22010-06-08 16:52:24 +0000746 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000747
Greg Claytoncb8977d2011-03-23 00:09:55 +0000748 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
749 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000750 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000751 ArchSpec &target_arch = GetTarget().GetArchitecture();
752
753 if (target_arch.IsValid())
754 {
755 // If the remote host is ARM and we have apple as the vendor, then
756 // ARM executables and shared libraries can have mixed ARM architectures.
757 // You can have an armv6 executable, and if the host is armv7, then the
758 // system will load the best possible architecture for all shared libraries
759 // it has, so we really need to take the remote host architecture as our
760 // defacto architecture in this case.
761
762 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
763 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
764 {
765 target_arch = gdb_remote_arch;
766 }
767 else
768 {
769 // Fill in what is missing in the triple
770 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
771 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000772 if (target_triple.getVendorName().size() == 0)
773 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000774 target_triple.setVendor (remote_triple.getVendor());
775
Greg Clayton2f085c62011-05-15 01:25:55 +0000776 if (target_triple.getOSName().size() == 0)
777 {
778 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000779
Greg Clayton2f085c62011-05-15 01:25:55 +0000780 if (target_triple.getEnvironmentName().size() == 0)
781 target_triple.setEnvironment (remote_triple.getEnvironment());
782 }
783 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000784 }
785 }
786 else
787 {
788 // The target doesn't have a valid architecture yet, set it from
789 // the architecture we got from the remote GDB server
790 target_arch = gdb_remote_arch;
791 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000792 }
Chris Lattner24943d22010-06-08 16:52:24 +0000793 }
794}
795
796void
797ProcessGDBRemote::DidLaunch ()
798{
799 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000800}
801
802Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000803ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000804{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000805 ProcessAttachInfo attach_info;
806 return DoAttachToProcessWithID(attach_pid, attach_info);
807}
808
809Error
810ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
811{
Chris Lattner24943d22010-06-08 16:52:24 +0000812 Error error;
813 // Clear out and clean up from any current state
814 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000815 if (attach_pid != LLDB_INVALID_PROCESS_ID)
816 {
Greg Claytona2f74232011-02-24 22:24:29 +0000817 // Make sure we aren't already connected?
818 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000819 {
Greg Claytona2f74232011-02-24 22:24:29 +0000820 char host_port[128];
821 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
822 char connect_url[128];
823 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000824
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000825 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000826
827 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000828 {
Greg Claytona2f74232011-02-24 22:24:29 +0000829 const char *error_string = error.AsCString();
830 if (error_string == NULL)
831 error_string = "unable to launch " DEBUGSERVER_BASENAME;
832
833 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000834 }
Greg Claytona2f74232011-02-24 22:24:29 +0000835 else
836 {
837 error = ConnectToDebugserver (connect_url);
838 }
839 }
840
841 if (error.Success())
842 {
843 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000844 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000845 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000846 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000847 }
848 }
Chris Lattner24943d22010-06-08 16:52:24 +0000849 return error;
850}
851
852size_t
853ProcessGDBRemote::AttachInputReaderCallback
854(
855 void *baton,
856 InputReader *reader,
857 lldb::InputReaderAction notification,
858 const char *bytes,
859 size_t bytes_len
860)
861{
862 if (notification == eInputReaderGotToken)
863 {
864 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
865 if (gdb_process->m_waiting_for_attach)
866 gdb_process->m_waiting_for_attach = false;
867 reader->SetIsDone(true);
868 return 1;
869 }
870 return 0;
871}
872
873Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000874ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000875{
876 Error error;
877 // Clear out and clean up from any current state
878 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000879
Chris Lattner24943d22010-06-08 16:52:24 +0000880 if (process_name && process_name[0])
881 {
Greg Claytona2f74232011-02-24 22:24:29 +0000882 // Make sure we aren't already connected?
883 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000884 {
Greg Claytona2f74232011-02-24 22:24:29 +0000885 char host_port[128];
886 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
887 char connect_url[128];
888 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
889
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000890 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000891 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000892 {
Greg Claytona2f74232011-02-24 22:24:29 +0000893 const char *error_string = error.AsCString();
894 if (error_string == NULL)
895 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000896
Greg Claytona2f74232011-02-24 22:24:29 +0000897 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000898 }
Greg Claytona2f74232011-02-24 22:24:29 +0000899 else
900 {
901 error = ConnectToDebugserver (connect_url);
902 }
903 }
904
905 if (error.Success())
906 {
907 StreamString packet;
908
909 if (wait_for_launch)
910 packet.PutCString("vAttachWait");
911 else
912 packet.PutCString("vAttachName");
913 packet.PutChar(';');
914 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
915
916 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
917
Chris Lattner24943d22010-06-08 16:52:24 +0000918 }
919 }
Chris Lattner24943d22010-06-08 16:52:24 +0000920 return error;
921}
922
Chris Lattner24943d22010-06-08 16:52:24 +0000923
924void
925ProcessGDBRemote::DidAttach ()
926{
Greg Claytone71e2582011-02-04 01:58:07 +0000927 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000928}
929
930Error
931ProcessGDBRemote::WillResume ()
932{
Greg Claytonc1f45872011-02-12 06:28:37 +0000933 m_continue_c_tids.clear();
934 m_continue_C_tids.clear();
935 m_continue_s_tids.clear();
936 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000937 return Error();
938}
939
940Error
941ProcessGDBRemote::DoResume ()
942{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000943 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000944 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
945 if (log)
946 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000947
948 Listener listener ("gdb-remote.resume-packet-sent");
949 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
950 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000951 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
952
Greg Claytonc1f45872011-02-12 06:28:37 +0000953 StreamString continue_packet;
954 bool continue_packet_error = false;
955 if (m_gdb_comm.HasAnyVContSupport ())
956 {
957 continue_packet.PutCString ("vCont");
958
959 if (!m_continue_c_tids.empty())
960 {
961 if (m_gdb_comm.GetVContSupported ('c'))
962 {
963 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 +0000964 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000965 }
966 else
967 continue_packet_error = true;
968 }
969
970 if (!continue_packet_error && !m_continue_C_tids.empty())
971 {
972 if (m_gdb_comm.GetVContSupported ('C'))
973 {
974 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 +0000975 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000976 }
977 else
978 continue_packet_error = true;
979 }
Greg Claytonb749a262010-12-03 06:02:24 +0000980
Greg Claytonc1f45872011-02-12 06:28:37 +0000981 if (!continue_packet_error && !m_continue_s_tids.empty())
982 {
983 if (m_gdb_comm.GetVContSupported ('s'))
984 {
985 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 +0000986 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000987 }
988 else
989 continue_packet_error = true;
990 }
991
992 if (!continue_packet_error && !m_continue_S_tids.empty())
993 {
994 if (m_gdb_comm.GetVContSupported ('S'))
995 {
996 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 +0000997 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000998 }
999 else
1000 continue_packet_error = true;
1001 }
1002
1003 if (continue_packet_error)
1004 continue_packet.GetString().clear();
1005 }
1006 else
1007 continue_packet_error = true;
1008
1009 if (continue_packet_error)
1010 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001011 // Either no vCont support, or we tried to use part of the vCont
1012 // packet that wasn't supported by the remote GDB server.
1013 // We need to try and make a simple packet that can do our continue
1014 const size_t num_threads = GetThreadList().GetSize();
1015 const size_t num_continue_c_tids = m_continue_c_tids.size();
1016 const size_t num_continue_C_tids = m_continue_C_tids.size();
1017 const size_t num_continue_s_tids = m_continue_s_tids.size();
1018 const size_t num_continue_S_tids = m_continue_S_tids.size();
1019 if (num_continue_c_tids > 0)
1020 {
1021 if (num_continue_c_tids == num_threads)
1022 {
1023 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001024 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001025 continue_packet.PutChar ('c');
1026 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001027 }
1028 else if (num_continue_c_tids == 1 &&
1029 num_continue_C_tids == 0 &&
1030 num_continue_s_tids == 0 &&
1031 num_continue_S_tids == 0 )
1032 {
1033 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001034 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001035 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001036 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001037 }
1038 }
1039
Greg Claytonde1dd812011-06-24 03:21:43 +00001040 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001041 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001042 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1043 num_continue_C_tids > 0 &&
1044 num_continue_s_tids == 0 &&
1045 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001046 {
1047 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001048 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001049 if (num_continue_C_tids > 1)
1050 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001051 // More that one thread with a signal, yet we don't have
1052 // vCont support and we are being asked to resume each
1053 // thread with a signal, we need to make sure they are
1054 // all the same signal, or we can't issue the continue
1055 // accurately with the current support...
1056 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001057 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001058 continue_packet_error = false;
1059 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1060 {
1061 if (m_continue_C_tids[i].second != continue_signo)
1062 continue_packet_error = true;
1063 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001064 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001065 if (!continue_packet_error)
1066 m_gdb_comm.SetCurrentThreadForRun (-1);
1067 }
1068 else
1069 {
1070 // Set the continue thread ID
1071 continue_packet_error = false;
1072 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001073 }
1074 if (!continue_packet_error)
1075 {
1076 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001077 continue_packet.Printf("C%2.2x", continue_signo);
1078 }
1079 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001080 }
1081
Greg Claytonde1dd812011-06-24 03:21:43 +00001082 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001083 {
1084 if (num_continue_s_tids == num_threads)
1085 {
1086 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001087 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001088 continue_packet.PutChar ('s');
1089 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001090 }
1091 else if (num_continue_c_tids == 0 &&
1092 num_continue_C_tids == 0 &&
1093 num_continue_s_tids == 1 &&
1094 num_continue_S_tids == 0 )
1095 {
1096 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001097 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001098 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001099 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001100 }
1101 }
1102
1103 if (!continue_packet_error && num_continue_S_tids > 0)
1104 {
1105 if (num_continue_S_tids == num_threads)
1106 {
1107 const int step_signo = m_continue_S_tids.front().second;
1108 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001109 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001110 if (num_continue_S_tids > 1)
1111 {
1112 for (size_t i=1; i<num_threads; ++i)
1113 {
1114 if (m_continue_S_tids[i].second != step_signo)
1115 continue_packet_error = true;
1116 }
1117 }
1118 if (!continue_packet_error)
1119 {
1120 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001121 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001122 continue_packet.Printf("S%2.2x", step_signo);
1123 }
1124 }
1125 else if (num_continue_c_tids == 0 &&
1126 num_continue_C_tids == 0 &&
1127 num_continue_s_tids == 0 &&
1128 num_continue_S_tids == 1 )
1129 {
1130 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001131 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001132 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001133 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001134 }
1135 }
1136 }
1137
1138 if (continue_packet_error)
1139 {
1140 error.SetErrorString ("can't make continue packet for this resume");
1141 }
1142 else
1143 {
1144 EventSP event_sp;
1145 TimeValue timeout;
1146 timeout = TimeValue::Now();
1147 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001148 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1149 {
1150 error.SetErrorString ("Trying to resume but the async thread is dead.");
1151 if (log)
1152 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1153 return error;
1154 }
1155
Greg Claytonc1f45872011-02-12 06:28:37 +00001156 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1157
1158 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001159 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001160 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001161 if (log)
1162 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1163 }
1164 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1165 {
1166 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1167 if (log)
1168 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1169 return error;
1170 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001171 }
Greg Claytonb749a262010-12-03 06:02:24 +00001172 }
1173
Jim Ingham3ae449a2010-11-17 02:32:00 +00001174 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001175}
1176
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001177void
1178ProcessGDBRemote::ClearThreadIDList ()
1179{
Greg Claytonff3448e2012-04-13 02:11:32 +00001180 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001181 m_thread_ids.clear();
1182}
1183
1184bool
1185ProcessGDBRemote::UpdateThreadIDList ()
1186{
Greg Claytonff3448e2012-04-13 02:11:32 +00001187 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001188 bool sequence_mutex_unavailable = false;
1189 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1190 if (sequence_mutex_unavailable)
1191 {
1192#if defined (LLDB_CONFIGURATION_DEBUG)
1193 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1194#endif
1195 return false; // We just didn't get the list
1196 }
1197 return true;
1198}
1199
Greg Claytonae932352012-04-10 00:18:59 +00001200bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001201ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001202{
1203 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001204 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001205 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001206 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001207
1208 size_t num_thread_ids = m_thread_ids.size();
1209 // The "m_thread_ids" thread ID list should always be updated after each stop
1210 // reply packet, but in case it isn't, update it here.
1211 if (num_thread_ids == 0)
1212 {
1213 if (!UpdateThreadIDList ())
1214 return false;
1215 num_thread_ids = m_thread_ids.size();
1216 }
Chris Lattner24943d22010-06-08 16:52:24 +00001217
Greg Clayton37f962e2011-08-22 02:49:39 +00001218 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001219 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001220 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001221 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001222 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001223 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1224 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001225 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001226 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001227 }
Chris Lattner24943d22010-06-08 16:52:24 +00001228 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001229
Greg Claytonae932352012-04-10 00:18:59 +00001230 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001231}
1232
1233
1234StateType
1235ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1236{
Greg Clayton261a18b2011-06-02 22:22:38 +00001237 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001238 const char stop_type = stop_packet.GetChar();
1239 switch (stop_type)
1240 {
1241 case 'T':
1242 case 'S':
1243 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001244 if (GetStopID() == 0)
1245 {
1246 // Our first stop, make sure we have a process ID, and also make
1247 // sure we know about our registers
1248 if (GetID() == LLDB_INVALID_PROCESS_ID)
1249 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001250 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001251 if (pid != LLDB_INVALID_PROCESS_ID)
1252 SetID (pid);
1253 }
1254 BuildDynamicRegisterInfo (true);
1255 }
Chris Lattner24943d22010-06-08 16:52:24 +00001256 // Stop with signal and thread info
1257 const uint8_t signo = stop_packet.GetHexU8();
1258 std::string name;
1259 std::string value;
1260 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001261 std::string reason;
1262 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001263 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001264 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001265 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1266 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001267 ThreadSP thread_sp;
1268
Chris Lattner24943d22010-06-08 16:52:24 +00001269 while (stop_packet.GetNameColonValue(name, value))
1270 {
1271 if (name.compare("metype") == 0)
1272 {
1273 // exception type in big endian hex
1274 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1275 }
1276 else if (name.compare("mecount") == 0)
1277 {
1278 // exception count in big endian hex
1279 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1280 }
1281 else if (name.compare("medata") == 0)
1282 {
1283 // exception data in big endian hex
1284 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1285 }
1286 else if (name.compare("thread") == 0)
1287 {
1288 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001289 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001290 // m_thread_list does have its own mutex, but we need to
1291 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1292 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001293 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001294 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001295 if (!thread_sp)
1296 {
1297 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001298 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001299 m_thread_list.AddThread(thread_sp);
1300 }
Chris Lattner24943d22010-06-08 16:52:24 +00001301 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001302 else if (name.compare("threads") == 0)
1303 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001304 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001305 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001306 // A comma separated list of all threads in the current
1307 // process that includes the thread for this stop reply
1308 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001309 size_t comma_pos;
1310 lldb::tid_t tid;
1311 while ((comma_pos = value.find(',')) != std::string::npos)
1312 {
1313 value[comma_pos] = '\0';
1314 // thread in big endian hex
1315 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1316 if (tid != LLDB_INVALID_THREAD_ID)
1317 m_thread_ids.push_back (tid);
1318 value.erase(0, comma_pos + 1);
1319
1320 }
1321 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1322 if (tid != LLDB_INVALID_THREAD_ID)
1323 m_thread_ids.push_back (tid);
1324 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001325 else if (name.compare("hexname") == 0)
1326 {
1327 StringExtractor name_extractor;
1328 // Swap "value" over into "name_extractor"
1329 name_extractor.GetStringRef().swap(value);
1330 // Now convert the HEX bytes into a string value
1331 name_extractor.GetHexByteString (value);
1332 thread_name.swap (value);
1333 }
Chris Lattner24943d22010-06-08 16:52:24 +00001334 else if (name.compare("name") == 0)
1335 {
1336 thread_name.swap (value);
1337 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001338 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001339 {
1340 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1341 }
Greg Clayton65611552011-06-04 01:26:29 +00001342 else if (name.compare("reason") == 0)
1343 {
1344 reason.swap(value);
1345 }
1346 else if (name.compare("description") == 0)
1347 {
1348 StringExtractor desc_extractor;
1349 // Swap "value" over into "name_extractor"
1350 desc_extractor.GetStringRef().swap(value);
1351 // Now convert the HEX bytes into a string value
1352 desc_extractor.GetHexByteString (thread_name);
1353 }
Greg Claytona875b642011-01-09 21:07:35 +00001354 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1355 {
1356 // We have a register number that contains an expedited
1357 // register value. Lets supply this register to our thread
1358 // so it won't have to go and read it.
1359 if (thread_sp)
1360 {
1361 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1362
1363 if (reg != UINT32_MAX)
1364 {
1365 StringExtractor reg_value_extractor;
1366 // Swap "value" over into "reg_value_extractor"
1367 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001368 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1369 {
1370 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1371 name.c_str(),
1372 reg,
1373 reg,
1374 reg_value_extractor.GetStringRef().c_str(),
1375 stop_packet.GetStringRef().c_str());
1376 }
Greg Claytona875b642011-01-09 21:07:35 +00001377 }
1378 }
1379 }
Chris Lattner24943d22010-06-08 16:52:24 +00001380 }
Chris Lattner24943d22010-06-08 16:52:24 +00001381
1382 if (thread_sp)
1383 {
1384 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1385
1386 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001387 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001388 if (exc_type != 0)
1389 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001390 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001391
1392 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1393 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001394 exc_data_size,
1395 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001396 exc_data_size >= 2 ? exc_data[1] : 0,
1397 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001398 }
Greg Clayton65611552011-06-04 01:26:29 +00001399 else
Chris Lattner24943d22010-06-08 16:52:24 +00001400 {
Greg Clayton65611552011-06-04 01:26:29 +00001401 bool handled = false;
1402 if (!reason.empty())
1403 {
1404 if (reason.compare("trace") == 0)
1405 {
1406 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1407 handled = true;
1408 }
1409 else if (reason.compare("breakpoint") == 0)
1410 {
1411 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001412 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001413 if (bp_site_sp)
1414 {
1415 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1416 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1417 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1418 if (bp_site_sp->ValidForThisThread (gdb_thread))
1419 {
1420 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1421 handled = true;
1422 }
1423 }
1424
1425 if (!handled)
1426 {
1427 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1428 }
1429 }
1430 else if (reason.compare("trap") == 0)
1431 {
1432 // Let the trap just use the standard signal stop reason below...
1433 }
1434 else if (reason.compare("watchpoint") == 0)
1435 {
1436 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1437 // TODO: locate the watchpoint somehow...
1438 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1439 handled = true;
1440 }
1441 else if (reason.compare("exception") == 0)
1442 {
1443 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1444 handled = true;
1445 }
1446 }
1447
1448 if (signo)
1449 {
1450 if (signo == SIGTRAP)
1451 {
1452 // Currently we are going to assume SIGTRAP means we are either
1453 // hitting a breakpoint or hardware single stepping.
1454 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001455 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001456 if (bp_site_sp)
1457 {
1458 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1459 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1460 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1461 if (bp_site_sp->ValidForThisThread (gdb_thread))
1462 {
1463 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1464 handled = true;
1465 }
1466 }
1467 if (!handled)
1468 {
1469 // TODO: check for breakpoint or trap opcode in case there is a hard
1470 // coded software trap
1471 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1472 handled = true;
1473 }
1474 }
1475 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001476 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001477 }
1478 else
1479 {
Greg Clayton643ee732010-08-04 01:40:35 +00001480 StopInfoSP invalid_stop_info_sp;
1481 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001482 }
Greg Clayton65611552011-06-04 01:26:29 +00001483
1484 if (!description.empty())
1485 {
1486 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1487 if (stop_info_sp)
1488 {
1489 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001490 }
Greg Clayton65611552011-06-04 01:26:29 +00001491 else
1492 {
1493 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1494 }
1495 }
1496 }
Chris Lattner24943d22010-06-08 16:52:24 +00001497 }
1498 return eStateStopped;
1499 }
1500 break;
1501
1502 case 'W':
1503 // process exited
1504 return eStateExited;
1505
1506 default:
1507 break;
1508 }
1509 return eStateInvalid;
1510}
1511
1512void
1513ProcessGDBRemote::RefreshStateAfterStop ()
1514{
Greg Claytonff3448e2012-04-13 02:11:32 +00001515 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001516 m_thread_ids.clear();
1517 // Set the thread stop info. It might have a "threads" key whose value is
1518 // a list of all thread IDs in the current process, so m_thread_ids might
1519 // get set.
1520 SetThreadStopInfo (m_last_stop_packet);
1521 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1522 if (m_thread_ids.empty())
1523 {
1524 // No, we need to fetch the thread list manually
1525 UpdateThreadIDList();
1526 }
1527
Chris Lattner24943d22010-06-08 16:52:24 +00001528 // Let all threads recover from stopping and do any clean up based
1529 // on the previous thread state (if any).
1530 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001531
Chris Lattner24943d22010-06-08 16:52:24 +00001532}
1533
1534Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001535ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001536{
1537 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001538
Greg Claytona4881d02011-01-22 07:12:45 +00001539 bool timed_out = false;
1540 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001541
1542 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001543 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001544 // We are being asked to halt during an attach. We need to just close
1545 // our file handle and debugserver will go away, and we can be done...
1546 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001547 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001548 else
1549 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001550 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001551 {
1552 if (timed_out)
1553 error.SetErrorString("timed out sending interrupt packet");
1554 else
1555 error.SetErrorString("unknown error sending interrupt packet");
1556 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001557
1558 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001559 }
Chris Lattner24943d22010-06-08 16:52:24 +00001560 return error;
1561}
1562
1563Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001564ProcessGDBRemote::InterruptIfRunning
1565(
1566 bool discard_thread_plans,
1567 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001568 EventSP &stop_event_sp
1569)
Chris Lattner24943d22010-06-08 16:52:24 +00001570{
1571 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001572
Greg Clayton2860ba92011-01-23 19:58:49 +00001573 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1574
Greg Clayton68ca8232011-01-25 02:58:48 +00001575 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001576 const bool is_running = m_gdb_comm.IsRunning();
1577 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001578 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001579 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001580 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001581 is_running);
1582
Greg Clayton2860ba92011-01-23 19:58:49 +00001583 if (discard_thread_plans)
1584 {
1585 if (log)
1586 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1587 m_thread_list.DiscardThreadPlans();
1588 }
1589 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001590 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001591 if (catch_stop_event)
1592 {
1593 if (log)
1594 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1595 PausePrivateStateThread();
1596 paused_private_state_thread = true;
1597 }
1598
Greg Clayton4fb400f2010-09-27 21:07:38 +00001599 bool timed_out = false;
1600 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001601
Greg Clayton05e4d972012-03-29 01:55:41 +00001602 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001603 {
1604 if (timed_out)
1605 error.SetErrorString("timed out sending interrupt packet");
1606 else
1607 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001608 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001609 ResumePrivateStateThread();
1610 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001611 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001612
Greg Clayton72e1c782011-01-22 23:43:18 +00001613 if (catch_stop_event)
1614 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001615 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001616 TimeValue timeout_time;
1617 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001618 timeout_time.OffsetWithSeconds(5);
1619 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001620
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001621 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001622 if (log)
1623 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001624
Greg Clayton2860ba92011-01-23 19:58:49 +00001625 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001626 error.SetErrorString("unable to verify target stopped");
1627 }
1628
Greg Clayton68ca8232011-01-25 02:58:48 +00001629 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001630 {
1631 if (log)
1632 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001633 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001634 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001635 }
Chris Lattner24943d22010-06-08 16:52:24 +00001636 return error;
1637}
1638
Greg Clayton4fb400f2010-09-27 21:07:38 +00001639Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001640ProcessGDBRemote::WillDetach ()
1641{
Greg Clayton2860ba92011-01-23 19:58:49 +00001642 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1643 if (log)
1644 log->Printf ("ProcessGDBRemote::WillDetach()");
1645
Greg Clayton72e1c782011-01-22 23:43:18 +00001646 bool discard_thread_plans = true;
1647 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001648 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001649
1650 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1651 // needed. This shouldn't be a feature of a particular plugin.
1652
Greg Clayton68ca8232011-01-25 02:58:48 +00001653 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001654}
1655
1656Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001657ProcessGDBRemote::DoDetach()
1658{
1659 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001660 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001661 if (log)
1662 log->Printf ("ProcessGDBRemote::DoDetach()");
1663
1664 DisableAllBreakpointSites ();
1665
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001666 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001667
Greg Clayton516f0842012-04-11 00:24:49 +00001668 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001669 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001670 {
Greg Clayton516f0842012-04-11 00:24:49 +00001671 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001672 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1673 else
1674 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001675 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001676 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001677 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001678
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001679 SetPrivateState (eStateDetached);
1680 ResumePrivateStateThread();
1681
1682 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001683 return error;
1684}
Chris Lattner24943d22010-06-08 16:52:24 +00001685
1686Error
1687ProcessGDBRemote::DoDestroy ()
1688{
1689 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001690 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001691 if (log)
1692 log->Printf ("ProcessGDBRemote::DoDestroy()");
1693
1694 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001695 int exit_status = SIGABRT;
1696 std::string exit_string;
1697
Greg Claytona4881d02011-01-22 07:12:45 +00001698 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001699 {
Jim Ingham8226e942011-10-28 01:11:35 +00001700 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001701 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001702
1703 StringExtractorGDBRemote response;
1704 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001705 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001706 {
1707 char packet_cmd = response.GetChar(0);
1708
1709 if (packet_cmd == 'W' || packet_cmd == 'X')
1710 {
Greg Clayton06709002011-12-06 04:51:14 +00001711 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001712 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001713 exit_status = response.GetHexU8();
1714 }
1715 else
1716 {
1717 if (log)
1718 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1719 exit_string.assign("got unexpected response to k packet: ");
1720 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001721 }
1722 }
1723 else
1724 {
Jim Ingham8247e622012-06-06 00:32:39 +00001725 if (log)
1726 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1727 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001728 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001729 }
Jim Ingham8247e622012-06-06 00:32:39 +00001730 else
1731 {
1732 if (log)
1733 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1734 exit_string.assign ("killing while attaching.");
1735 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001736 }
Jim Ingham8247e622012-06-06 00:32:39 +00001737 else
1738 {
1739 // If we missed setting the exit status on the way out, do it here.
1740 // NB set exit status can be called multiple times, the first one sets the status.
1741 exit_string.assign("destroying when not connected to debugserver");
1742 }
1743
1744 SetExitStatus(exit_status, exit_string.c_str());
1745
Chris Lattner24943d22010-06-08 16:52:24 +00001746 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001747 KillDebugserverProcess ();
1748 return error;
1749}
1750
Chris Lattner24943d22010-06-08 16:52:24 +00001751//------------------------------------------------------------------
1752// Process Queries
1753//------------------------------------------------------------------
1754
1755bool
1756ProcessGDBRemote::IsAlive ()
1757{
Greg Clayton58e844b2010-12-08 05:08:21 +00001758 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001759}
1760
1761addr_t
1762ProcessGDBRemote::GetImageInfoAddress()
1763{
Greg Clayton516f0842012-04-11 00:24:49 +00001764 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001765}
1766
Chris Lattner24943d22010-06-08 16:52:24 +00001767//------------------------------------------------------------------
1768// Process Memory
1769//------------------------------------------------------------------
1770size_t
1771ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1772{
1773 if (size > m_max_memory_size)
1774 {
1775 // Keep memory read sizes down to a sane limit. This function will be
1776 // called multiple times in order to complete the task by
1777 // lldb_private::Process so it is ok to do this.
1778 size = m_max_memory_size;
1779 }
1780
1781 char packet[64];
1782 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1783 assert (packet_len + 1 < sizeof(packet));
1784 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001785 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001786 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001787 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001788 {
1789 error.Clear();
1790 return response.GetHexBytes(buf, size, '\xdd');
1791 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001792 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001793 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001794 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001795 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1796 else
1797 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1798 }
1799 else
1800 {
1801 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1802 }
1803 return 0;
1804}
1805
1806size_t
1807ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1808{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001809 if (size > m_max_memory_size)
1810 {
1811 // Keep memory read sizes down to a sane limit. This function will be
1812 // called multiple times in order to complete the task by
1813 // lldb_private::Process so it is ok to do this.
1814 size = m_max_memory_size;
1815 }
1816
Chris Lattner24943d22010-06-08 16:52:24 +00001817 StreamString packet;
1818 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001819 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001820 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001821 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001822 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001823 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001824 {
1825 error.Clear();
1826 return size;
1827 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001828 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001829 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001830 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001831 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1832 else
1833 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1834 }
1835 else
1836 {
1837 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1838 }
1839 return 0;
1840}
1841
1842lldb::addr_t
1843ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1844{
Greg Clayton989816b2011-05-14 01:50:35 +00001845 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1846
Greg Clayton2f085c62011-05-15 01:25:55 +00001847 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001848 switch (supported)
1849 {
1850 case eLazyBoolCalculate:
1851 case eLazyBoolYes:
1852 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1853 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1854 return allocated_addr;
1855
1856 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001857 // Call mmap() to create memory in the inferior..
1858 unsigned prot = 0;
1859 if (permissions & lldb::ePermissionsReadable)
1860 prot |= eMmapProtRead;
1861 if (permissions & lldb::ePermissionsWritable)
1862 prot |= eMmapProtWrite;
1863 if (permissions & lldb::ePermissionsExecutable)
1864 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001865
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001866 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1867 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1868 m_addr_to_mmap_size[allocated_addr] = size;
1869 else
1870 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001871 break;
1872 }
1873
Chris Lattner24943d22010-06-08 16:52:24 +00001874 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001875 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001876 else
1877 error.Clear();
1878 return allocated_addr;
1879}
1880
1881Error
Greg Claytona9385532011-11-18 07:03:08 +00001882ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1883 MemoryRegionInfo &region_info)
1884{
1885
1886 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1887 return error;
1888}
1889
1890Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00001891ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
1892{
1893
1894 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
1895 return error;
1896}
1897
1898Error
Chris Lattner24943d22010-06-08 16:52:24 +00001899ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1900{
1901 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001902 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1903
1904 switch (supported)
1905 {
1906 case eLazyBoolCalculate:
1907 // We should never be deallocating memory without allocating memory
1908 // first so we should never get eLazyBoolCalculate
1909 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1910 break;
1911
1912 case eLazyBoolYes:
1913 if (!m_gdb_comm.DeallocateMemory (addr))
1914 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1915 break;
1916
1917 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001918 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001919 {
1920 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001921 if (pos != m_addr_to_mmap_size.end() &&
1922 InferiorCallMunmap(this, addr, pos->second))
1923 m_addr_to_mmap_size.erase (pos);
1924 else
1925 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001926 }
1927 break;
1928 }
1929
Chris Lattner24943d22010-06-08 16:52:24 +00001930 return error;
1931}
1932
1933
1934//------------------------------------------------------------------
1935// Process STDIO
1936//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001937size_t
1938ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1939{
1940 if (m_stdio_communication.IsConnected())
1941 {
1942 ConnectionStatus status;
1943 m_stdio_communication.Write(src, src_len, status, NULL);
1944 }
1945 return 0;
1946}
1947
1948Error
1949ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1950{
1951 Error error;
1952 assert (bp_site != NULL);
1953
Greg Claytone005f2c2010-11-06 01:53:30 +00001954 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001955 user_id_t site_id = bp_site->GetID();
1956 const addr_t addr = bp_site->GetLoadAddress();
1957 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001958 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001959
1960 if (bp_site->IsEnabled())
1961 {
1962 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001963 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 +00001964 return error;
1965 }
1966 else
1967 {
1968 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1969
1970 if (bp_site->HardwarePreferred())
1971 {
1972 // Try and set hardware breakpoint, and if that fails, fall through
1973 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001974 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001975 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001976 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001977 {
1978 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001979 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001980 return error;
1981 }
Chris Lattner24943d22010-06-08 16:52:24 +00001982 }
1983 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001984
1985 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001986 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001987 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1988 {
1989 bp_site->SetEnabled(true);
1990 bp_site->SetType (BreakpointSite::eExternal);
1991 return error;
1992 }
Chris Lattner24943d22010-06-08 16:52:24 +00001993 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001994
1995 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001996 }
1997
1998 if (log)
1999 {
2000 const char *err_string = error.AsCString();
2001 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2002 bp_site->GetLoadAddress(),
2003 err_string ? err_string : "NULL");
2004 }
2005 // We shouldn't reach here on a successful breakpoint enable...
2006 if (error.Success())
2007 error.SetErrorToGenericError();
2008 return error;
2009}
2010
2011Error
2012ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2013{
2014 Error error;
2015 assert (bp_site != NULL);
2016 addr_t addr = bp_site->GetLoadAddress();
2017 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002018 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002019 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002020 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002021
2022 if (bp_site->IsEnabled())
2023 {
2024 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2025
Greg Claytonb72d0f02011-04-12 05:54:46 +00002026 BreakpointSite::Type bp_type = bp_site->GetType();
2027 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002028 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002029 case BreakpointSite::eSoftware:
2030 error = DisableSoftwareBreakpoint (bp_site);
2031 break;
2032
2033 case BreakpointSite::eHardware:
2034 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2035 error.SetErrorToGenericError();
2036 break;
2037
2038 case BreakpointSite::eExternal:
2039 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2040 error.SetErrorToGenericError();
2041 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002042 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002043 if (error.Success())
2044 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002045 }
2046 else
2047 {
2048 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002049 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 +00002050 return error;
2051 }
2052
2053 if (error.Success())
2054 error.SetErrorToGenericError();
2055 return error;
2056}
2057
Johnny Chen21900fb2011-09-06 22:38:36 +00002058// Pre-requisite: wp != NULL.
2059static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002060GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002061{
2062 assert(wp);
2063 bool watch_read = wp->WatchpointRead();
2064 bool watch_write = wp->WatchpointWrite();
2065
2066 // watch_read and watch_write cannot both be false.
2067 assert(watch_read || watch_write);
2068 if (watch_read && watch_write)
2069 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002070 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002071 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002072 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002073 return eWatchpointWrite;
2074}
2075
Chris Lattner24943d22010-06-08 16:52:24 +00002076Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002077ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002078{
2079 Error error;
2080 if (wp)
2081 {
2082 user_id_t watchID = wp->GetID();
2083 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002084 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002085 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002086 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002087 if (wp->IsEnabled())
2088 {
2089 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002090 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002091 return error;
2092 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002093
2094 GDBStoppointType type = GetGDBStoppointType(wp);
2095 // Pass down an appropriate z/Z packet...
2096 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002097 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002098 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2099 {
2100 wp->SetEnabled(true);
2101 return error;
2102 }
2103 else
2104 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002105 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002106 else
2107 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002108 }
2109 else
2110 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002111 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002112 }
2113 if (error.Success())
2114 error.SetErrorToGenericError();
2115 return error;
2116}
2117
2118Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002119ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002120{
2121 Error error;
2122 if (wp)
2123 {
2124 user_id_t watchID = wp->GetID();
2125
Greg Claytone005f2c2010-11-06 01:53:30 +00002126 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002127
2128 addr_t addr = wp->GetLoadAddress();
2129 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002130 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002131
Johnny Chen21900fb2011-09-06 22:38:36 +00002132 if (!wp->IsEnabled())
2133 {
2134 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002135 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002136 return error;
2137 }
2138
Chris Lattner24943d22010-06-08 16:52:24 +00002139 if (wp->IsHardware())
2140 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002141 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002142 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002143 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2144 {
2145 wp->SetEnabled(false);
2146 return error;
2147 }
2148 else
2149 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002150 }
2151 // TODO: clear software watchpoints if we implement them
2152 }
2153 else
2154 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002155 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002156 }
2157 if (error.Success())
2158 error.SetErrorToGenericError();
2159 return error;
2160}
2161
2162void
2163ProcessGDBRemote::Clear()
2164{
2165 m_flags = 0;
2166 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002167}
2168
2169Error
2170ProcessGDBRemote::DoSignal (int signo)
2171{
2172 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002173 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002174 if (log)
2175 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2176
2177 if (!m_gdb_comm.SendAsyncSignal (signo))
2178 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2179 return error;
2180}
2181
Chris Lattner24943d22010-06-08 16:52:24 +00002182Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002183ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2184{
2185 ProcessLaunchInfo launch_info;
2186 return StartDebugserverProcess(debugserver_url, launch_info);
2187}
2188
2189Error
2190ProcessGDBRemote::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 +00002191{
2192 Error error;
2193 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2194 {
2195 // If we locate debugserver, keep that located version around
2196 static FileSpec g_debugserver_file_spec;
2197
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002198 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002199 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002200 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002201
2202 // Always check to see if we have an environment override for the path
2203 // to the debugserver to use and use it if we do.
2204 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2205 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002206 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002207 else
2208 debugserver_file_spec = g_debugserver_file_spec;
2209 bool debugserver_exists = debugserver_file_spec.Exists();
2210 if (!debugserver_exists)
2211 {
2212 // The debugserver binary is in the LLDB.framework/Resources
2213 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002214 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002215 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002216 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002217 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002218 if (debugserver_exists)
2219 {
2220 g_debugserver_file_spec = debugserver_file_spec;
2221 }
2222 else
2223 {
2224 g_debugserver_file_spec.Clear();
2225 debugserver_file_spec.Clear();
2226 }
Chris Lattner24943d22010-06-08 16:52:24 +00002227 }
2228 }
2229
2230 if (debugserver_exists)
2231 {
2232 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2233
2234 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002235
Greg Claytone005f2c2010-11-06 01:53:30 +00002236 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002237
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002238 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002239 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002240
Chris Lattner24943d22010-06-08 16:52:24 +00002241 // Start args with "debugserver /file/path -r --"
2242 debugserver_args.AppendArgument(debugserver_path);
2243 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002244 // use native registers, not the GDB registers
2245 debugserver_args.AppendArgument("--native-regs");
2246 // make debugserver run in its own session so signals generated by
2247 // special terminal key sequences (^C) don't affect debugserver
2248 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002249
Chris Lattner24943d22010-06-08 16:52:24 +00002250 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2251 if (env_debugserver_log_file)
2252 {
2253 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2254 debugserver_args.AppendArgument(arg_cstr);
2255 }
2256
2257 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2258 if (env_debugserver_log_flags)
2259 {
2260 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2261 debugserver_args.AppendArgument(arg_cstr);
2262 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002263// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002264// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002265
Greg Claytonb72d0f02011-04-12 05:54:46 +00002266 // We currently send down all arguments, attach pids, or attach
2267 // process names in dedicated GDB server packets, so we don't need
2268 // to pass them as arguments. This is currently because of all the
2269 // things we need to setup prior to launching: the environment,
2270 // current working dir, file actions, etc.
2271#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002272 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002273 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002274 {
Greg Claytona2f74232011-02-24 22:24:29 +00002275 // Terminate the debugserver args so we can now append the inferior args
2276 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002277
Greg Claytona2f74232011-02-24 22:24:29 +00002278 for (int i = 0; inferior_argv[i] != NULL; ++i)
2279 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002280 }
2281 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2282 {
2283 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2284 debugserver_args.AppendArgument (arg_cstr);
2285 }
2286 else if (attach_name && attach_name[0])
2287 {
2288 if (wait_for_launch)
2289 debugserver_args.AppendArgument ("--waitfor");
2290 else
2291 debugserver_args.AppendArgument ("--attach");
2292 debugserver_args.AppendArgument (attach_name);
2293 }
Chris Lattner24943d22010-06-08 16:52:24 +00002294#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002295
2296 ProcessLaunchInfo::FileAction file_action;
2297
2298 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2299 // to "/dev/null" if we run into any problems.
2300 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002301 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002302 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002303 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002304 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002305 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002306
2307 if (log)
2308 {
2309 StreamString strm;
2310 debugserver_args.Dump (&strm);
2311 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2312 }
2313
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002314 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2315 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002316
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002317 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002318
Greg Claytonb72d0f02011-04-12 05:54:46 +00002319 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002320 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002321 else
Chris Lattner24943d22010-06-08 16:52:24 +00002322 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2323
2324 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002325 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002326 }
2327 else
2328 {
Greg Clayton9c236732011-10-26 00:56:27 +00002329 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002330 }
2331
2332 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2333 StartAsyncThread ();
2334 }
2335 return error;
2336}
2337
2338bool
2339ProcessGDBRemote::MonitorDebugserverProcess
2340(
2341 void *callback_baton,
2342 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002343 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002344 int signo, // Zero for no signal
2345 int exit_status // Exit value of process if signal is zero
2346)
2347{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002348 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2349 // and might not exist anymore, so we need to carefully try to get the
2350 // target for this process first since we have a race condition when
2351 // we are done running between getting the notice that the inferior
2352 // process has died and the debugserver that was debugging this process.
2353 // In our test suite, we are also continually running process after
2354 // process, so we must be very careful to make sure:
2355 // 1 - process object hasn't been deleted already
2356 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002357
2358 // "debugserver_pid" argument passed in is the process ID for
2359 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002360 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002361
Greg Clayton75ccf502010-08-21 02:22:51 +00002362 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002363
Greg Clayton1c4642c2011-11-16 05:37:56 +00002364 // Get a shared pointer to the target that has a matching process pointer.
2365 // This target could be gone, or the target could already have a new process
2366 // object inside of it
2367 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2368
Greg Clayton72e1c782011-01-22 23:43:18 +00002369 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002370 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 +00002371
Greg Clayton1c4642c2011-11-16 05:37:56 +00002372 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002373 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002374 // We found a process in a target that matches, but another thread
2375 // might be in the process of launching a new process that will
2376 // soon replace it, so get a shared pointer to the process so we
2377 // can keep it alive.
2378 ProcessSP process_sp (target_sp->GetProcessSP());
2379 // Now we have a shared pointer to the process that can't go away on us
2380 // so we now make sure it was the same as the one passed in, and also make
2381 // sure that our previous "process *" didn't get deleted and have a new
2382 // "process *" created in its place with the same pointer. To verify this
2383 // we make sure the process has our debugserver process ID. If we pass all
2384 // of these tests, then we are sure that this process is the one we were
2385 // looking for.
2386 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002387 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002388 // Sleep for a half a second to make sure our inferior process has
2389 // time to set its exit status before we set it incorrectly when
2390 // both the debugserver and the inferior process shut down.
2391 usleep (500000);
2392 // If our process hasn't yet exited, debugserver might have died.
2393 // If the process did exit, the we are reaping it.
2394 const StateType state = process->GetState();
2395
2396 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2397 state != eStateInvalid &&
2398 state != eStateUnloaded &&
2399 state != eStateExited &&
2400 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002401 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002402 char error_str[1024];
2403 if (signo)
2404 {
2405 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2406 if (signal_cstr)
2407 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2408 else
2409 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2410 }
Chris Lattner24943d22010-06-08 16:52:24 +00002411 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002412 {
2413 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2414 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002415
Greg Clayton1c4642c2011-11-16 05:37:56 +00002416 process->SetExitStatus (-1, error_str);
2417 }
2418 // Debugserver has exited we need to let our ProcessGDBRemote
2419 // know that it no longer has a debugserver instance
2420 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002421 }
Chris Lattner24943d22010-06-08 16:52:24 +00002422 }
2423 return true;
2424}
2425
2426void
2427ProcessGDBRemote::KillDebugserverProcess ()
2428{
2429 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2430 {
2431 ::kill (m_debugserver_pid, SIGINT);
2432 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2433 }
2434}
2435
2436void
2437ProcessGDBRemote::Initialize()
2438{
2439 static bool g_initialized = false;
2440
2441 if (g_initialized == false)
2442 {
2443 g_initialized = true;
2444 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2445 GetPluginDescriptionStatic(),
2446 CreateInstance);
2447
2448 Log::Callbacks log_callbacks = {
2449 ProcessGDBRemoteLog::DisableLog,
2450 ProcessGDBRemoteLog::EnableLog,
2451 ProcessGDBRemoteLog::ListLogCategories
2452 };
2453
2454 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2455 }
2456}
2457
2458bool
Chris Lattner24943d22010-06-08 16:52:24 +00002459ProcessGDBRemote::StartAsyncThread ()
2460{
Greg Claytone005f2c2010-11-06 01:53:30 +00002461 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002462
2463 if (log)
2464 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2465
2466 // Create a thread that watches our internal state and controls which
2467 // events make it to clients (into the DCProcess event queue).
2468 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002469 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002470}
2471
2472void
2473ProcessGDBRemote::StopAsyncThread ()
2474{
Greg Claytone005f2c2010-11-06 01:53:30 +00002475 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002476
2477 if (log)
2478 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2479
2480 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002481
2482 // This will shut down the async thread.
2483 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002484
2485 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002486 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002487 {
2488 Host::ThreadJoin (m_async_thread, NULL, NULL);
2489 }
2490}
2491
2492
2493void *
2494ProcessGDBRemote::AsyncThread (void *arg)
2495{
2496 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2497
Greg Claytone005f2c2010-11-06 01:53:30 +00002498 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002499 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002500 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002501
2502 Listener listener ("ProcessGDBRemote::AsyncThread");
2503 EventSP event_sp;
2504 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2505 eBroadcastBitAsyncThreadShouldExit;
2506
2507 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2508 {
Greg Claytona2f74232011-02-24 22:24:29 +00002509 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2510
Chris Lattner24943d22010-06-08 16:52:24 +00002511 bool done = false;
2512 while (!done)
2513 {
2514 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002515 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002516 if (listener.WaitForEvent (NULL, event_sp))
2517 {
2518 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002519 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002520 {
Greg Claytona2f74232011-02-24 22:24:29 +00002521 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002522 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 +00002523
Greg Claytona2f74232011-02-24 22:24:29 +00002524 switch (event_type)
2525 {
2526 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002527 {
Greg Claytona2f74232011-02-24 22:24:29 +00002528 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002529
Greg Claytona2f74232011-02-24 22:24:29 +00002530 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002531 {
Greg Claytona2f74232011-02-24 22:24:29 +00002532 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2533 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2534 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002535 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002536
Greg Claytona2f74232011-02-24 22:24:29 +00002537 if (::strstr (continue_cstr, "vAttach") == NULL)
2538 process->SetPrivateState(eStateRunning);
2539 StringExtractorGDBRemote response;
2540 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002541
Greg Clayton67b402c2012-05-16 02:48:06 +00002542 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2543 // The thread ID list might be contained within the "response", or the stop reply packet that
2544 // caused the stop. So clear it now before we give the stop reply packet to the process
2545 // using the process->SetLastStopPacket()...
2546 process->ClearThreadIDList ();
2547
Greg Claytona2f74232011-02-24 22:24:29 +00002548 switch (stop_state)
2549 {
2550 case eStateStopped:
2551 case eStateCrashed:
2552 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002553 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002554 process->SetPrivateState (stop_state);
2555 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002556
Greg Claytona2f74232011-02-24 22:24:29 +00002557 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002558 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002559 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002560 response.SetFilePos(1);
2561 process->SetExitStatus(response.GetHexU8(), NULL);
2562 done = true;
2563 break;
2564
2565 case eStateInvalid:
2566 process->SetExitStatus(-1, "lost connection");
2567 break;
2568
2569 default:
2570 process->SetPrivateState (stop_state);
2571 break;
2572 }
Chris Lattner24943d22010-06-08 16:52:24 +00002573 }
2574 }
Greg Claytona2f74232011-02-24 22:24:29 +00002575 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002576
Greg Claytona2f74232011-02-24 22:24:29 +00002577 case eBroadcastBitAsyncThreadShouldExit:
2578 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002579 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002580 done = true;
2581 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002582
Greg Claytona2f74232011-02-24 22:24:29 +00002583 default:
2584 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002585 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 +00002586 done = true;
2587 break;
2588 }
2589 }
2590 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2591 {
2592 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2593 {
2594 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002595 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002596 }
Chris Lattner24943d22010-06-08 16:52:24 +00002597 }
2598 }
2599 else
2600 {
2601 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002602 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 +00002603 done = true;
2604 }
2605 }
2606 }
2607
2608 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002609 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002610
2611 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2612 return NULL;
2613}
2614
Chris Lattner24943d22010-06-08 16:52:24 +00002615const char *
2616ProcessGDBRemote::GetDispatchQueueNameForThread
2617(
2618 addr_t thread_dispatch_qaddr,
2619 std::string &dispatch_queue_name
2620)
2621{
2622 dispatch_queue_name.clear();
2623 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2624 {
2625 // Cache the dispatch_queue_offsets_addr value so we don't always have
2626 // to look it up
2627 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2628 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002629 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2630 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002631 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2632 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002633 if (module_sp)
2634 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2635
2636 if (dispatch_queue_offsets_symbol == NULL)
2637 {
Greg Clayton444fe992012-02-26 05:51:37 +00002638 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2639 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002640 if (module_sp)
2641 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2642 }
Chris Lattner24943d22010-06-08 16:52:24 +00002643 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002644 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002645
2646 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2647 return NULL;
2648 }
2649
2650 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002651 DataExtractor data (memory_buffer,
2652 sizeof(memory_buffer),
2653 m_target.GetArchitecture().GetByteOrder(),
2654 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002655
2656 // Excerpt from src/queue_private.h
2657 struct dispatch_queue_offsets_s
2658 {
2659 uint16_t dqo_version;
2660 uint16_t dqo_label;
2661 uint16_t dqo_label_size;
2662 } dispatch_queue_offsets;
2663
2664
2665 Error error;
2666 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2667 {
2668 uint32_t data_offset = 0;
2669 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2670 {
2671 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2672 {
2673 data_offset = 0;
2674 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2675 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2676 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2677 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2678 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2679 dispatch_queue_name.erase (bytes_read);
2680 }
2681 }
2682 }
2683 }
2684 if (dispatch_queue_name.empty())
2685 return NULL;
2686 return dispatch_queue_name.c_str();
2687}
2688
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002689//uint32_t
2690//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2691//{
2692// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2693// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2694// if (m_local_debugserver)
2695// {
2696// return Host::ListProcessesMatchingName (name, matches, pids);
2697// }
2698// else
2699// {
2700// // FIXME: Implement talking to the remote debugserver.
2701// return 0;
2702// }
2703//
2704//}
2705//
Jim Ingham55e01d82011-01-22 01:33:44 +00002706bool
2707ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2708 lldb_private::StoppointCallbackContext *context,
2709 lldb::user_id_t break_id,
2710 lldb::user_id_t break_loc_id)
2711{
2712 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2713 // run so I can stop it if that's what I want to do.
2714 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2715 if (log)
2716 log->Printf("Hit New Thread Notification breakpoint.");
2717 return false;
2718}
2719
2720
2721bool
2722ProcessGDBRemote::StartNoticingNewThreads()
2723{
Jim Ingham55e01d82011-01-22 01:33:44 +00002724 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002725 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002726 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002727 if (log && log->GetVerbose())
2728 log->Printf("Enabled noticing new thread breakpoint.");
2729 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002730 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002731 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002732 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002733 PlatformSP platform_sp (m_target.GetPlatform());
2734 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002735 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002736 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2737 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002738 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002739 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002740 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2741 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002742 }
2743 else
2744 {
2745 if (log)
2746 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002747 }
2748 }
2749 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002750 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002751}
2752
2753bool
2754ProcessGDBRemote::StopNoticingNewThreads()
2755{
Jim Inghamff276fe2011-02-08 05:19:01 +00002756 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002757 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002758 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002759
2760 if (m_thread_create_bp_sp)
2761 m_thread_create_bp_sp->SetEnabled(false);
2762
Jim Ingham55e01d82011-01-22 01:33:44 +00002763 return true;
2764}
2765
2766