blob: 91a3af7c38afbf879fe06ea98c22c945d092c63c [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 }
73};
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),
Jim Ingham7508e732010-08-09 23:31:02 +0000176 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000177 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000178{
Greg Claytonff39f742011-04-01 00:29:43 +0000179 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
180 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000181 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000182}
183
184//----------------------------------------------------------------------
185// Destructor
186//----------------------------------------------------------------------
187ProcessGDBRemote::~ProcessGDBRemote()
188{
189 // m_mach_process.UnregisterNotificationCallbacks (this);
190 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000191 // We need to call finalize on the process before destroying ourselves
192 // to make sure all of the broadcaster cleanup goes as planned. If we
193 // destruct this class, then Process::~Process() might have problems
194 // trying to fully destroy the broadcaster.
195 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000196}
197
198//----------------------------------------------------------------------
199// PluginInterface
200//----------------------------------------------------------------------
201const char *
202ProcessGDBRemote::GetPluginName()
203{
204 return "Process debugging plug-in that uses the GDB remote protocol";
205}
206
207const char *
208ProcessGDBRemote::GetShortPluginName()
209{
210 return GetPluginNameStatic();
211}
212
213uint32_t
214ProcessGDBRemote::GetPluginVersion()
215{
216 return 1;
217}
218
219void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000220ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000221{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000222 if (!force && m_register_info.GetNumRegisters() > 0)
223 return;
224
225 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000226 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000227 uint32_t reg_offset = 0;
228 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000229 StringExtractorGDBRemote::ResponseType response_type;
230 for (response_type = StringExtractorGDBRemote::eResponse;
231 response_type == StringExtractorGDBRemote::eResponse;
232 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000233 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000234 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
235 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000236 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000237 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000238 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000239 response_type = response.GetResponseType();
240 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000241 {
242 std::string name;
243 std::string value;
244 ConstString reg_name;
245 ConstString alt_name;
246 ConstString set_name;
247 RegisterInfo reg_info = { NULL, // Name
248 NULL, // Alt name
249 0, // byte size
250 reg_offset, // offset
251 eEncodingUint, // encoding
252 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000253 {
254 LLDB_INVALID_REGNUM, // GCC reg num
255 LLDB_INVALID_REGNUM, // DWARF reg num
256 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000257 reg_num, // GDB reg num
258 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000259 },
260 NULL,
261 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000262 };
263
264 while (response.GetNameColonValue(name, value))
265 {
266 if (name.compare("name") == 0)
267 {
268 reg_name.SetCString(value.c_str());
269 }
270 else if (name.compare("alt-name") == 0)
271 {
272 alt_name.SetCString(value.c_str());
273 }
274 else if (name.compare("bitsize") == 0)
275 {
276 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
277 }
278 else if (name.compare("offset") == 0)
279 {
280 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000281 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000282 {
283 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000284 }
285 }
286 else if (name.compare("encoding") == 0)
287 {
288 if (value.compare("uint") == 0)
289 reg_info.encoding = eEncodingUint;
290 else if (value.compare("sint") == 0)
291 reg_info.encoding = eEncodingSint;
292 else if (value.compare("ieee754") == 0)
293 reg_info.encoding = eEncodingIEEE754;
294 else if (value.compare("vector") == 0)
295 reg_info.encoding = eEncodingVector;
296 }
297 else if (name.compare("format") == 0)
298 {
299 if (value.compare("binary") == 0)
300 reg_info.format = eFormatBinary;
301 else if (value.compare("decimal") == 0)
302 reg_info.format = eFormatDecimal;
303 else if (value.compare("hex") == 0)
304 reg_info.format = eFormatHex;
305 else if (value.compare("float") == 0)
306 reg_info.format = eFormatFloat;
307 else if (value.compare("vector-sint8") == 0)
308 reg_info.format = eFormatVectorOfSInt8;
309 else if (value.compare("vector-uint8") == 0)
310 reg_info.format = eFormatVectorOfUInt8;
311 else if (value.compare("vector-sint16") == 0)
312 reg_info.format = eFormatVectorOfSInt16;
313 else if (value.compare("vector-uint16") == 0)
314 reg_info.format = eFormatVectorOfUInt16;
315 else if (value.compare("vector-sint32") == 0)
316 reg_info.format = eFormatVectorOfSInt32;
317 else if (value.compare("vector-uint32") == 0)
318 reg_info.format = eFormatVectorOfUInt32;
319 else if (value.compare("vector-float32") == 0)
320 reg_info.format = eFormatVectorOfFloat32;
321 else if (value.compare("vector-uint128") == 0)
322 reg_info.format = eFormatVectorOfUInt128;
323 }
324 else if (name.compare("set") == 0)
325 {
326 set_name.SetCString(value.c_str());
327 }
328 else if (name.compare("gcc") == 0)
329 {
330 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
331 }
332 else if (name.compare("dwarf") == 0)
333 {
334 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
335 }
336 else if (name.compare("generic") == 0)
337 {
338 if (value.compare("pc") == 0)
339 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
340 else if (value.compare("sp") == 0)
341 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
342 else if (value.compare("fp") == 0)
343 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
344 else if (value.compare("ra") == 0)
345 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
346 else if (value.compare("flags") == 0)
347 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000348 else if (value.find("arg") == 0)
349 {
350 if (value.size() == 4)
351 {
352 switch (value[3])
353 {
354 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
355 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
356 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
357 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
358 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
359 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
360 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
361 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
362 }
363 }
364 }
Chris Lattner24943d22010-06-08 16:52:24 +0000365 }
366 }
367
Jason Molenda53d96862010-06-11 23:44:18 +0000368 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000369 assert (reg_info.byte_size != 0);
370 reg_offset += reg_info.byte_size;
371 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
372 }
373 }
374 else
375 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000376 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000377 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000378 }
379 }
380
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000381 // We didn't get anything if the accumulated reg_num is zero. See if we are
382 // debugging ARM and fill with a hard coded register set until we can get an
383 // updated debugserver down on the devices.
384 // On the other hand, if the accumulated reg_num is positive, see if we can
385 // add composite registers to the existing primordial ones.
386 bool from_scratch = (reg_num == 0);
387
388 const ArchSpec &target_arch = GetTarget().GetArchitecture();
389 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
390 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000391 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000392 if (remote_arch.IsValid()
393 && remote_arch.GetMachine() == llvm::Triple::arm
394 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
395 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000396 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000397 else if (target_arch.GetMachine() == llvm::Triple::arm)
398 {
399 m_register_info.HardcodeARMRegisters(from_scratch);
400 }
401
402 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000403 m_register_info.Finalize ();
404}
405
406Error
407ProcessGDBRemote::WillLaunch (Module* module)
408{
409 return WillLaunchOrAttach ();
410}
411
412Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000413ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000414{
415 return WillLaunchOrAttach ();
416}
417
418Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000419ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000420{
421 return WillLaunchOrAttach ();
422}
423
424Error
Greg Claytone71e2582011-02-04 01:58:07 +0000425ProcessGDBRemote::DoConnectRemote (const char *remote_url)
426{
427 Error error (WillLaunchOrAttach ());
428
429 if (error.Fail())
430 return error;
431
Greg Clayton180546b2011-04-30 01:09:13 +0000432 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000433
434 if (error.Fail())
435 return error;
436 StartAsyncThread ();
437
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000438 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000439 if (pid == LLDB_INVALID_PROCESS_ID)
440 {
441 // We don't have a valid process ID, so note that we are connected
442 // and could now request to launch or attach, or get remote process
443 // listings...
444 SetPrivateState (eStateConnected);
445 }
446 else
447 {
448 // We have a valid process
449 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000450 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000451 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000452 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000453 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000454 if (state == eStateStopped)
455 {
456 SetPrivateState (state);
457 }
458 else
Greg Claytond9919d32011-12-01 23:28:38 +0000459 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 +0000460 }
461 else
Greg Claytond9919d32011-12-01 23:28:38 +0000462 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 +0000463 }
Jason Molendacb740b32012-05-03 22:37:30 +0000464
465 if (error.Success()
466 && !GetTarget().GetArchitecture().IsValid()
467 && m_gdb_comm.GetHostArchitecture().IsValid())
468 {
469 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
470 }
471
Greg Claytone71e2582011-02-04 01:58:07 +0000472 return error;
473}
474
475Error
Chris Lattner24943d22010-06-08 16:52:24 +0000476ProcessGDBRemote::WillLaunchOrAttach ()
477{
478 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000479 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000480 return error;
481}
482
483//----------------------------------------------------------------------
484// Process Control
485//----------------------------------------------------------------------
486Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000487ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000488{
Greg Clayton4b407112010-09-30 21:49:03 +0000489 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000490
491 uint32_t launch_flags = launch_info.GetFlags().Get();
492 const char *stdin_path = NULL;
493 const char *stdout_path = NULL;
494 const char *stderr_path = NULL;
495 const char *working_dir = launch_info.GetWorkingDirectory();
496
497 const ProcessLaunchInfo::FileAction *file_action;
498 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
499 if (file_action)
500 {
501 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
502 stdin_path = file_action->GetPath();
503 }
504 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
505 if (file_action)
506 {
507 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
508 stdout_path = file_action->GetPath();
509 }
510 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
511 if (file_action)
512 {
513 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
514 stderr_path = file_action->GetPath();
515 }
516
Chris Lattner24943d22010-06-08 16:52:24 +0000517 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
518 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
519 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000520 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000521
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000522 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000523 if (object_file)
524 {
Chris Lattner24943d22010-06-08 16:52:24 +0000525 char host_port[128];
526 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000527 char connect_url[128];
528 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000529
Greg Claytona2f74232011-02-24 22:24:29 +0000530 // Make sure we aren't already connected?
531 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000532 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000533 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000534 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000535 {
Johnny Chenc143d622011-08-09 18:56:45 +0000536 if (log)
537 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000538 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000539 }
Chris Lattner24943d22010-06-08 16:52:24 +0000540
Greg Claytone71e2582011-02-04 01:58:07 +0000541 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000542 }
543
544 if (error.Success())
545 {
546 lldb_utility::PseudoTerminal pty;
547 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000548
549 // If the debugserver is local and we aren't disabling STDIO, lets use
550 // a pseudo terminal to instead of relying on the 'O' packets for stdio
551 // since 'O' packets can really slow down debugging if the inferior
552 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000553 PlatformSP platform_sp (m_target.GetPlatform());
554 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000555 {
556 const char *slave_name = NULL;
557 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000558 {
Greg Claytona2f74232011-02-24 22:24:29 +0000559 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
560 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000561 }
Greg Claytona2f74232011-02-24 22:24:29 +0000562 if (stdin_path == NULL)
563 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000564
Greg Claytona2f74232011-02-24 22:24:29 +0000565 if (stdout_path == NULL)
566 stdout_path = slave_name;
567
568 if (stderr_path == NULL)
569 stderr_path = slave_name;
570 }
571
Greg Claytonafb81862011-03-02 21:34:46 +0000572 // Set STDIN to /dev/null if we want STDIO disabled or if either
573 // STDOUT or STDERR have been set to something and STDIN hasn't
574 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000575 stdin_path = "/dev/null";
576
Greg Claytonafb81862011-03-02 21:34:46 +0000577 // Set STDOUT to /dev/null if we want STDIO disabled or if either
578 // STDIN or STDERR have been set to something and STDOUT hasn't
579 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000580 stdout_path = "/dev/null";
581
Greg Claytonafb81862011-03-02 21:34:46 +0000582 // Set STDERR to /dev/null if we want STDIO disabled or if either
583 // STDIN or STDOUT have been set to something and STDERR hasn't
584 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000585 stderr_path = "/dev/null";
586
587 if (stdin_path)
588 m_gdb_comm.SetSTDIN (stdin_path);
589 if (stdout_path)
590 m_gdb_comm.SetSTDOUT (stdout_path);
591 if (stderr_path)
592 m_gdb_comm.SetSTDERR (stderr_path);
593
594 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
595
Greg Claytona4582402011-05-08 04:53:50 +0000596 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000597
598 if (working_dir && working_dir[0])
599 {
600 m_gdb_comm.SetWorkingDir (working_dir);
601 }
602
603 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000604 const Args &environment = launch_info.GetEnvironmentEntries();
605 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000606 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000607 size_t num_environment_entries = environment.GetArgumentCount();
608 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000609 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000610 const char *env_entry = environment.GetArgumentAtIndex(i);
611 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000612 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000613 }
Greg Claytona2f74232011-02-24 22:24:29 +0000614 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000615
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000616 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000617 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000618 if (arg_packet_err == 0)
619 {
620 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000621 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000622 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000623 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000624 }
625 else
626 {
Greg Claytona2f74232011-02-24 22:24:29 +0000627 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000628 }
Greg Claytona2f74232011-02-24 22:24:29 +0000629 }
630 else
631 {
Greg Clayton9c236732011-10-26 00:56:27 +0000632 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000633 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000634
635 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000636
Greg Claytona2f74232011-02-24 22:24:29 +0000637 if (GetID() == LLDB_INVALID_PROCESS_ID)
638 {
Johnny Chenc143d622011-08-09 18:56:45 +0000639 if (log)
640 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000641 KillDebugserverProcess ();
642 return error;
643 }
644
Greg Clayton261a18b2011-06-02 22:22:38 +0000645 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000646 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000647 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000648
649 if (!disable_stdio)
650 {
651 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000652 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000653 }
Chris Lattner24943d22010-06-08 16:52:24 +0000654 }
655 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000656 else
657 {
Johnny Chenc143d622011-08-09 18:56:45 +0000658 if (log)
659 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000660 }
Chris Lattner24943d22010-06-08 16:52:24 +0000661 }
662 else
663 {
664 // Set our user ID to an invalid process ID.
665 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000666 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
667 exe_module->GetFileSpec().GetFilename().AsCString(),
668 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000669 }
Chris Lattner24943d22010-06-08 16:52:24 +0000670 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000671
Chris Lattner24943d22010-06-08 16:52:24 +0000672}
673
674
675Error
Greg Claytone71e2582011-02-04 01:58:07 +0000676ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000677{
678 Error error;
679 // Sleep and wait a bit for debugserver to start to listen...
680 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
681 if (conn_ap.get())
682 {
Chris Lattner24943d22010-06-08 16:52:24 +0000683 const uint32_t max_retry_count = 50;
684 uint32_t retry_count = 0;
685 while (!m_gdb_comm.IsConnected())
686 {
Greg Claytone71e2582011-02-04 01:58:07 +0000687 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000688 {
689 m_gdb_comm.SetConnection (conn_ap.release());
690 break;
691 }
692 retry_count++;
693
694 if (retry_count >= max_retry_count)
695 break;
696
697 usleep (100000);
698 }
699 }
700
701 if (!m_gdb_comm.IsConnected())
702 {
703 if (error.Success())
704 error.SetErrorString("not connected to remote gdb server");
705 return error;
706 }
707
Greg Clayton24bc5d92011-03-30 18:16:51 +0000708 // We always seem to be able to open a connection to a local port
709 // so we need to make sure we can then send data to it. If we can't
710 // then we aren't actually connected to anything, so try and do the
711 // handshake with the remote GDB server and make sure that goes
712 // alright.
713 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000714 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000715 m_gdb_comm.Disconnect();
716 if (error.Success())
717 error.SetErrorString("not connected to remote gdb server");
718 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000719 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000720 m_gdb_comm.ResetDiscoverableSettings();
721 m_gdb_comm.QueryNoAckModeSupported ();
722 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000723 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000724 m_gdb_comm.GetHostInfo ();
725 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000726 return error;
727}
728
729void
730ProcessGDBRemote::DidLaunchOrAttach ()
731{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000732 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
733 if (log)
734 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000735 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000736 {
737 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
738
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000739 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000740
Chris Lattner24943d22010-06-08 16:52:24 +0000741 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000742
Greg Claytoncb8977d2011-03-23 00:09:55 +0000743 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
744 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000745 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000746 ArchSpec &target_arch = GetTarget().GetArchitecture();
747
748 if (target_arch.IsValid())
749 {
750 // If the remote host is ARM and we have apple as the vendor, then
751 // ARM executables and shared libraries can have mixed ARM architectures.
752 // You can have an armv6 executable, and if the host is armv7, then the
753 // system will load the best possible architecture for all shared libraries
754 // it has, so we really need to take the remote host architecture as our
755 // defacto architecture in this case.
756
757 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
758 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
759 {
760 target_arch = gdb_remote_arch;
761 }
762 else
763 {
764 // Fill in what is missing in the triple
765 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
766 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000767 if (target_triple.getVendorName().size() == 0)
768 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000769 target_triple.setVendor (remote_triple.getVendor());
770
Greg Clayton2f085c62011-05-15 01:25:55 +0000771 if (target_triple.getOSName().size() == 0)
772 {
773 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000774
Greg Clayton2f085c62011-05-15 01:25:55 +0000775 if (target_triple.getEnvironmentName().size() == 0)
776 target_triple.setEnvironment (remote_triple.getEnvironment());
777 }
778 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000779 }
780 }
781 else
782 {
783 // The target doesn't have a valid architecture yet, set it from
784 // the architecture we got from the remote GDB server
785 target_arch = gdb_remote_arch;
786 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000787 }
Chris Lattner24943d22010-06-08 16:52:24 +0000788 }
789}
790
791void
792ProcessGDBRemote::DidLaunch ()
793{
794 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000795}
796
797Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000798ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000799{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000800 ProcessAttachInfo attach_info;
801 return DoAttachToProcessWithID(attach_pid, attach_info);
802}
803
804Error
805ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
806{
Chris Lattner24943d22010-06-08 16:52:24 +0000807 Error error;
808 // Clear out and clean up from any current state
809 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000810 if (attach_pid != LLDB_INVALID_PROCESS_ID)
811 {
Greg Claytona2f74232011-02-24 22:24:29 +0000812 // Make sure we aren't already connected?
813 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000814 {
Greg Claytona2f74232011-02-24 22:24:29 +0000815 char host_port[128];
816 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
817 char connect_url[128];
818 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000819
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000820 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000821
822 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000823 {
Greg Claytona2f74232011-02-24 22:24:29 +0000824 const char *error_string = error.AsCString();
825 if (error_string == NULL)
826 error_string = "unable to launch " DEBUGSERVER_BASENAME;
827
828 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000829 }
Greg Claytona2f74232011-02-24 22:24:29 +0000830 else
831 {
832 error = ConnectToDebugserver (connect_url);
833 }
834 }
835
836 if (error.Success())
837 {
838 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000839 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000840 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000841 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000842 }
843 }
Chris Lattner24943d22010-06-08 16:52:24 +0000844 return error;
845}
846
847size_t
848ProcessGDBRemote::AttachInputReaderCallback
849(
850 void *baton,
851 InputReader *reader,
852 lldb::InputReaderAction notification,
853 const char *bytes,
854 size_t bytes_len
855)
856{
857 if (notification == eInputReaderGotToken)
858 {
859 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
860 if (gdb_process->m_waiting_for_attach)
861 gdb_process->m_waiting_for_attach = false;
862 reader->SetIsDone(true);
863 return 1;
864 }
865 return 0;
866}
867
868Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000869ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000870{
871 Error error;
872 // Clear out and clean up from any current state
873 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000874
Chris Lattner24943d22010-06-08 16:52:24 +0000875 if (process_name && process_name[0])
876 {
Greg Claytona2f74232011-02-24 22:24:29 +0000877 // Make sure we aren't already connected?
878 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000879 {
Greg Claytona2f74232011-02-24 22:24:29 +0000880 char host_port[128];
881 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
882 char connect_url[128];
883 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
884
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000885 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000886 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000887 {
Greg Claytona2f74232011-02-24 22:24:29 +0000888 const char *error_string = error.AsCString();
889 if (error_string == NULL)
890 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000891
Greg Claytona2f74232011-02-24 22:24:29 +0000892 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000893 }
Greg Claytona2f74232011-02-24 22:24:29 +0000894 else
895 {
896 error = ConnectToDebugserver (connect_url);
897 }
898 }
899
900 if (error.Success())
901 {
902 StreamString packet;
903
904 if (wait_for_launch)
905 packet.PutCString("vAttachWait");
906 else
907 packet.PutCString("vAttachName");
908 packet.PutChar(';');
909 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
910
911 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
912
Chris Lattner24943d22010-06-08 16:52:24 +0000913 }
914 }
Chris Lattner24943d22010-06-08 16:52:24 +0000915 return error;
916}
917
Chris Lattner24943d22010-06-08 16:52:24 +0000918
919void
920ProcessGDBRemote::DidAttach ()
921{
Greg Claytone71e2582011-02-04 01:58:07 +0000922 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000923}
924
925Error
926ProcessGDBRemote::WillResume ()
927{
Greg Claytonc1f45872011-02-12 06:28:37 +0000928 m_continue_c_tids.clear();
929 m_continue_C_tids.clear();
930 m_continue_s_tids.clear();
931 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000932 return Error();
933}
934
935Error
936ProcessGDBRemote::DoResume ()
937{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000938 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000939 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
940 if (log)
941 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000942
943 Listener listener ("gdb-remote.resume-packet-sent");
944 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
945 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000946 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
947
Greg Claytonc1f45872011-02-12 06:28:37 +0000948 StreamString continue_packet;
949 bool continue_packet_error = false;
950 if (m_gdb_comm.HasAnyVContSupport ())
951 {
952 continue_packet.PutCString ("vCont");
953
954 if (!m_continue_c_tids.empty())
955 {
956 if (m_gdb_comm.GetVContSupported ('c'))
957 {
958 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 +0000959 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000960 }
961 else
962 continue_packet_error = true;
963 }
964
965 if (!continue_packet_error && !m_continue_C_tids.empty())
966 {
967 if (m_gdb_comm.GetVContSupported ('C'))
968 {
969 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 +0000970 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000971 }
972 else
973 continue_packet_error = true;
974 }
Greg Claytonb749a262010-12-03 06:02:24 +0000975
Greg Claytonc1f45872011-02-12 06:28:37 +0000976 if (!continue_packet_error && !m_continue_s_tids.empty())
977 {
978 if (m_gdb_comm.GetVContSupported ('s'))
979 {
980 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 +0000981 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000982 }
983 else
984 continue_packet_error = true;
985 }
986
987 if (!continue_packet_error && !m_continue_S_tids.empty())
988 {
989 if (m_gdb_comm.GetVContSupported ('S'))
990 {
991 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 +0000992 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000993 }
994 else
995 continue_packet_error = true;
996 }
997
998 if (continue_packet_error)
999 continue_packet.GetString().clear();
1000 }
1001 else
1002 continue_packet_error = true;
1003
1004 if (continue_packet_error)
1005 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001006 // Either no vCont support, or we tried to use part of the vCont
1007 // packet that wasn't supported by the remote GDB server.
1008 // We need to try and make a simple packet that can do our continue
1009 const size_t num_threads = GetThreadList().GetSize();
1010 const size_t num_continue_c_tids = m_continue_c_tids.size();
1011 const size_t num_continue_C_tids = m_continue_C_tids.size();
1012 const size_t num_continue_s_tids = m_continue_s_tids.size();
1013 const size_t num_continue_S_tids = m_continue_S_tids.size();
1014 if (num_continue_c_tids > 0)
1015 {
1016 if (num_continue_c_tids == num_threads)
1017 {
1018 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001019 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001020 continue_packet.PutChar ('c');
1021 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001022 }
1023 else if (num_continue_c_tids == 1 &&
1024 num_continue_C_tids == 0 &&
1025 num_continue_s_tids == 0 &&
1026 num_continue_S_tids == 0 )
1027 {
1028 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001029 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001030 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001031 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001032 }
1033 }
1034
Greg Claytonde1dd812011-06-24 03:21:43 +00001035 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001036 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001037 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1038 num_continue_C_tids > 0 &&
1039 num_continue_s_tids == 0 &&
1040 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001041 {
1042 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001043 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001044 if (num_continue_C_tids > 1)
1045 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001046 // More that one thread with a signal, yet we don't have
1047 // vCont support and we are being asked to resume each
1048 // thread with a signal, we need to make sure they are
1049 // all the same signal, or we can't issue the continue
1050 // accurately with the current support...
1051 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001052 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001053 continue_packet_error = false;
1054 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1055 {
1056 if (m_continue_C_tids[i].second != continue_signo)
1057 continue_packet_error = true;
1058 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001059 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001060 if (!continue_packet_error)
1061 m_gdb_comm.SetCurrentThreadForRun (-1);
1062 }
1063 else
1064 {
1065 // Set the continue thread ID
1066 continue_packet_error = false;
1067 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001068 }
1069 if (!continue_packet_error)
1070 {
1071 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001072 continue_packet.Printf("C%2.2x", continue_signo);
1073 }
1074 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001075 }
1076
Greg Claytonde1dd812011-06-24 03:21:43 +00001077 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001078 {
1079 if (num_continue_s_tids == num_threads)
1080 {
1081 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001082 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001083 continue_packet.PutChar ('s');
1084 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001085 }
1086 else if (num_continue_c_tids == 0 &&
1087 num_continue_C_tids == 0 &&
1088 num_continue_s_tids == 1 &&
1089 num_continue_S_tids == 0 )
1090 {
1091 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001092 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001093 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001094 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001095 }
1096 }
1097
1098 if (!continue_packet_error && num_continue_S_tids > 0)
1099 {
1100 if (num_continue_S_tids == num_threads)
1101 {
1102 const int step_signo = m_continue_S_tids.front().second;
1103 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001104 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001105 if (num_continue_S_tids > 1)
1106 {
1107 for (size_t i=1; i<num_threads; ++i)
1108 {
1109 if (m_continue_S_tids[i].second != step_signo)
1110 continue_packet_error = true;
1111 }
1112 }
1113 if (!continue_packet_error)
1114 {
1115 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001116 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001117 continue_packet.Printf("S%2.2x", step_signo);
1118 }
1119 }
1120 else if (num_continue_c_tids == 0 &&
1121 num_continue_C_tids == 0 &&
1122 num_continue_s_tids == 0 &&
1123 num_continue_S_tids == 1 )
1124 {
1125 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001126 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001127 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001128 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001129 }
1130 }
1131 }
1132
1133 if (continue_packet_error)
1134 {
1135 error.SetErrorString ("can't make continue packet for this resume");
1136 }
1137 else
1138 {
1139 EventSP event_sp;
1140 TimeValue timeout;
1141 timeout = TimeValue::Now();
1142 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001143 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1144 {
1145 error.SetErrorString ("Trying to resume but the async thread is dead.");
1146 if (log)
1147 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1148 return error;
1149 }
1150
Greg Claytonc1f45872011-02-12 06:28:37 +00001151 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1152
1153 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001154 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001155 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001156 if (log)
1157 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1158 }
1159 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1160 {
1161 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1162 if (log)
1163 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1164 return error;
1165 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001166 }
Greg Claytonb749a262010-12-03 06:02:24 +00001167 }
1168
Jim Ingham3ae449a2010-11-17 02:32:00 +00001169 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001170}
1171
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001172void
1173ProcessGDBRemote::ClearThreadIDList ()
1174{
Greg Claytonff3448e2012-04-13 02:11:32 +00001175 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001176 m_thread_ids.clear();
1177}
1178
1179bool
1180ProcessGDBRemote::UpdateThreadIDList ()
1181{
Greg Claytonff3448e2012-04-13 02:11:32 +00001182 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001183 bool sequence_mutex_unavailable = false;
1184 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1185 if (sequence_mutex_unavailable)
1186 {
1187#if defined (LLDB_CONFIGURATION_DEBUG)
1188 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1189#endif
1190 return false; // We just didn't get the list
1191 }
1192 return true;
1193}
1194
Greg Claytonae932352012-04-10 00:18:59 +00001195bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001196ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001197{
1198 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001199 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001200 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001201 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001202
1203 size_t num_thread_ids = m_thread_ids.size();
1204 // The "m_thread_ids" thread ID list should always be updated after each stop
1205 // reply packet, but in case it isn't, update it here.
1206 if (num_thread_ids == 0)
1207 {
1208 if (!UpdateThreadIDList ())
1209 return false;
1210 num_thread_ids = m_thread_ids.size();
1211 }
Chris Lattner24943d22010-06-08 16:52:24 +00001212
Greg Clayton37f962e2011-08-22 02:49:39 +00001213 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001214 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001215 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001216 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001217 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001218 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1219 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001220 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001221 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001222 }
Chris Lattner24943d22010-06-08 16:52:24 +00001223 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001224
Greg Claytonae932352012-04-10 00:18:59 +00001225 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001226}
1227
1228
1229StateType
1230ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1231{
Greg Clayton261a18b2011-06-02 22:22:38 +00001232 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001233 const char stop_type = stop_packet.GetChar();
1234 switch (stop_type)
1235 {
1236 case 'T':
1237 case 'S':
1238 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001239 if (GetStopID() == 0)
1240 {
1241 // Our first stop, make sure we have a process ID, and also make
1242 // sure we know about our registers
1243 if (GetID() == LLDB_INVALID_PROCESS_ID)
1244 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001245 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001246 if (pid != LLDB_INVALID_PROCESS_ID)
1247 SetID (pid);
1248 }
1249 BuildDynamicRegisterInfo (true);
1250 }
Chris Lattner24943d22010-06-08 16:52:24 +00001251 // Stop with signal and thread info
1252 const uint8_t signo = stop_packet.GetHexU8();
1253 std::string name;
1254 std::string value;
1255 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001256 std::string reason;
1257 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001258 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001259 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001260 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1261 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001262 ThreadSP thread_sp;
1263
Chris Lattner24943d22010-06-08 16:52:24 +00001264 while (stop_packet.GetNameColonValue(name, value))
1265 {
1266 if (name.compare("metype") == 0)
1267 {
1268 // exception type in big endian hex
1269 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1270 }
1271 else if (name.compare("mecount") == 0)
1272 {
1273 // exception count in big endian hex
1274 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1275 }
1276 else if (name.compare("medata") == 0)
1277 {
1278 // exception data in big endian hex
1279 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1280 }
1281 else if (name.compare("thread") == 0)
1282 {
1283 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001284 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001285 // m_thread_list does have its own mutex, but we need to
1286 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1287 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001288 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001289 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001290 if (!thread_sp)
1291 {
1292 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001293 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001294 m_thread_list.AddThread(thread_sp);
1295 }
Chris Lattner24943d22010-06-08 16:52:24 +00001296 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001297 else if (name.compare("threads") == 0)
1298 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001299 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001300 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001301 // A comma separated list of all threads in the current
1302 // process that includes the thread for this stop reply
1303 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001304 size_t comma_pos;
1305 lldb::tid_t tid;
1306 while ((comma_pos = value.find(',')) != std::string::npos)
1307 {
1308 value[comma_pos] = '\0';
1309 // thread in big endian hex
1310 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1311 if (tid != LLDB_INVALID_THREAD_ID)
1312 m_thread_ids.push_back (tid);
1313 value.erase(0, comma_pos + 1);
1314
1315 }
1316 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1317 if (tid != LLDB_INVALID_THREAD_ID)
1318 m_thread_ids.push_back (tid);
1319 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001320 else if (name.compare("hexname") == 0)
1321 {
1322 StringExtractor name_extractor;
1323 // Swap "value" over into "name_extractor"
1324 name_extractor.GetStringRef().swap(value);
1325 // Now convert the HEX bytes into a string value
1326 name_extractor.GetHexByteString (value);
1327 thread_name.swap (value);
1328 }
Chris Lattner24943d22010-06-08 16:52:24 +00001329 else if (name.compare("name") == 0)
1330 {
1331 thread_name.swap (value);
1332 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001333 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001334 {
1335 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1336 }
Greg Clayton65611552011-06-04 01:26:29 +00001337 else if (name.compare("reason") == 0)
1338 {
1339 reason.swap(value);
1340 }
1341 else if (name.compare("description") == 0)
1342 {
1343 StringExtractor desc_extractor;
1344 // Swap "value" over into "name_extractor"
1345 desc_extractor.GetStringRef().swap(value);
1346 // Now convert the HEX bytes into a string value
1347 desc_extractor.GetHexByteString (thread_name);
1348 }
Greg Claytona875b642011-01-09 21:07:35 +00001349 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1350 {
1351 // We have a register number that contains an expedited
1352 // register value. Lets supply this register to our thread
1353 // so it won't have to go and read it.
1354 if (thread_sp)
1355 {
1356 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1357
1358 if (reg != UINT32_MAX)
1359 {
1360 StringExtractor reg_value_extractor;
1361 // Swap "value" over into "reg_value_extractor"
1362 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001363 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1364 {
1365 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1366 name.c_str(),
1367 reg,
1368 reg,
1369 reg_value_extractor.GetStringRef().c_str(),
1370 stop_packet.GetStringRef().c_str());
1371 }
Greg Claytona875b642011-01-09 21:07:35 +00001372 }
1373 }
1374 }
Chris Lattner24943d22010-06-08 16:52:24 +00001375 }
Chris Lattner24943d22010-06-08 16:52:24 +00001376
1377 if (thread_sp)
1378 {
1379 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1380
1381 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001382 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001383 if (exc_type != 0)
1384 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001385 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001386
1387 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1388 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001389 exc_data_size,
1390 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001391 exc_data_size >= 2 ? exc_data[1] : 0,
1392 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001393 }
Greg Clayton65611552011-06-04 01:26:29 +00001394 else
Chris Lattner24943d22010-06-08 16:52:24 +00001395 {
Greg Clayton65611552011-06-04 01:26:29 +00001396 bool handled = false;
1397 if (!reason.empty())
1398 {
1399 if (reason.compare("trace") == 0)
1400 {
1401 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1402 handled = true;
1403 }
1404 else if (reason.compare("breakpoint") == 0)
1405 {
1406 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001407 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001408 if (bp_site_sp)
1409 {
1410 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1411 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1412 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1413 if (bp_site_sp->ValidForThisThread (gdb_thread))
1414 {
1415 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1416 handled = true;
1417 }
1418 }
1419
1420 if (!handled)
1421 {
1422 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1423 }
1424 }
1425 else if (reason.compare("trap") == 0)
1426 {
1427 // Let the trap just use the standard signal stop reason below...
1428 }
1429 else if (reason.compare("watchpoint") == 0)
1430 {
1431 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1432 // TODO: locate the watchpoint somehow...
1433 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1434 handled = true;
1435 }
1436 else if (reason.compare("exception") == 0)
1437 {
1438 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1439 handled = true;
1440 }
1441 }
1442
1443 if (signo)
1444 {
1445 if (signo == SIGTRAP)
1446 {
1447 // Currently we are going to assume SIGTRAP means we are either
1448 // hitting a breakpoint or hardware single stepping.
1449 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001450 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001451 if (bp_site_sp)
1452 {
1453 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1454 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1455 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1456 if (bp_site_sp->ValidForThisThread (gdb_thread))
1457 {
1458 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1459 handled = true;
1460 }
1461 }
1462 if (!handled)
1463 {
1464 // TODO: check for breakpoint or trap opcode in case there is a hard
1465 // coded software trap
1466 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1467 handled = true;
1468 }
1469 }
1470 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001471 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001472 }
1473 else
1474 {
Greg Clayton643ee732010-08-04 01:40:35 +00001475 StopInfoSP invalid_stop_info_sp;
1476 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001477 }
Greg Clayton65611552011-06-04 01:26:29 +00001478
1479 if (!description.empty())
1480 {
1481 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1482 if (stop_info_sp)
1483 {
1484 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001485 }
Greg Clayton65611552011-06-04 01:26:29 +00001486 else
1487 {
1488 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1489 }
1490 }
1491 }
Chris Lattner24943d22010-06-08 16:52:24 +00001492 }
1493 return eStateStopped;
1494 }
1495 break;
1496
1497 case 'W':
1498 // process exited
1499 return eStateExited;
1500
1501 default:
1502 break;
1503 }
1504 return eStateInvalid;
1505}
1506
1507void
1508ProcessGDBRemote::RefreshStateAfterStop ()
1509{
Greg Claytonff3448e2012-04-13 02:11:32 +00001510 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001511 m_thread_ids.clear();
1512 // Set the thread stop info. It might have a "threads" key whose value is
1513 // a list of all thread IDs in the current process, so m_thread_ids might
1514 // get set.
1515 SetThreadStopInfo (m_last_stop_packet);
1516 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1517 if (m_thread_ids.empty())
1518 {
1519 // No, we need to fetch the thread list manually
1520 UpdateThreadIDList();
1521 }
1522
Chris Lattner24943d22010-06-08 16:52:24 +00001523 // Let all threads recover from stopping and do any clean up based
1524 // on the previous thread state (if any).
1525 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001526
Chris Lattner24943d22010-06-08 16:52:24 +00001527}
1528
1529Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001530ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001531{
1532 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001533
Greg Claytona4881d02011-01-22 07:12:45 +00001534 bool timed_out = false;
1535 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001536
1537 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001538 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001539 // We are being asked to halt during an attach. We need to just close
1540 // our file handle and debugserver will go away, and we can be done...
1541 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001542 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001543 else
1544 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001545 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001546 {
1547 if (timed_out)
1548 error.SetErrorString("timed out sending interrupt packet");
1549 else
1550 error.SetErrorString("unknown error sending interrupt packet");
1551 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001552
1553 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001554 }
Chris Lattner24943d22010-06-08 16:52:24 +00001555 return error;
1556}
1557
1558Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001559ProcessGDBRemote::InterruptIfRunning
1560(
1561 bool discard_thread_plans,
1562 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001563 EventSP &stop_event_sp
1564)
Chris Lattner24943d22010-06-08 16:52:24 +00001565{
1566 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001567
Greg Clayton2860ba92011-01-23 19:58:49 +00001568 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1569
Greg Clayton68ca8232011-01-25 02:58:48 +00001570 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001571 const bool is_running = m_gdb_comm.IsRunning();
1572 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001573 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001574 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001575 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001576 is_running);
1577
Greg Clayton2860ba92011-01-23 19:58:49 +00001578 if (discard_thread_plans)
1579 {
1580 if (log)
1581 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1582 m_thread_list.DiscardThreadPlans();
1583 }
1584 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001585 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001586 if (catch_stop_event)
1587 {
1588 if (log)
1589 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1590 PausePrivateStateThread();
1591 paused_private_state_thread = true;
1592 }
1593
Greg Clayton4fb400f2010-09-27 21:07:38 +00001594 bool timed_out = false;
1595 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001596
Greg Clayton05e4d972012-03-29 01:55:41 +00001597 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001598 {
1599 if (timed_out)
1600 error.SetErrorString("timed out sending interrupt packet");
1601 else
1602 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001603 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001604 ResumePrivateStateThread();
1605 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001606 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001607
Greg Clayton72e1c782011-01-22 23:43:18 +00001608 if (catch_stop_event)
1609 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001610 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001611 TimeValue timeout_time;
1612 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001613 timeout_time.OffsetWithSeconds(5);
1614 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001615
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001616 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001617 if (log)
1618 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001619
Greg Clayton2860ba92011-01-23 19:58:49 +00001620 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001621 error.SetErrorString("unable to verify target stopped");
1622 }
1623
Greg Clayton68ca8232011-01-25 02:58:48 +00001624 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001625 {
1626 if (log)
1627 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001628 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001629 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001630 }
Chris Lattner24943d22010-06-08 16:52:24 +00001631 return error;
1632}
1633
Greg Clayton4fb400f2010-09-27 21:07:38 +00001634Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001635ProcessGDBRemote::WillDetach ()
1636{
Greg Clayton2860ba92011-01-23 19:58:49 +00001637 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1638 if (log)
1639 log->Printf ("ProcessGDBRemote::WillDetach()");
1640
Greg Clayton72e1c782011-01-22 23:43:18 +00001641 bool discard_thread_plans = true;
1642 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001643 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001644 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001645}
1646
1647Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001648ProcessGDBRemote::DoDetach()
1649{
1650 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001651 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001652 if (log)
1653 log->Printf ("ProcessGDBRemote::DoDetach()");
1654
1655 DisableAllBreakpointSites ();
1656
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001657 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001658
Greg Clayton516f0842012-04-11 00:24:49 +00001659 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001660 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001661 {
Greg Clayton516f0842012-04-11 00:24:49 +00001662 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001663 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1664 else
1665 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001666 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001667 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001668 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001669
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001670 SetPrivateState (eStateDetached);
1671 ResumePrivateStateThread();
1672
1673 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001674 return error;
1675}
Chris Lattner24943d22010-06-08 16:52:24 +00001676
1677Error
1678ProcessGDBRemote::DoDestroy ()
1679{
1680 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001681 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001682 if (log)
1683 log->Printf ("ProcessGDBRemote::DoDestroy()");
1684
1685 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001686 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001687 {
Jim Ingham8226e942011-10-28 01:11:35 +00001688 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001689 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001690
1691 StringExtractorGDBRemote response;
1692 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001693 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001694 {
1695 char packet_cmd = response.GetChar(0);
1696
1697 if (packet_cmd == 'W' || packet_cmd == 'X')
1698 {
Greg Clayton06709002011-12-06 04:51:14 +00001699 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001700 ClearThreadIDList ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001701 SetExitStatus(response.GetHexU8(), NULL);
1702 }
1703 }
1704 else
1705 {
1706 SetExitStatus(SIGABRT, NULL);
1707 //error.SetErrorString("kill packet failed");
1708 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001709 }
1710 }
Chris Lattner24943d22010-06-08 16:52:24 +00001711 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001712 KillDebugserverProcess ();
1713 return error;
1714}
1715
Chris Lattner24943d22010-06-08 16:52:24 +00001716//------------------------------------------------------------------
1717// Process Queries
1718//------------------------------------------------------------------
1719
1720bool
1721ProcessGDBRemote::IsAlive ()
1722{
Greg Clayton58e844b2010-12-08 05:08:21 +00001723 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001724}
1725
1726addr_t
1727ProcessGDBRemote::GetImageInfoAddress()
1728{
Greg Clayton516f0842012-04-11 00:24:49 +00001729 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001730}
1731
Chris Lattner24943d22010-06-08 16:52:24 +00001732//------------------------------------------------------------------
1733// Process Memory
1734//------------------------------------------------------------------
1735size_t
1736ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1737{
1738 if (size > m_max_memory_size)
1739 {
1740 // Keep memory read sizes down to a sane limit. This function will be
1741 // called multiple times in order to complete the task by
1742 // lldb_private::Process so it is ok to do this.
1743 size = m_max_memory_size;
1744 }
1745
1746 char packet[64];
1747 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1748 assert (packet_len + 1 < sizeof(packet));
1749 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001750 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001751 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001752 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001753 {
1754 error.Clear();
1755 return response.GetHexBytes(buf, size, '\xdd');
1756 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001757 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001758 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001759 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001760 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1761 else
1762 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1763 }
1764 else
1765 {
1766 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1767 }
1768 return 0;
1769}
1770
1771size_t
1772ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1773{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001774 if (size > m_max_memory_size)
1775 {
1776 // Keep memory read sizes down to a sane limit. This function will be
1777 // called multiple times in order to complete the task by
1778 // lldb_private::Process so it is ok to do this.
1779 size = m_max_memory_size;
1780 }
1781
Chris Lattner24943d22010-06-08 16:52:24 +00001782 StreamString packet;
1783 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001784 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001785 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001786 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001787 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001788 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001789 {
1790 error.Clear();
1791 return size;
1792 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001793 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001794 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001795 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001796 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1797 else
1798 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1799 }
1800 else
1801 {
1802 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1803 }
1804 return 0;
1805}
1806
1807lldb::addr_t
1808ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1809{
Greg Clayton989816b2011-05-14 01:50:35 +00001810 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1811
Greg Clayton2f085c62011-05-15 01:25:55 +00001812 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001813 switch (supported)
1814 {
1815 case eLazyBoolCalculate:
1816 case eLazyBoolYes:
1817 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1818 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1819 return allocated_addr;
1820
1821 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001822 // Call mmap() to create memory in the inferior..
1823 unsigned prot = 0;
1824 if (permissions & lldb::ePermissionsReadable)
1825 prot |= eMmapProtRead;
1826 if (permissions & lldb::ePermissionsWritable)
1827 prot |= eMmapProtWrite;
1828 if (permissions & lldb::ePermissionsExecutable)
1829 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001830
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001831 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1832 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1833 m_addr_to_mmap_size[allocated_addr] = size;
1834 else
1835 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001836 break;
1837 }
1838
Chris Lattner24943d22010-06-08 16:52:24 +00001839 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001840 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001841 else
1842 error.Clear();
1843 return allocated_addr;
1844}
1845
1846Error
Greg Claytona9385532011-11-18 07:03:08 +00001847ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1848 MemoryRegionInfo &region_info)
1849{
1850
1851 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1852 return error;
1853}
1854
1855Error
Chris Lattner24943d22010-06-08 16:52:24 +00001856ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1857{
1858 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001859 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1860
1861 switch (supported)
1862 {
1863 case eLazyBoolCalculate:
1864 // We should never be deallocating memory without allocating memory
1865 // first so we should never get eLazyBoolCalculate
1866 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1867 break;
1868
1869 case eLazyBoolYes:
1870 if (!m_gdb_comm.DeallocateMemory (addr))
1871 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1872 break;
1873
1874 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001875 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001876 {
1877 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001878 if (pos != m_addr_to_mmap_size.end() &&
1879 InferiorCallMunmap(this, addr, pos->second))
1880 m_addr_to_mmap_size.erase (pos);
1881 else
1882 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001883 }
1884 break;
1885 }
1886
Chris Lattner24943d22010-06-08 16:52:24 +00001887 return error;
1888}
1889
1890
1891//------------------------------------------------------------------
1892// Process STDIO
1893//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001894size_t
1895ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1896{
1897 if (m_stdio_communication.IsConnected())
1898 {
1899 ConnectionStatus status;
1900 m_stdio_communication.Write(src, src_len, status, NULL);
1901 }
1902 return 0;
1903}
1904
1905Error
1906ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1907{
1908 Error error;
1909 assert (bp_site != NULL);
1910
Greg Claytone005f2c2010-11-06 01:53:30 +00001911 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001912 user_id_t site_id = bp_site->GetID();
1913 const addr_t addr = bp_site->GetLoadAddress();
1914 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001915 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001916
1917 if (bp_site->IsEnabled())
1918 {
1919 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001920 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 +00001921 return error;
1922 }
1923 else
1924 {
1925 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1926
1927 if (bp_site->HardwarePreferred())
1928 {
1929 // Try and set hardware breakpoint, and if that fails, fall through
1930 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001931 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001932 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001933 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001934 {
1935 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001936 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001937 return error;
1938 }
Chris Lattner24943d22010-06-08 16:52:24 +00001939 }
1940 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001941
1942 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001943 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001944 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1945 {
1946 bp_site->SetEnabled(true);
1947 bp_site->SetType (BreakpointSite::eExternal);
1948 return error;
1949 }
Chris Lattner24943d22010-06-08 16:52:24 +00001950 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001951
1952 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001953 }
1954
1955 if (log)
1956 {
1957 const char *err_string = error.AsCString();
1958 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1959 bp_site->GetLoadAddress(),
1960 err_string ? err_string : "NULL");
1961 }
1962 // We shouldn't reach here on a successful breakpoint enable...
1963 if (error.Success())
1964 error.SetErrorToGenericError();
1965 return error;
1966}
1967
1968Error
1969ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1970{
1971 Error error;
1972 assert (bp_site != NULL);
1973 addr_t addr = bp_site->GetLoadAddress();
1974 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001975 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001976 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001977 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001978
1979 if (bp_site->IsEnabled())
1980 {
1981 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1982
Greg Claytonb72d0f02011-04-12 05:54:46 +00001983 BreakpointSite::Type bp_type = bp_site->GetType();
1984 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001985 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001986 case BreakpointSite::eSoftware:
1987 error = DisableSoftwareBreakpoint (bp_site);
1988 break;
1989
1990 case BreakpointSite::eHardware:
1991 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1992 error.SetErrorToGenericError();
1993 break;
1994
1995 case BreakpointSite::eExternal:
1996 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1997 error.SetErrorToGenericError();
1998 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001999 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002000 if (error.Success())
2001 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002002 }
2003 else
2004 {
2005 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002006 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 +00002007 return error;
2008 }
2009
2010 if (error.Success())
2011 error.SetErrorToGenericError();
2012 return error;
2013}
2014
Johnny Chen21900fb2011-09-06 22:38:36 +00002015// Pre-requisite: wp != NULL.
2016static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002017GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002018{
2019 assert(wp);
2020 bool watch_read = wp->WatchpointRead();
2021 bool watch_write = wp->WatchpointWrite();
2022
2023 // watch_read and watch_write cannot both be false.
2024 assert(watch_read || watch_write);
2025 if (watch_read && watch_write)
2026 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002027 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002028 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002029 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002030 return eWatchpointWrite;
2031}
2032
Chris Lattner24943d22010-06-08 16:52:24 +00002033Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002034ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002035{
2036 Error error;
2037 if (wp)
2038 {
2039 user_id_t watchID = wp->GetID();
2040 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002041 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002042 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002043 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002044 if (wp->IsEnabled())
2045 {
2046 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002047 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002048 return error;
2049 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002050
2051 GDBStoppointType type = GetGDBStoppointType(wp);
2052 // Pass down an appropriate z/Z packet...
2053 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002054 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002055 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2056 {
2057 wp->SetEnabled(true);
2058 return error;
2059 }
2060 else
2061 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002062 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002063 else
2064 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002065 }
2066 else
2067 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002068 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002069 }
2070 if (error.Success())
2071 error.SetErrorToGenericError();
2072 return error;
2073}
2074
2075Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002076ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002077{
2078 Error error;
2079 if (wp)
2080 {
2081 user_id_t watchID = wp->GetID();
2082
Greg Claytone005f2c2010-11-06 01:53:30 +00002083 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002084
2085 addr_t addr = wp->GetLoadAddress();
2086 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002087 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002088
Johnny Chen21900fb2011-09-06 22:38:36 +00002089 if (!wp->IsEnabled())
2090 {
2091 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002092 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002093 return error;
2094 }
2095
Chris Lattner24943d22010-06-08 16:52:24 +00002096 if (wp->IsHardware())
2097 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002098 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002099 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002100 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2101 {
2102 wp->SetEnabled(false);
2103 return error;
2104 }
2105 else
2106 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002107 }
2108 // TODO: clear software watchpoints if we implement them
2109 }
2110 else
2111 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002112 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002113 }
2114 if (error.Success())
2115 error.SetErrorToGenericError();
2116 return error;
2117}
2118
2119void
2120ProcessGDBRemote::Clear()
2121{
2122 m_flags = 0;
2123 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002124}
2125
2126Error
2127ProcessGDBRemote::DoSignal (int signo)
2128{
2129 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002130 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002131 if (log)
2132 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2133
2134 if (!m_gdb_comm.SendAsyncSignal (signo))
2135 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2136 return error;
2137}
2138
Chris Lattner24943d22010-06-08 16:52:24 +00002139Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002140ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2141{
2142 ProcessLaunchInfo launch_info;
2143 return StartDebugserverProcess(debugserver_url, launch_info);
2144}
2145
2146Error
2147ProcessGDBRemote::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 +00002148{
2149 Error error;
2150 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2151 {
2152 // If we locate debugserver, keep that located version around
2153 static FileSpec g_debugserver_file_spec;
2154
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002155 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002156 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002157 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002158
2159 // Always check to see if we have an environment override for the path
2160 // to the debugserver to use and use it if we do.
2161 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2162 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002163 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002164 else
2165 debugserver_file_spec = g_debugserver_file_spec;
2166 bool debugserver_exists = debugserver_file_spec.Exists();
2167 if (!debugserver_exists)
2168 {
2169 // The debugserver binary is in the LLDB.framework/Resources
2170 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002171 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002172 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002173 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002174 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002175 if (debugserver_exists)
2176 {
2177 g_debugserver_file_spec = debugserver_file_spec;
2178 }
2179 else
2180 {
2181 g_debugserver_file_spec.Clear();
2182 debugserver_file_spec.Clear();
2183 }
Chris Lattner24943d22010-06-08 16:52:24 +00002184 }
2185 }
2186
2187 if (debugserver_exists)
2188 {
2189 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2190
2191 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002192
Greg Claytone005f2c2010-11-06 01:53:30 +00002193 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002194
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002195 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002196 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002197
Chris Lattner24943d22010-06-08 16:52:24 +00002198 // Start args with "debugserver /file/path -r --"
2199 debugserver_args.AppendArgument(debugserver_path);
2200 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002201 // use native registers, not the GDB registers
2202 debugserver_args.AppendArgument("--native-regs");
2203 // make debugserver run in its own session so signals generated by
2204 // special terminal key sequences (^C) don't affect debugserver
2205 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002206
Chris Lattner24943d22010-06-08 16:52:24 +00002207 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2208 if (env_debugserver_log_file)
2209 {
2210 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2211 debugserver_args.AppendArgument(arg_cstr);
2212 }
2213
2214 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2215 if (env_debugserver_log_flags)
2216 {
2217 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2218 debugserver_args.AppendArgument(arg_cstr);
2219 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002220// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002221// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002222
Greg Claytonb72d0f02011-04-12 05:54:46 +00002223 // We currently send down all arguments, attach pids, or attach
2224 // process names in dedicated GDB server packets, so we don't need
2225 // to pass them as arguments. This is currently because of all the
2226 // things we need to setup prior to launching: the environment,
2227 // current working dir, file actions, etc.
2228#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002229 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002230 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002231 {
Greg Claytona2f74232011-02-24 22:24:29 +00002232 // Terminate the debugserver args so we can now append the inferior args
2233 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002234
Greg Claytona2f74232011-02-24 22:24:29 +00002235 for (int i = 0; inferior_argv[i] != NULL; ++i)
2236 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002237 }
2238 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2239 {
2240 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2241 debugserver_args.AppendArgument (arg_cstr);
2242 }
2243 else if (attach_name && attach_name[0])
2244 {
2245 if (wait_for_launch)
2246 debugserver_args.AppendArgument ("--waitfor");
2247 else
2248 debugserver_args.AppendArgument ("--attach");
2249 debugserver_args.AppendArgument (attach_name);
2250 }
Chris Lattner24943d22010-06-08 16:52:24 +00002251#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002252
2253 ProcessLaunchInfo::FileAction file_action;
2254
2255 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2256 // to "/dev/null" if we run into any problems.
2257 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002258 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002259 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002260 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002261 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002262 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002263
2264 if (log)
2265 {
2266 StreamString strm;
2267 debugserver_args.Dump (&strm);
2268 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2269 }
2270
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002271 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2272 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002273
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002274 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002275
Greg Claytonb72d0f02011-04-12 05:54:46 +00002276 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002277 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002278 else
Chris Lattner24943d22010-06-08 16:52:24 +00002279 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2280
2281 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002282 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002283 }
2284 else
2285 {
Greg Clayton9c236732011-10-26 00:56:27 +00002286 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002287 }
2288
2289 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2290 StartAsyncThread ();
2291 }
2292 return error;
2293}
2294
2295bool
2296ProcessGDBRemote::MonitorDebugserverProcess
2297(
2298 void *callback_baton,
2299 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002300 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002301 int signo, // Zero for no signal
2302 int exit_status // Exit value of process if signal is zero
2303)
2304{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002305 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2306 // and might not exist anymore, so we need to carefully try to get the
2307 // target for this process first since we have a race condition when
2308 // we are done running between getting the notice that the inferior
2309 // process has died and the debugserver that was debugging this process.
2310 // In our test suite, we are also continually running process after
2311 // process, so we must be very careful to make sure:
2312 // 1 - process object hasn't been deleted already
2313 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002314
2315 // "debugserver_pid" argument passed in is the process ID for
2316 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002317 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002318
Greg Clayton75ccf502010-08-21 02:22:51 +00002319 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002320
Greg Clayton1c4642c2011-11-16 05:37:56 +00002321 // Get a shared pointer to the target that has a matching process pointer.
2322 // This target could be gone, or the target could already have a new process
2323 // object inside of it
2324 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2325
Greg Clayton72e1c782011-01-22 23:43:18 +00002326 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002327 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 +00002328
Greg Clayton1c4642c2011-11-16 05:37:56 +00002329 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002330 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002331 // We found a process in a target that matches, but another thread
2332 // might be in the process of launching a new process that will
2333 // soon replace it, so get a shared pointer to the process so we
2334 // can keep it alive.
2335 ProcessSP process_sp (target_sp->GetProcessSP());
2336 // Now we have a shared pointer to the process that can't go away on us
2337 // so we now make sure it was the same as the one passed in, and also make
2338 // sure that our previous "process *" didn't get deleted and have a new
2339 // "process *" created in its place with the same pointer. To verify this
2340 // we make sure the process has our debugserver process ID. If we pass all
2341 // of these tests, then we are sure that this process is the one we were
2342 // looking for.
2343 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002344 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002345 // Sleep for a half a second to make sure our inferior process has
2346 // time to set its exit status before we set it incorrectly when
2347 // both the debugserver and the inferior process shut down.
2348 usleep (500000);
2349 // If our process hasn't yet exited, debugserver might have died.
2350 // If the process did exit, the we are reaping it.
2351 const StateType state = process->GetState();
2352
2353 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2354 state != eStateInvalid &&
2355 state != eStateUnloaded &&
2356 state != eStateExited &&
2357 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002358 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002359 char error_str[1024];
2360 if (signo)
2361 {
2362 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2363 if (signal_cstr)
2364 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2365 else
2366 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2367 }
Chris Lattner24943d22010-06-08 16:52:24 +00002368 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002369 {
2370 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2371 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002372
Greg Clayton1c4642c2011-11-16 05:37:56 +00002373 process->SetExitStatus (-1, error_str);
2374 }
2375 // Debugserver has exited we need to let our ProcessGDBRemote
2376 // know that it no longer has a debugserver instance
2377 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002378 }
Chris Lattner24943d22010-06-08 16:52:24 +00002379 }
2380 return true;
2381}
2382
2383void
2384ProcessGDBRemote::KillDebugserverProcess ()
2385{
2386 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2387 {
2388 ::kill (m_debugserver_pid, SIGINT);
2389 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2390 }
2391}
2392
2393void
2394ProcessGDBRemote::Initialize()
2395{
2396 static bool g_initialized = false;
2397
2398 if (g_initialized == false)
2399 {
2400 g_initialized = true;
2401 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2402 GetPluginDescriptionStatic(),
2403 CreateInstance);
2404
2405 Log::Callbacks log_callbacks = {
2406 ProcessGDBRemoteLog::DisableLog,
2407 ProcessGDBRemoteLog::EnableLog,
2408 ProcessGDBRemoteLog::ListLogCategories
2409 };
2410
2411 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2412 }
2413}
2414
2415bool
Chris Lattner24943d22010-06-08 16:52:24 +00002416ProcessGDBRemote::StartAsyncThread ()
2417{
Greg Claytone005f2c2010-11-06 01:53:30 +00002418 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002419
2420 if (log)
2421 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2422
2423 // Create a thread that watches our internal state and controls which
2424 // events make it to clients (into the DCProcess event queue).
2425 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002426 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002427}
2428
2429void
2430ProcessGDBRemote::StopAsyncThread ()
2431{
Greg Claytone005f2c2010-11-06 01:53:30 +00002432 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002433
2434 if (log)
2435 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2436
2437 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002438
2439 // This will shut down the async thread.
2440 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002441
2442 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002443 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002444 {
2445 Host::ThreadJoin (m_async_thread, NULL, NULL);
2446 }
2447}
2448
2449
2450void *
2451ProcessGDBRemote::AsyncThread (void *arg)
2452{
2453 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2454
Greg Claytone005f2c2010-11-06 01:53:30 +00002455 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002456 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002457 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002458
2459 Listener listener ("ProcessGDBRemote::AsyncThread");
2460 EventSP event_sp;
2461 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2462 eBroadcastBitAsyncThreadShouldExit;
2463
2464 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2465 {
Greg Claytona2f74232011-02-24 22:24:29 +00002466 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2467
Chris Lattner24943d22010-06-08 16:52:24 +00002468 bool done = false;
2469 while (!done)
2470 {
2471 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002472 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002473 if (listener.WaitForEvent (NULL, event_sp))
2474 {
2475 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002476 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002477 {
Greg Claytona2f74232011-02-24 22:24:29 +00002478 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002479 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 +00002480
Greg Claytona2f74232011-02-24 22:24:29 +00002481 switch (event_type)
2482 {
2483 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002484 {
Greg Claytona2f74232011-02-24 22:24:29 +00002485 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002486
Greg Claytona2f74232011-02-24 22:24:29 +00002487 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002488 {
Greg Claytona2f74232011-02-24 22:24:29 +00002489 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2490 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2491 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002492 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002493
Greg Claytona2f74232011-02-24 22:24:29 +00002494 if (::strstr (continue_cstr, "vAttach") == NULL)
2495 process->SetPrivateState(eStateRunning);
2496 StringExtractorGDBRemote response;
2497 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002498
Greg Claytona2f74232011-02-24 22:24:29 +00002499 switch (stop_state)
2500 {
2501 case eStateStopped:
2502 case eStateCrashed:
2503 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002504 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002505 process->SetPrivateState (stop_state);
2506 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002507
Greg Claytona2f74232011-02-24 22:24:29 +00002508 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002509 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002510 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002511 response.SetFilePos(1);
2512 process->SetExitStatus(response.GetHexU8(), NULL);
2513 done = true;
2514 break;
2515
2516 case eStateInvalid:
2517 process->SetExitStatus(-1, "lost connection");
2518 break;
2519
2520 default:
2521 process->SetPrivateState (stop_state);
2522 break;
2523 }
Chris Lattner24943d22010-06-08 16:52:24 +00002524 }
2525 }
Greg Claytona2f74232011-02-24 22:24:29 +00002526 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002527
Greg Claytona2f74232011-02-24 22:24:29 +00002528 case eBroadcastBitAsyncThreadShouldExit:
2529 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002530 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002531 done = true;
2532 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002533
Greg Claytona2f74232011-02-24 22:24:29 +00002534 default:
2535 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002536 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 +00002537 done = true;
2538 break;
2539 }
2540 }
2541 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2542 {
2543 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2544 {
2545 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002546 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002547 }
Chris Lattner24943d22010-06-08 16:52:24 +00002548 }
2549 }
2550 else
2551 {
2552 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002553 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 +00002554 done = true;
2555 }
2556 }
2557 }
2558
2559 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002560 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002561
2562 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2563 return NULL;
2564}
2565
Chris Lattner24943d22010-06-08 16:52:24 +00002566const char *
2567ProcessGDBRemote::GetDispatchQueueNameForThread
2568(
2569 addr_t thread_dispatch_qaddr,
2570 std::string &dispatch_queue_name
2571)
2572{
2573 dispatch_queue_name.clear();
2574 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2575 {
2576 // Cache the dispatch_queue_offsets_addr value so we don't always have
2577 // to look it up
2578 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2579 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002580 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2581 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002582 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2583 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002584 if (module_sp)
2585 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2586
2587 if (dispatch_queue_offsets_symbol == NULL)
2588 {
Greg Clayton444fe992012-02-26 05:51:37 +00002589 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2590 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002591 if (module_sp)
2592 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2593 }
Chris Lattner24943d22010-06-08 16:52:24 +00002594 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002595 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002596
2597 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2598 return NULL;
2599 }
2600
2601 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002602 DataExtractor data (memory_buffer,
2603 sizeof(memory_buffer),
2604 m_target.GetArchitecture().GetByteOrder(),
2605 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002606
2607 // Excerpt from src/queue_private.h
2608 struct dispatch_queue_offsets_s
2609 {
2610 uint16_t dqo_version;
2611 uint16_t dqo_label;
2612 uint16_t dqo_label_size;
2613 } dispatch_queue_offsets;
2614
2615
2616 Error error;
2617 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2618 {
2619 uint32_t data_offset = 0;
2620 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2621 {
2622 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2623 {
2624 data_offset = 0;
2625 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2626 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2627 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2628 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2629 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2630 dispatch_queue_name.erase (bytes_read);
2631 }
2632 }
2633 }
2634 }
2635 if (dispatch_queue_name.empty())
2636 return NULL;
2637 return dispatch_queue_name.c_str();
2638}
2639
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002640//uint32_t
2641//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2642//{
2643// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2644// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2645// if (m_local_debugserver)
2646// {
2647// return Host::ListProcessesMatchingName (name, matches, pids);
2648// }
2649// else
2650// {
2651// // FIXME: Implement talking to the remote debugserver.
2652// return 0;
2653// }
2654//
2655//}
2656//
Jim Ingham55e01d82011-01-22 01:33:44 +00002657bool
2658ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2659 lldb_private::StoppointCallbackContext *context,
2660 lldb::user_id_t break_id,
2661 lldb::user_id_t break_loc_id)
2662{
2663 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2664 // run so I can stop it if that's what I want to do.
2665 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2666 if (log)
2667 log->Printf("Hit New Thread Notification breakpoint.");
2668 return false;
2669}
2670
2671
2672bool
2673ProcessGDBRemote::StartNoticingNewThreads()
2674{
2675 static const char *bp_names[] =
2676 {
2677 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002678 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002679 "_pthread_start",
2680 NULL
2681 };
2682
2683 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2684 size_t num_bps = m_thread_observation_bps.size();
2685 if (num_bps != 0)
2686 {
2687 for (int i = 0; i < num_bps; i++)
2688 {
2689 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2690 if (break_sp)
2691 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002692 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002693 log->Printf("Enabled noticing new thread breakpoint.");
2694 break_sp->SetEnabled(true);
2695 }
2696 }
2697 }
2698 else
2699 {
2700 for (int i = 0; bp_names[i] != NULL; i++)
2701 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002702 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002703 if (breakpoint)
2704 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002705 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002706 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2707 m_thread_observation_bps.push_back(breakpoint->GetID());
2708 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2709 }
2710 else
2711 {
2712 if (log)
2713 log->Printf("Failed to create new thread notification breakpoint.");
2714 return false;
2715 }
2716 }
2717 }
2718
2719 return true;
2720}
2721
2722bool
2723ProcessGDBRemote::StopNoticingNewThreads()
2724{
Jim Inghamff276fe2011-02-08 05:19:01 +00002725 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002726 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002727 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002728 size_t num_bps = m_thread_observation_bps.size();
2729 if (num_bps != 0)
2730 {
2731 for (int i = 0; i < num_bps; i++)
2732 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002733
2734 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2735 if (break_sp)
2736 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002737 break_sp->SetEnabled(false);
2738 }
2739 }
2740 }
2741 return true;
2742}
2743
2744