blob: 53b7a24d2e80be1d301c6b51df1281db81804ac0 [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"
35#include "lldb/Core/StreamString.h"
36#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000037#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Host/TimeValue.h"
39#include "lldb/Symbol/ObjectFile.h"
40#include "lldb/Target/DynamicLoader.h"
41#include "lldb/Target/Target.h"
42#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000043#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000044#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045
46// Project includes
47#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000048#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000049#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000050#include "GDBRemoteRegisterContext.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000054#include "StopInfoMachException.h"
55
Chris Lattner24943d22010-06-08 16:52:24 +000056
Chris Lattner24943d22010-06-08 16:52:24 +000057
58#define DEBUGSERVER_BASENAME "debugserver"
59using namespace lldb;
60using namespace lldb_private;
61
Jim Inghamf9600482011-03-29 21:45:47 +000062static bool rand_initialized = false;
63
Chris Lattner24943d22010-06-08 16:52:24 +000064static inline uint16_t
65get_random_port ()
66{
Jim Inghamf9600482011-03-29 21:45:47 +000067 if (!rand_initialized)
68 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000069 time_t seed = time(NULL);
70
Jim Inghamf9600482011-03-29 21:45:47 +000071 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000072 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000073 }
Stephen Wilson50daf772011-03-25 18:16:28 +000074 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000075}
76
77
78const char *
79ProcessGDBRemote::GetPluginNameStatic()
80{
Greg Claytonb1888f22011-03-19 01:12:21 +000081 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000082}
83
84const char *
85ProcessGDBRemote::GetPluginDescriptionStatic()
86{
87 return "GDB Remote protocol based debugging plug-in.";
88}
89
90void
91ProcessGDBRemote::Terminate()
92{
93 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
94}
95
96
Greg Clayton46c9a352012-02-09 06:16:32 +000097lldb::ProcessSP
98ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +000099{
Greg Clayton46c9a352012-02-09 06:16:32 +0000100 lldb::ProcessSP process_sp;
101 if (crash_file_path == NULL)
102 process_sp.reset (new ProcessGDBRemote (target, listener));
103 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000104}
105
106bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000107ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000108{
Greg Clayton61ddf562011-10-21 21:41:45 +0000109 if (plugin_specified_by_name)
110 return true;
111
Chris Lattner24943d22010-06-08 16:52:24 +0000112 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000113 Module *exe_module = target.GetExecutableModulePointer();
114 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000115 {
116 ObjectFile *exe_objfile = exe_module->GetObjectFile();
117 // We can't debug core files...
118 switch (exe_objfile->GetType())
119 {
120 case ObjectFile::eTypeInvalid:
121 case ObjectFile::eTypeCoreFile:
122 case ObjectFile::eTypeDebugInfo:
123 case ObjectFile::eTypeObjectFile:
124 case ObjectFile::eTypeSharedLibrary:
125 case ObjectFile::eTypeStubLibrary:
126 return false;
127 case ObjectFile::eTypeExecutable:
128 case ObjectFile::eTypeDynamicLinker:
129 case ObjectFile::eTypeUnknown:
130 break;
131 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000132 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000133 }
Jim Ingham7508e732010-08-09 23:31:02 +0000134 // However, if there is no executable module, we return true since we might be preparing to attach.
135 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000136}
137
138//----------------------------------------------------------------------
139// ProcessGDBRemote constructor
140//----------------------------------------------------------------------
141ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
142 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000143 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000144 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000145 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000146 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000147 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000148 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000149 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000150 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000151 m_continue_c_tids (),
152 m_continue_C_tids (),
153 m_continue_s_tids (),
154 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000155 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000156 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000157 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000158 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000159{
Greg Claytonff39f742011-04-01 00:29:43 +0000160 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
161 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000162}
163
164//----------------------------------------------------------------------
165// Destructor
166//----------------------------------------------------------------------
167ProcessGDBRemote::~ProcessGDBRemote()
168{
169 // m_mach_process.UnregisterNotificationCallbacks (this);
170 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000171 // We need to call finalize on the process before destroying ourselves
172 // to make sure all of the broadcaster cleanup goes as planned. If we
173 // destruct this class, then Process::~Process() might have problems
174 // trying to fully destroy the broadcaster.
175 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000176}
177
178//----------------------------------------------------------------------
179// PluginInterface
180//----------------------------------------------------------------------
181const char *
182ProcessGDBRemote::GetPluginName()
183{
184 return "Process debugging plug-in that uses the GDB remote protocol";
185}
186
187const char *
188ProcessGDBRemote::GetShortPluginName()
189{
190 return GetPluginNameStatic();
191}
192
193uint32_t
194ProcessGDBRemote::GetPluginVersion()
195{
196 return 1;
197}
198
199void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000200ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000201{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000202 if (!force && m_register_info.GetNumRegisters() > 0)
203 return;
204
205 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000206 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000207 uint32_t reg_offset = 0;
208 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000209 StringExtractorGDBRemote::ResponseType response_type;
210 for (response_type = StringExtractorGDBRemote::eResponse;
211 response_type == StringExtractorGDBRemote::eResponse;
212 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000213 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000214 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
215 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000216 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000217 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000218 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000219 response_type = response.GetResponseType();
220 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000221 {
222 std::string name;
223 std::string value;
224 ConstString reg_name;
225 ConstString alt_name;
226 ConstString set_name;
227 RegisterInfo reg_info = { NULL, // Name
228 NULL, // Alt name
229 0, // byte size
230 reg_offset, // offset
231 eEncodingUint, // encoding
232 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000233 {
234 LLDB_INVALID_REGNUM, // GCC reg num
235 LLDB_INVALID_REGNUM, // DWARF reg num
236 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000237 reg_num, // GDB reg num
238 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000239 }
240 };
241
242 while (response.GetNameColonValue(name, value))
243 {
244 if (name.compare("name") == 0)
245 {
246 reg_name.SetCString(value.c_str());
247 }
248 else if (name.compare("alt-name") == 0)
249 {
250 alt_name.SetCString(value.c_str());
251 }
252 else if (name.compare("bitsize") == 0)
253 {
254 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
255 }
256 else if (name.compare("offset") == 0)
257 {
258 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000259 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000260 {
261 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000262 }
263 }
264 else if (name.compare("encoding") == 0)
265 {
266 if (value.compare("uint") == 0)
267 reg_info.encoding = eEncodingUint;
268 else if (value.compare("sint") == 0)
269 reg_info.encoding = eEncodingSint;
270 else if (value.compare("ieee754") == 0)
271 reg_info.encoding = eEncodingIEEE754;
272 else if (value.compare("vector") == 0)
273 reg_info.encoding = eEncodingVector;
274 }
275 else if (name.compare("format") == 0)
276 {
277 if (value.compare("binary") == 0)
278 reg_info.format = eFormatBinary;
279 else if (value.compare("decimal") == 0)
280 reg_info.format = eFormatDecimal;
281 else if (value.compare("hex") == 0)
282 reg_info.format = eFormatHex;
283 else if (value.compare("float") == 0)
284 reg_info.format = eFormatFloat;
285 else if (value.compare("vector-sint8") == 0)
286 reg_info.format = eFormatVectorOfSInt8;
287 else if (value.compare("vector-uint8") == 0)
288 reg_info.format = eFormatVectorOfUInt8;
289 else if (value.compare("vector-sint16") == 0)
290 reg_info.format = eFormatVectorOfSInt16;
291 else if (value.compare("vector-uint16") == 0)
292 reg_info.format = eFormatVectorOfUInt16;
293 else if (value.compare("vector-sint32") == 0)
294 reg_info.format = eFormatVectorOfSInt32;
295 else if (value.compare("vector-uint32") == 0)
296 reg_info.format = eFormatVectorOfUInt32;
297 else if (value.compare("vector-float32") == 0)
298 reg_info.format = eFormatVectorOfFloat32;
299 else if (value.compare("vector-uint128") == 0)
300 reg_info.format = eFormatVectorOfUInt128;
301 }
302 else if (name.compare("set") == 0)
303 {
304 set_name.SetCString(value.c_str());
305 }
306 else if (name.compare("gcc") == 0)
307 {
308 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
309 }
310 else if (name.compare("dwarf") == 0)
311 {
312 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
313 }
314 else if (name.compare("generic") == 0)
315 {
316 if (value.compare("pc") == 0)
317 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
318 else if (value.compare("sp") == 0)
319 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
320 else if (value.compare("fp") == 0)
321 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
322 else if (value.compare("ra") == 0)
323 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
324 else if (value.compare("flags") == 0)
325 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000326 else if (value.find("arg") == 0)
327 {
328 if (value.size() == 4)
329 {
330 switch (value[3])
331 {
332 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
333 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
334 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
335 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
336 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
337 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
338 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
339 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
340 }
341 }
342 }
Chris Lattner24943d22010-06-08 16:52:24 +0000343 }
344 }
345
Jason Molenda53d96862010-06-11 23:44:18 +0000346 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000347 assert (reg_info.byte_size != 0);
348 reg_offset += reg_info.byte_size;
349 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
350 }
351 }
352 else
353 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000354 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000355 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000356 }
357 }
358
359 if (reg_num == 0)
360 {
361 // We didn't get anything. See if we are debugging ARM and fill with
362 // a hard coded register set until we can get an updated debugserver
363 // down on the devices.
Jason Molenda428b5502011-10-06 01:45:46 +0000364
365 if (!GetTarget().GetArchitecture().IsValid()
366 && m_gdb_comm.GetHostArchitecture().IsValid()
367 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm
368 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
369 {
Chris Lattner24943d22010-06-08 16:52:24 +0000370 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000371 }
372 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
373 {
374 m_register_info.HardcodeARMRegisters();
375 }
Chris Lattner24943d22010-06-08 16:52:24 +0000376 }
377 m_register_info.Finalize ();
378}
379
380Error
381ProcessGDBRemote::WillLaunch (Module* module)
382{
383 return WillLaunchOrAttach ();
384}
385
386Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000387ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000388{
389 return WillLaunchOrAttach ();
390}
391
392Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000393ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000394{
395 return WillLaunchOrAttach ();
396}
397
398Error
Greg Claytone71e2582011-02-04 01:58:07 +0000399ProcessGDBRemote::DoConnectRemote (const char *remote_url)
400{
401 Error error (WillLaunchOrAttach ());
402
403 if (error.Fail())
404 return error;
405
Greg Clayton180546b2011-04-30 01:09:13 +0000406 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000407
408 if (error.Fail())
409 return error;
410 StartAsyncThread ();
411
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000412 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000413 if (pid == LLDB_INVALID_PROCESS_ID)
414 {
415 // We don't have a valid process ID, so note that we are connected
416 // and could now request to launch or attach, or get remote process
417 // listings...
418 SetPrivateState (eStateConnected);
419 }
420 else
421 {
422 // We have a valid process
423 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000424 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000425 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000426 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000427 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000428 if (state == eStateStopped)
429 {
430 SetPrivateState (state);
431 }
432 else
Greg Claytond9919d32011-12-01 23:28:38 +0000433 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 +0000434 }
435 else
Greg Claytond9919d32011-12-01 23:28:38 +0000436 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 +0000437 }
438 return error;
439}
440
441Error
Chris Lattner24943d22010-06-08 16:52:24 +0000442ProcessGDBRemote::WillLaunchOrAttach ()
443{
444 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000445 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000446 return error;
447}
448
449//----------------------------------------------------------------------
450// Process Control
451//----------------------------------------------------------------------
452Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000453ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000454{
Greg Clayton4b407112010-09-30 21:49:03 +0000455 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000456
457 uint32_t launch_flags = launch_info.GetFlags().Get();
458 const char *stdin_path = NULL;
459 const char *stdout_path = NULL;
460 const char *stderr_path = NULL;
461 const char *working_dir = launch_info.GetWorkingDirectory();
462
463 const ProcessLaunchInfo::FileAction *file_action;
464 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
465 if (file_action)
466 {
467 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
468 stdin_path = file_action->GetPath();
469 }
470 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
471 if (file_action)
472 {
473 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
474 stdout_path = file_action->GetPath();
475 }
476 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
477 if (file_action)
478 {
479 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
480 stderr_path = file_action->GetPath();
481 }
482
Chris Lattner24943d22010-06-08 16:52:24 +0000483 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
484 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
485 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000486 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000487
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000488 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000489 if (object_file)
490 {
Chris Lattner24943d22010-06-08 16:52:24 +0000491 char host_port[128];
492 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000493 char connect_url[128];
494 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000495
Greg Claytona2f74232011-02-24 22:24:29 +0000496 // Make sure we aren't already connected?
497 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000498 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000499 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000500 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000501 {
Johnny Chenc143d622011-08-09 18:56:45 +0000502 if (log)
503 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000504 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000505 }
Chris Lattner24943d22010-06-08 16:52:24 +0000506
Greg Claytone71e2582011-02-04 01:58:07 +0000507 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000508 }
509
510 if (error.Success())
511 {
512 lldb_utility::PseudoTerminal pty;
513 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000514
515 // If the debugserver is local and we aren't disabling STDIO, lets use
516 // a pseudo terminal to instead of relying on the 'O' packets for stdio
517 // since 'O' packets can really slow down debugging if the inferior
518 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000519 PlatformSP platform_sp (m_target.GetPlatform());
520 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000521 {
522 const char *slave_name = NULL;
523 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000524 {
Greg Claytona2f74232011-02-24 22:24:29 +0000525 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
526 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000527 }
Greg Claytona2f74232011-02-24 22:24:29 +0000528 if (stdin_path == NULL)
529 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000530
Greg Claytona2f74232011-02-24 22:24:29 +0000531 if (stdout_path == NULL)
532 stdout_path = slave_name;
533
534 if (stderr_path == NULL)
535 stderr_path = slave_name;
536 }
537
Greg Claytonafb81862011-03-02 21:34:46 +0000538 // Set STDIN to /dev/null if we want STDIO disabled or if either
539 // STDOUT or STDERR have been set to something and STDIN hasn't
540 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000541 stdin_path = "/dev/null";
542
Greg Claytonafb81862011-03-02 21:34:46 +0000543 // Set STDOUT to /dev/null if we want STDIO disabled or if either
544 // STDIN or STDERR have been set to something and STDOUT hasn't
545 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000546 stdout_path = "/dev/null";
547
Greg Claytonafb81862011-03-02 21:34:46 +0000548 // Set STDERR to /dev/null if we want STDIO disabled or if either
549 // STDIN or STDOUT have been set to something and STDERR hasn't
550 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000551 stderr_path = "/dev/null";
552
553 if (stdin_path)
554 m_gdb_comm.SetSTDIN (stdin_path);
555 if (stdout_path)
556 m_gdb_comm.SetSTDOUT (stdout_path);
557 if (stderr_path)
558 m_gdb_comm.SetSTDERR (stderr_path);
559
560 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
561
Greg Claytona4582402011-05-08 04:53:50 +0000562 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000563
564 if (working_dir && working_dir[0])
565 {
566 m_gdb_comm.SetWorkingDir (working_dir);
567 }
568
569 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000570 const Args &environment = launch_info.GetEnvironmentEntries();
571 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000572 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000573 size_t num_environment_entries = environment.GetArgumentCount();
574 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000575 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000576 const char *env_entry = environment.GetArgumentAtIndex(i);
577 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000578 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000579 }
Greg Claytona2f74232011-02-24 22:24:29 +0000580 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000581
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000582 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000583 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000584 if (arg_packet_err == 0)
585 {
586 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000587 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000588 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000589 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000590 }
591 else
592 {
Greg Claytona2f74232011-02-24 22:24:29 +0000593 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000594 }
Greg Claytona2f74232011-02-24 22:24:29 +0000595 }
596 else
597 {
Greg Clayton9c236732011-10-26 00:56:27 +0000598 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000599 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000600
601 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000602
Greg Claytona2f74232011-02-24 22:24:29 +0000603 if (GetID() == LLDB_INVALID_PROCESS_ID)
604 {
Johnny Chenc143d622011-08-09 18:56:45 +0000605 if (log)
606 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000607 KillDebugserverProcess ();
608 return error;
609 }
610
Greg Clayton261a18b2011-06-02 22:22:38 +0000611 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000612 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000613 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000614
615 if (!disable_stdio)
616 {
617 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000618 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000619 }
Chris Lattner24943d22010-06-08 16:52:24 +0000620 }
621 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000622 else
623 {
Johnny Chenc143d622011-08-09 18:56:45 +0000624 if (log)
625 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000626 }
Chris Lattner24943d22010-06-08 16:52:24 +0000627 }
628 else
629 {
630 // Set our user ID to an invalid process ID.
631 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000632 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
633 exe_module->GetFileSpec().GetFilename().AsCString(),
634 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000635 }
Chris Lattner24943d22010-06-08 16:52:24 +0000636 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000637
Chris Lattner24943d22010-06-08 16:52:24 +0000638}
639
640
641Error
Greg Claytone71e2582011-02-04 01:58:07 +0000642ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000643{
644 Error error;
645 // Sleep and wait a bit for debugserver to start to listen...
646 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
647 if (conn_ap.get())
648 {
Chris Lattner24943d22010-06-08 16:52:24 +0000649 const uint32_t max_retry_count = 50;
650 uint32_t retry_count = 0;
651 while (!m_gdb_comm.IsConnected())
652 {
Greg Claytone71e2582011-02-04 01:58:07 +0000653 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000654 {
655 m_gdb_comm.SetConnection (conn_ap.release());
656 break;
657 }
658 retry_count++;
659
660 if (retry_count >= max_retry_count)
661 break;
662
663 usleep (100000);
664 }
665 }
666
667 if (!m_gdb_comm.IsConnected())
668 {
669 if (error.Success())
670 error.SetErrorString("not connected to remote gdb server");
671 return error;
672 }
673
Greg Clayton24bc5d92011-03-30 18:16:51 +0000674 // We always seem to be able to open a connection to a local port
675 // so we need to make sure we can then send data to it. If we can't
676 // then we aren't actually connected to anything, so try and do the
677 // handshake with the remote GDB server and make sure that goes
678 // alright.
679 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000680 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000681 m_gdb_comm.Disconnect();
682 if (error.Success())
683 error.SetErrorString("not connected to remote gdb server");
684 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000685 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000686 m_gdb_comm.ResetDiscoverableSettings();
687 m_gdb_comm.QueryNoAckModeSupported ();
688 m_gdb_comm.GetThreadSuffixSupported ();
689 m_gdb_comm.GetHostInfo ();
690 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000691 return error;
692}
693
694void
695ProcessGDBRemote::DidLaunchOrAttach ()
696{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000697 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
698 if (log)
699 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000700 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000701 {
702 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
703
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000704 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000705
Chris Lattner24943d22010-06-08 16:52:24 +0000706 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000707
Greg Claytoncb8977d2011-03-23 00:09:55 +0000708 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
709 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000710 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000711 ArchSpec &target_arch = GetTarget().GetArchitecture();
712
713 if (target_arch.IsValid())
714 {
715 // If the remote host is ARM and we have apple as the vendor, then
716 // ARM executables and shared libraries can have mixed ARM architectures.
717 // You can have an armv6 executable, and if the host is armv7, then the
718 // system will load the best possible architecture for all shared libraries
719 // it has, so we really need to take the remote host architecture as our
720 // defacto architecture in this case.
721
722 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
723 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
724 {
725 target_arch = gdb_remote_arch;
726 }
727 else
728 {
729 // Fill in what is missing in the triple
730 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
731 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000732 if (target_triple.getVendorName().size() == 0)
733 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000734 target_triple.setVendor (remote_triple.getVendor());
735
Greg Clayton2f085c62011-05-15 01:25:55 +0000736 if (target_triple.getOSName().size() == 0)
737 {
738 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000739
Greg Clayton2f085c62011-05-15 01:25:55 +0000740 if (target_triple.getEnvironmentName().size() == 0)
741 target_triple.setEnvironment (remote_triple.getEnvironment());
742 }
743 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000744 }
745 }
746 else
747 {
748 // The target doesn't have a valid architecture yet, set it from
749 // the architecture we got from the remote GDB server
750 target_arch = gdb_remote_arch;
751 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000752 }
Chris Lattner24943d22010-06-08 16:52:24 +0000753 }
754}
755
756void
757ProcessGDBRemote::DidLaunch ()
758{
759 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000760}
761
762Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000763ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000764{
765 Error error;
766 // Clear out and clean up from any current state
767 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000768 if (attach_pid != LLDB_INVALID_PROCESS_ID)
769 {
Greg Claytona2f74232011-02-24 22:24:29 +0000770 // Make sure we aren't already connected?
771 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000772 {
Greg Claytona2f74232011-02-24 22:24:29 +0000773 char host_port[128];
774 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
775 char connect_url[128];
776 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000777
Greg Claytonb72d0f02011-04-12 05:54:46 +0000778 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000779
780 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000781 {
Greg Claytona2f74232011-02-24 22:24:29 +0000782 const char *error_string = error.AsCString();
783 if (error_string == NULL)
784 error_string = "unable to launch " DEBUGSERVER_BASENAME;
785
786 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000787 }
Greg Claytona2f74232011-02-24 22:24:29 +0000788 else
789 {
790 error = ConnectToDebugserver (connect_url);
791 }
792 }
793
794 if (error.Success())
795 {
796 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000797 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000798 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000799 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000800 }
801 }
Chris Lattner24943d22010-06-08 16:52:24 +0000802 return error;
803}
804
805size_t
806ProcessGDBRemote::AttachInputReaderCallback
807(
808 void *baton,
809 InputReader *reader,
810 lldb::InputReaderAction notification,
811 const char *bytes,
812 size_t bytes_len
813)
814{
815 if (notification == eInputReaderGotToken)
816 {
817 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
818 if (gdb_process->m_waiting_for_attach)
819 gdb_process->m_waiting_for_attach = false;
820 reader->SetIsDone(true);
821 return 1;
822 }
823 return 0;
824}
825
826Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000827ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000828{
829 Error error;
830 // Clear out and clean up from any current state
831 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000832
Chris Lattner24943d22010-06-08 16:52:24 +0000833 if (process_name && process_name[0])
834 {
Greg Claytona2f74232011-02-24 22:24:29 +0000835 // Make sure we aren't already connected?
836 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000837 {
Greg Claytona2f74232011-02-24 22:24:29 +0000838 char host_port[128];
839 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
840 char connect_url[128];
841 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
842
Greg Claytonb72d0f02011-04-12 05:54:46 +0000843 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000844 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000845 {
Greg Claytona2f74232011-02-24 22:24:29 +0000846 const char *error_string = error.AsCString();
847 if (error_string == NULL)
848 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000849
Greg Claytona2f74232011-02-24 22:24:29 +0000850 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000851 }
Greg Claytona2f74232011-02-24 22:24:29 +0000852 else
853 {
854 error = ConnectToDebugserver (connect_url);
855 }
856 }
857
858 if (error.Success())
859 {
860 StreamString packet;
861
862 if (wait_for_launch)
863 packet.PutCString("vAttachWait");
864 else
865 packet.PutCString("vAttachName");
866 packet.PutChar(';');
867 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
868
869 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
870
Chris Lattner24943d22010-06-08 16:52:24 +0000871 }
872 }
Chris Lattner24943d22010-06-08 16:52:24 +0000873 return error;
874}
875
Chris Lattner24943d22010-06-08 16:52:24 +0000876
877void
878ProcessGDBRemote::DidAttach ()
879{
Greg Claytone71e2582011-02-04 01:58:07 +0000880 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000881}
882
883Error
884ProcessGDBRemote::WillResume ()
885{
Greg Claytonc1f45872011-02-12 06:28:37 +0000886 m_continue_c_tids.clear();
887 m_continue_C_tids.clear();
888 m_continue_s_tids.clear();
889 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000890 return Error();
891}
892
893Error
894ProcessGDBRemote::DoResume ()
895{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000896 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000897 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
898 if (log)
899 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000900
901 Listener listener ("gdb-remote.resume-packet-sent");
902 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
903 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000904 StreamString continue_packet;
905 bool continue_packet_error = false;
906 if (m_gdb_comm.HasAnyVContSupport ())
907 {
908 continue_packet.PutCString ("vCont");
909
910 if (!m_continue_c_tids.empty())
911 {
912 if (m_gdb_comm.GetVContSupported ('c'))
913 {
914 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 +0000915 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000916 }
917 else
918 continue_packet_error = true;
919 }
920
921 if (!continue_packet_error && !m_continue_C_tids.empty())
922 {
923 if (m_gdb_comm.GetVContSupported ('C'))
924 {
925 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 +0000926 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000927 }
928 else
929 continue_packet_error = true;
930 }
Greg Claytonb749a262010-12-03 06:02:24 +0000931
Greg Claytonc1f45872011-02-12 06:28:37 +0000932 if (!continue_packet_error && !m_continue_s_tids.empty())
933 {
934 if (m_gdb_comm.GetVContSupported ('s'))
935 {
936 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 +0000937 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000938 }
939 else
940 continue_packet_error = true;
941 }
942
943 if (!continue_packet_error && !m_continue_S_tids.empty())
944 {
945 if (m_gdb_comm.GetVContSupported ('S'))
946 {
947 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 +0000948 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000949 }
950 else
951 continue_packet_error = true;
952 }
953
954 if (continue_packet_error)
955 continue_packet.GetString().clear();
956 }
957 else
958 continue_packet_error = true;
959
960 if (continue_packet_error)
961 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000962 // Either no vCont support, or we tried to use part of the vCont
963 // packet that wasn't supported by the remote GDB server.
964 // We need to try and make a simple packet that can do our continue
965 const size_t num_threads = GetThreadList().GetSize();
966 const size_t num_continue_c_tids = m_continue_c_tids.size();
967 const size_t num_continue_C_tids = m_continue_C_tids.size();
968 const size_t num_continue_s_tids = m_continue_s_tids.size();
969 const size_t num_continue_S_tids = m_continue_S_tids.size();
970 if (num_continue_c_tids > 0)
971 {
972 if (num_continue_c_tids == num_threads)
973 {
974 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000975 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000976 continue_packet.PutChar ('c');
977 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000978 }
979 else if (num_continue_c_tids == 1 &&
980 num_continue_C_tids == 0 &&
981 num_continue_s_tids == 0 &&
982 num_continue_S_tids == 0 )
983 {
984 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000985 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000986 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000987 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000988 }
989 }
990
Greg Claytonde1dd812011-06-24 03:21:43 +0000991 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000992 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000993 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
994 num_continue_C_tids > 0 &&
995 num_continue_s_tids == 0 &&
996 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000997 {
998 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000999 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001000 if (num_continue_C_tids > 1)
1001 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001002 // More that one thread with a signal, yet we don't have
1003 // vCont support and we are being asked to resume each
1004 // thread with a signal, we need to make sure they are
1005 // all the same signal, or we can't issue the continue
1006 // accurately with the current support...
1007 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001008 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001009 continue_packet_error = false;
1010 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1011 {
1012 if (m_continue_C_tids[i].second != continue_signo)
1013 continue_packet_error = true;
1014 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001015 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001016 if (!continue_packet_error)
1017 m_gdb_comm.SetCurrentThreadForRun (-1);
1018 }
1019 else
1020 {
1021 // Set the continue thread ID
1022 continue_packet_error = false;
1023 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001024 }
1025 if (!continue_packet_error)
1026 {
1027 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001028 continue_packet.Printf("C%2.2x", continue_signo);
1029 }
1030 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001031 }
1032
Greg Claytonde1dd812011-06-24 03:21:43 +00001033 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001034 {
1035 if (num_continue_s_tids == num_threads)
1036 {
1037 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001038 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001039 continue_packet.PutChar ('s');
1040 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001041 }
1042 else if (num_continue_c_tids == 0 &&
1043 num_continue_C_tids == 0 &&
1044 num_continue_s_tids == 1 &&
1045 num_continue_S_tids == 0 )
1046 {
1047 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001048 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001049 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001050 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001051 }
1052 }
1053
1054 if (!continue_packet_error && num_continue_S_tids > 0)
1055 {
1056 if (num_continue_S_tids == num_threads)
1057 {
1058 const int step_signo = m_continue_S_tids.front().second;
1059 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001060 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001061 if (num_continue_S_tids > 1)
1062 {
1063 for (size_t i=1; i<num_threads; ++i)
1064 {
1065 if (m_continue_S_tids[i].second != step_signo)
1066 continue_packet_error = true;
1067 }
1068 }
1069 if (!continue_packet_error)
1070 {
1071 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001072 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001073 continue_packet.Printf("S%2.2x", step_signo);
1074 }
1075 }
1076 else if (num_continue_c_tids == 0 &&
1077 num_continue_C_tids == 0 &&
1078 num_continue_s_tids == 0 &&
1079 num_continue_S_tids == 1 )
1080 {
1081 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001082 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001083 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001084 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001085 }
1086 }
1087 }
1088
1089 if (continue_packet_error)
1090 {
1091 error.SetErrorString ("can't make continue packet for this resume");
1092 }
1093 else
1094 {
1095 EventSP event_sp;
1096 TimeValue timeout;
1097 timeout = TimeValue::Now();
1098 timeout.OffsetWithSeconds (5);
1099 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1100
1101 if (listener.WaitForEvent (&timeout, event_sp) == false)
1102 error.SetErrorString("Resume timed out.");
1103 }
Greg Claytonb749a262010-12-03 06:02:24 +00001104 }
1105
Jim Ingham3ae449a2010-11-17 02:32:00 +00001106 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001107}
1108
Chris Lattner24943d22010-06-08 16:52:24 +00001109uint32_t
Greg Clayton37f962e2011-08-22 02:49:39 +00001110ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001111{
1112 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001113 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001114 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001115 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001116 // Update the thread list's stop id immediately so we don't recurse into this function.
Chris Lattner24943d22010-06-08 16:52:24 +00001117
Greg Clayton37f962e2011-08-22 02:49:39 +00001118 std::vector<lldb::tid_t> thread_ids;
1119 bool sequence_mutex_unavailable = false;
1120 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1121 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001122 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001123 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001124 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001125 tid_t tid = thread_ids[i];
1126 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1127 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001128 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001129 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001130 }
Chris Lattner24943d22010-06-08 16:52:24 +00001131 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001132
1133 if (sequence_mutex_unavailable == false)
1134 SetThreadStopInfo (m_last_stop_packet);
1135 return new_thread_list.GetSize(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001136}
1137
1138
1139StateType
1140ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1141{
Greg Clayton261a18b2011-06-02 22:22:38 +00001142 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001143 const char stop_type = stop_packet.GetChar();
1144 switch (stop_type)
1145 {
1146 case 'T':
1147 case 'S':
1148 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001149 if (GetStopID() == 0)
1150 {
1151 // Our first stop, make sure we have a process ID, and also make
1152 // sure we know about our registers
1153 if (GetID() == LLDB_INVALID_PROCESS_ID)
1154 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001155 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001156 if (pid != LLDB_INVALID_PROCESS_ID)
1157 SetID (pid);
1158 }
1159 BuildDynamicRegisterInfo (true);
1160 }
Chris Lattner24943d22010-06-08 16:52:24 +00001161 // Stop with signal and thread info
1162 const uint8_t signo = stop_packet.GetHexU8();
1163 std::string name;
1164 std::string value;
1165 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001166 std::string reason;
1167 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001168 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001169 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001170 uint32_t tid = LLDB_INVALID_THREAD_ID;
1171 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1172 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001173 ThreadSP thread_sp;
1174
Chris Lattner24943d22010-06-08 16:52:24 +00001175 while (stop_packet.GetNameColonValue(name, value))
1176 {
1177 if (name.compare("metype") == 0)
1178 {
1179 // exception type in big endian hex
1180 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1181 }
1182 else if (name.compare("mecount") == 0)
1183 {
1184 // exception count in big endian hex
1185 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1186 }
1187 else if (name.compare("medata") == 0)
1188 {
1189 // exception data in big endian hex
1190 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1191 }
1192 else if (name.compare("thread") == 0)
1193 {
1194 // thread in big endian hex
1195 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001196 // m_thread_list does have its own mutex, but we need to
1197 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1198 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001199 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001200 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001201 if (!thread_sp)
1202 {
1203 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001204 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001205 m_thread_list.AddThread(thread_sp);
1206 }
Chris Lattner24943d22010-06-08 16:52:24 +00001207 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001208 else if (name.compare("hexname") == 0)
1209 {
1210 StringExtractor name_extractor;
1211 // Swap "value" over into "name_extractor"
1212 name_extractor.GetStringRef().swap(value);
1213 // Now convert the HEX bytes into a string value
1214 name_extractor.GetHexByteString (value);
1215 thread_name.swap (value);
1216 }
Chris Lattner24943d22010-06-08 16:52:24 +00001217 else if (name.compare("name") == 0)
1218 {
1219 thread_name.swap (value);
1220 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001221 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001222 {
1223 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1224 }
Greg Clayton65611552011-06-04 01:26:29 +00001225 else if (name.compare("reason") == 0)
1226 {
1227 reason.swap(value);
1228 }
1229 else if (name.compare("description") == 0)
1230 {
1231 StringExtractor desc_extractor;
1232 // Swap "value" over into "name_extractor"
1233 desc_extractor.GetStringRef().swap(value);
1234 // Now convert the HEX bytes into a string value
1235 desc_extractor.GetHexByteString (thread_name);
1236 }
Greg Claytona875b642011-01-09 21:07:35 +00001237 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1238 {
1239 // We have a register number that contains an expedited
1240 // register value. Lets supply this register to our thread
1241 // so it won't have to go and read it.
1242 if (thread_sp)
1243 {
1244 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1245
1246 if (reg != UINT32_MAX)
1247 {
1248 StringExtractor reg_value_extractor;
1249 // Swap "value" over into "reg_value_extractor"
1250 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001251 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1252 {
1253 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1254 name.c_str(),
1255 reg,
1256 reg,
1257 reg_value_extractor.GetStringRef().c_str(),
1258 stop_packet.GetStringRef().c_str());
1259 }
Greg Claytona875b642011-01-09 21:07:35 +00001260 }
1261 }
1262 }
Chris Lattner24943d22010-06-08 16:52:24 +00001263 }
Chris Lattner24943d22010-06-08 16:52:24 +00001264
1265 if (thread_sp)
1266 {
1267 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1268
1269 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001270 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001271 if (exc_type != 0)
1272 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001273 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001274
1275 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1276 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001277 exc_data_size,
1278 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001279 exc_data_size >= 2 ? exc_data[1] : 0,
1280 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001281 }
Greg Clayton65611552011-06-04 01:26:29 +00001282 else
Chris Lattner24943d22010-06-08 16:52:24 +00001283 {
Greg Clayton65611552011-06-04 01:26:29 +00001284 bool handled = false;
1285 if (!reason.empty())
1286 {
1287 if (reason.compare("trace") == 0)
1288 {
1289 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1290 handled = true;
1291 }
1292 else if (reason.compare("breakpoint") == 0)
1293 {
1294 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001295 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001296 if (bp_site_sp)
1297 {
1298 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1299 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1300 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1301 if (bp_site_sp->ValidForThisThread (gdb_thread))
1302 {
1303 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1304 handled = true;
1305 }
1306 }
1307
1308 if (!handled)
1309 {
1310 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1311 }
1312 }
1313 else if (reason.compare("trap") == 0)
1314 {
1315 // Let the trap just use the standard signal stop reason below...
1316 }
1317 else if (reason.compare("watchpoint") == 0)
1318 {
1319 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1320 // TODO: locate the watchpoint somehow...
1321 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1322 handled = true;
1323 }
1324 else if (reason.compare("exception") == 0)
1325 {
1326 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1327 handled = true;
1328 }
1329 }
1330
1331 if (signo)
1332 {
1333 if (signo == SIGTRAP)
1334 {
1335 // Currently we are going to assume SIGTRAP means we are either
1336 // hitting a breakpoint or hardware single stepping.
1337 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001338 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001339 if (bp_site_sp)
1340 {
1341 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1342 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1343 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1344 if (bp_site_sp->ValidForThisThread (gdb_thread))
1345 {
1346 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1347 handled = true;
1348 }
1349 }
1350 if (!handled)
1351 {
1352 // TODO: check for breakpoint or trap opcode in case there is a hard
1353 // coded software trap
1354 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1355 handled = true;
1356 }
1357 }
1358 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001359 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001360 }
1361 else
1362 {
Greg Clayton643ee732010-08-04 01:40:35 +00001363 StopInfoSP invalid_stop_info_sp;
1364 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001365 }
Greg Clayton65611552011-06-04 01:26:29 +00001366
1367 if (!description.empty())
1368 {
1369 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1370 if (stop_info_sp)
1371 {
1372 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001373 }
Greg Clayton65611552011-06-04 01:26:29 +00001374 else
1375 {
1376 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1377 }
1378 }
1379 }
Chris Lattner24943d22010-06-08 16:52:24 +00001380 }
1381 return eStateStopped;
1382 }
1383 break;
1384
1385 case 'W':
1386 // process exited
1387 return eStateExited;
1388
1389 default:
1390 break;
1391 }
1392 return eStateInvalid;
1393}
1394
1395void
1396ProcessGDBRemote::RefreshStateAfterStop ()
1397{
Chris Lattner24943d22010-06-08 16:52:24 +00001398 // Let all threads recover from stopping and do any clean up based
1399 // on the previous thread state (if any).
1400 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001401 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001402}
1403
1404Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001405ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001406{
1407 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001408
Greg Claytona4881d02011-01-22 07:12:45 +00001409 bool timed_out = false;
1410 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001411
1412 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001413 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001414 // We are being asked to halt during an attach. We need to just close
1415 // our file handle and debugserver will go away, and we can be done...
1416 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001417 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001418 else
1419 {
1420 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1421 {
1422 if (timed_out)
1423 error.SetErrorString("timed out sending interrupt packet");
1424 else
1425 error.SetErrorString("unknown error sending interrupt packet");
1426 }
1427 }
Chris Lattner24943d22010-06-08 16:52:24 +00001428 return error;
1429}
1430
1431Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001432ProcessGDBRemote::InterruptIfRunning
1433(
1434 bool discard_thread_plans,
1435 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001436 EventSP &stop_event_sp
1437)
Chris Lattner24943d22010-06-08 16:52:24 +00001438{
1439 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001440
Greg Clayton2860ba92011-01-23 19:58:49 +00001441 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1442
Greg Clayton68ca8232011-01-25 02:58:48 +00001443 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001444 const bool is_running = m_gdb_comm.IsRunning();
1445 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001446 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001447 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001448 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001449 is_running);
1450
Greg Clayton2860ba92011-01-23 19:58:49 +00001451 if (discard_thread_plans)
1452 {
1453 if (log)
1454 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1455 m_thread_list.DiscardThreadPlans();
1456 }
1457 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001458 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001459 if (catch_stop_event)
1460 {
1461 if (log)
1462 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1463 PausePrivateStateThread();
1464 paused_private_state_thread = true;
1465 }
1466
Greg Clayton4fb400f2010-09-27 21:07:38 +00001467 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001468 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001469 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001470
Greg Clayton72e1c782011-01-22 23:43:18 +00001471 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001472 {
1473 if (timed_out)
1474 error.SetErrorString("timed out sending interrupt packet");
1475 else
1476 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001477 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001478 ResumePrivateStateThread();
1479 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001480 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001481
Greg Clayton72e1c782011-01-22 23:43:18 +00001482 if (catch_stop_event)
1483 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001484 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001485 TimeValue timeout_time;
1486 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001487 timeout_time.OffsetWithSeconds(5);
1488 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001489
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001490 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001491 if (log)
1492 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001493
Greg Clayton2860ba92011-01-23 19:58:49 +00001494 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001495 error.SetErrorString("unable to verify target stopped");
1496 }
1497
Greg Clayton68ca8232011-01-25 02:58:48 +00001498 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001499 {
1500 if (log)
1501 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001502 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001503 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001504 }
Chris Lattner24943d22010-06-08 16:52:24 +00001505 return error;
1506}
1507
Greg Clayton4fb400f2010-09-27 21:07:38 +00001508Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001509ProcessGDBRemote::WillDetach ()
1510{
Greg Clayton2860ba92011-01-23 19:58:49 +00001511 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1512 if (log)
1513 log->Printf ("ProcessGDBRemote::WillDetach()");
1514
Greg Clayton72e1c782011-01-22 23:43:18 +00001515 bool discard_thread_plans = true;
1516 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001517 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001518 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001519}
1520
1521Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001522ProcessGDBRemote::DoDetach()
1523{
1524 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001525 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001526 if (log)
1527 log->Printf ("ProcessGDBRemote::DoDetach()");
1528
1529 DisableAllBreakpointSites ();
1530
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001531 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001532
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001533 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1534 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001535 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001536 if (response_size)
1537 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1538 else
1539 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001540 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001541 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001542 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001543
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001544 SetPrivateState (eStateDetached);
1545 ResumePrivateStateThread();
1546
1547 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001548 return error;
1549}
Chris Lattner24943d22010-06-08 16:52:24 +00001550
1551Error
1552ProcessGDBRemote::DoDestroy ()
1553{
1554 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001555 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001556 if (log)
1557 log->Printf ("ProcessGDBRemote::DoDestroy()");
1558
1559 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001560 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001561 {
Jim Ingham8226e942011-10-28 01:11:35 +00001562 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001563 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001564
1565 StringExtractorGDBRemote response;
1566 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001567 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001568 {
1569 char packet_cmd = response.GetChar(0);
1570
1571 if (packet_cmd == 'W' || packet_cmd == 'X')
1572 {
Greg Clayton06709002011-12-06 04:51:14 +00001573 SetLastStopPacket (response);
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001574 SetExitStatus(response.GetHexU8(), NULL);
1575 }
1576 }
1577 else
1578 {
1579 SetExitStatus(SIGABRT, NULL);
1580 //error.SetErrorString("kill packet failed");
1581 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001582 }
1583 }
Chris Lattner24943d22010-06-08 16:52:24 +00001584 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001585 KillDebugserverProcess ();
1586 return error;
1587}
1588
Chris Lattner24943d22010-06-08 16:52:24 +00001589//------------------------------------------------------------------
1590// Process Queries
1591//------------------------------------------------------------------
1592
1593bool
1594ProcessGDBRemote::IsAlive ()
1595{
Greg Clayton58e844b2010-12-08 05:08:21 +00001596 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001597}
1598
1599addr_t
1600ProcessGDBRemote::GetImageInfoAddress()
1601{
1602 if (!m_gdb_comm.IsRunning())
1603 {
1604 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001605 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001606 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001607 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001608 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1609 }
1610 }
1611 return LLDB_INVALID_ADDRESS;
1612}
1613
Chris Lattner24943d22010-06-08 16:52:24 +00001614//------------------------------------------------------------------
1615// Process Memory
1616//------------------------------------------------------------------
1617size_t
1618ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1619{
1620 if (size > m_max_memory_size)
1621 {
1622 // Keep memory read sizes down to a sane limit. This function will be
1623 // called multiple times in order to complete the task by
1624 // lldb_private::Process so it is ok to do this.
1625 size = m_max_memory_size;
1626 }
1627
1628 char packet[64];
1629 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1630 assert (packet_len + 1 < sizeof(packet));
1631 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001632 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001633 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001634 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001635 {
1636 error.Clear();
1637 return response.GetHexBytes(buf, size, '\xdd');
1638 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001639 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001640 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001641 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001642 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1643 else
1644 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1645 }
1646 else
1647 {
1648 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1649 }
1650 return 0;
1651}
1652
1653size_t
1654ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1655{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001656 if (size > m_max_memory_size)
1657 {
1658 // Keep memory read sizes down to a sane limit. This function will be
1659 // called multiple times in order to complete the task by
1660 // lldb_private::Process so it is ok to do this.
1661 size = m_max_memory_size;
1662 }
1663
Chris Lattner24943d22010-06-08 16:52:24 +00001664 StreamString packet;
1665 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001666 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001667 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001668 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001669 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001670 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001671 {
1672 error.Clear();
1673 return size;
1674 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001675 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001676 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001677 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001678 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1679 else
1680 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1681 }
1682 else
1683 {
1684 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1685 }
1686 return 0;
1687}
1688
1689lldb::addr_t
1690ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1691{
Greg Clayton989816b2011-05-14 01:50:35 +00001692 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1693
Greg Clayton2f085c62011-05-15 01:25:55 +00001694 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001695 switch (supported)
1696 {
1697 case eLazyBoolCalculate:
1698 case eLazyBoolYes:
1699 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1700 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1701 return allocated_addr;
1702
1703 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001704 // Call mmap() to create memory in the inferior..
1705 unsigned prot = 0;
1706 if (permissions & lldb::ePermissionsReadable)
1707 prot |= eMmapProtRead;
1708 if (permissions & lldb::ePermissionsWritable)
1709 prot |= eMmapProtWrite;
1710 if (permissions & lldb::ePermissionsExecutable)
1711 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001712
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001713 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1714 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1715 m_addr_to_mmap_size[allocated_addr] = size;
1716 else
1717 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001718 break;
1719 }
1720
Chris Lattner24943d22010-06-08 16:52:24 +00001721 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001722 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001723 else
1724 error.Clear();
1725 return allocated_addr;
1726}
1727
1728Error
Greg Claytona9385532011-11-18 07:03:08 +00001729ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1730 MemoryRegionInfo &region_info)
1731{
1732
1733 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1734 return error;
1735}
1736
1737Error
Chris Lattner24943d22010-06-08 16:52:24 +00001738ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1739{
1740 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001741 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1742
1743 switch (supported)
1744 {
1745 case eLazyBoolCalculate:
1746 // We should never be deallocating memory without allocating memory
1747 // first so we should never get eLazyBoolCalculate
1748 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1749 break;
1750
1751 case eLazyBoolYes:
1752 if (!m_gdb_comm.DeallocateMemory (addr))
1753 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1754 break;
1755
1756 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001757 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001758 {
1759 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001760 if (pos != m_addr_to_mmap_size.end() &&
1761 InferiorCallMunmap(this, addr, pos->second))
1762 m_addr_to_mmap_size.erase (pos);
1763 else
1764 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001765 }
1766 break;
1767 }
1768
Chris Lattner24943d22010-06-08 16:52:24 +00001769 return error;
1770}
1771
1772
1773//------------------------------------------------------------------
1774// Process STDIO
1775//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001776size_t
1777ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1778{
1779 if (m_stdio_communication.IsConnected())
1780 {
1781 ConnectionStatus status;
1782 m_stdio_communication.Write(src, src_len, status, NULL);
1783 }
1784 return 0;
1785}
1786
1787Error
1788ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1789{
1790 Error error;
1791 assert (bp_site != NULL);
1792
Greg Claytone005f2c2010-11-06 01:53:30 +00001793 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001794 user_id_t site_id = bp_site->GetID();
1795 const addr_t addr = bp_site->GetLoadAddress();
1796 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001797 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001798
1799 if (bp_site->IsEnabled())
1800 {
1801 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001802 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 +00001803 return error;
1804 }
1805 else
1806 {
1807 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1808
1809 if (bp_site->HardwarePreferred())
1810 {
1811 // Try and set hardware breakpoint, and if that fails, fall through
1812 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001813 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001814 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001815 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001816 {
1817 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001818 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001819 return error;
1820 }
Chris Lattner24943d22010-06-08 16:52:24 +00001821 }
1822 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001823
1824 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001825 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001826 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1827 {
1828 bp_site->SetEnabled(true);
1829 bp_site->SetType (BreakpointSite::eExternal);
1830 return error;
1831 }
Chris Lattner24943d22010-06-08 16:52:24 +00001832 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001833
1834 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001835 }
1836
1837 if (log)
1838 {
1839 const char *err_string = error.AsCString();
1840 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1841 bp_site->GetLoadAddress(),
1842 err_string ? err_string : "NULL");
1843 }
1844 // We shouldn't reach here on a successful breakpoint enable...
1845 if (error.Success())
1846 error.SetErrorToGenericError();
1847 return error;
1848}
1849
1850Error
1851ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1852{
1853 Error error;
1854 assert (bp_site != NULL);
1855 addr_t addr = bp_site->GetLoadAddress();
1856 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001857 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001858 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001859 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001860
1861 if (bp_site->IsEnabled())
1862 {
1863 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1864
Greg Claytonb72d0f02011-04-12 05:54:46 +00001865 BreakpointSite::Type bp_type = bp_site->GetType();
1866 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001867 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001868 case BreakpointSite::eSoftware:
1869 error = DisableSoftwareBreakpoint (bp_site);
1870 break;
1871
1872 case BreakpointSite::eHardware:
1873 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1874 error.SetErrorToGenericError();
1875 break;
1876
1877 case BreakpointSite::eExternal:
1878 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1879 error.SetErrorToGenericError();
1880 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001881 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001882 if (error.Success())
1883 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001884 }
1885 else
1886 {
1887 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001888 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 +00001889 return error;
1890 }
1891
1892 if (error.Success())
1893 error.SetErrorToGenericError();
1894 return error;
1895}
1896
Johnny Chen21900fb2011-09-06 22:38:36 +00001897// Pre-requisite: wp != NULL.
1898static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00001899GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00001900{
1901 assert(wp);
1902 bool watch_read = wp->WatchpointRead();
1903 bool watch_write = wp->WatchpointWrite();
1904
1905 // watch_read and watch_write cannot both be false.
1906 assert(watch_read || watch_write);
1907 if (watch_read && watch_write)
1908 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001909 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00001910 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00001911 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00001912 return eWatchpointWrite;
1913}
1914
Chris Lattner24943d22010-06-08 16:52:24 +00001915Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001916ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001917{
1918 Error error;
1919 if (wp)
1920 {
1921 user_id_t watchID = wp->GetID();
1922 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001923 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001924 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001925 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00001926 if (wp->IsEnabled())
1927 {
1928 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001929 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001930 return error;
1931 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001932
1933 GDBStoppointType type = GetGDBStoppointType(wp);
1934 // Pass down an appropriate z/Z packet...
1935 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00001936 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001937 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
1938 {
1939 wp->SetEnabled(true);
1940 return error;
1941 }
1942 else
1943 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001944 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001945 else
1946 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00001947 }
1948 else
1949 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001950 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001951 }
1952 if (error.Success())
1953 error.SetErrorToGenericError();
1954 return error;
1955}
1956
1957Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001958ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001959{
1960 Error error;
1961 if (wp)
1962 {
1963 user_id_t watchID = wp->GetID();
1964
Greg Claytone005f2c2010-11-06 01:53:30 +00001965 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001966
1967 addr_t addr = wp->GetLoadAddress();
1968 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001969 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001970
Johnny Chen21900fb2011-09-06 22:38:36 +00001971 if (!wp->IsEnabled())
1972 {
1973 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001974 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00001975 return error;
1976 }
1977
Chris Lattner24943d22010-06-08 16:52:24 +00001978 if (wp->IsHardware())
1979 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001980 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00001981 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00001982 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
1983 {
1984 wp->SetEnabled(false);
1985 return error;
1986 }
1987 else
1988 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001989 }
1990 // TODO: clear software watchpoints if we implement them
1991 }
1992 else
1993 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001994 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001995 }
1996 if (error.Success())
1997 error.SetErrorToGenericError();
1998 return error;
1999}
2000
2001void
2002ProcessGDBRemote::Clear()
2003{
2004 m_flags = 0;
2005 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002006}
2007
2008Error
2009ProcessGDBRemote::DoSignal (int signo)
2010{
2011 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002012 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002013 if (log)
2014 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2015
2016 if (!m_gdb_comm.SendAsyncSignal (signo))
2017 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2018 return error;
2019}
2020
Chris Lattner24943d22010-06-08 16:52:24 +00002021Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002022ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner24943d22010-06-08 16:52:24 +00002023{
2024 Error error;
2025 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2026 {
2027 // If we locate debugserver, keep that located version around
2028 static FileSpec g_debugserver_file_spec;
2029
Greg Claytonb72d0f02011-04-12 05:54:46 +00002030 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002031 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002032 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002033
2034 // Always check to see if we have an environment override for the path
2035 // to the debugserver to use and use it if we do.
2036 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2037 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002038 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002039 else
2040 debugserver_file_spec = g_debugserver_file_spec;
2041 bool debugserver_exists = debugserver_file_spec.Exists();
2042 if (!debugserver_exists)
2043 {
2044 // The debugserver binary is in the LLDB.framework/Resources
2045 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002046 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002047 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002048 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002049 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002050 if (debugserver_exists)
2051 {
2052 g_debugserver_file_spec = debugserver_file_spec;
2053 }
2054 else
2055 {
2056 g_debugserver_file_spec.Clear();
2057 debugserver_file_spec.Clear();
2058 }
Chris Lattner24943d22010-06-08 16:52:24 +00002059 }
2060 }
2061
2062 if (debugserver_exists)
2063 {
2064 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2065
2066 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002067
Greg Claytone005f2c2010-11-06 01:53:30 +00002068 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002069
Greg Claytonb72d0f02011-04-12 05:54:46 +00002070 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002071 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002072
Chris Lattner24943d22010-06-08 16:52:24 +00002073 // Start args with "debugserver /file/path -r --"
2074 debugserver_args.AppendArgument(debugserver_path);
2075 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002076 // use native registers, not the GDB registers
2077 debugserver_args.AppendArgument("--native-regs");
2078 // make debugserver run in its own session so signals generated by
2079 // special terminal key sequences (^C) don't affect debugserver
2080 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002081
Chris Lattner24943d22010-06-08 16:52:24 +00002082 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2083 if (env_debugserver_log_file)
2084 {
2085 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2086 debugserver_args.AppendArgument(arg_cstr);
2087 }
2088
2089 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2090 if (env_debugserver_log_flags)
2091 {
2092 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2093 debugserver_args.AppendArgument(arg_cstr);
2094 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002095// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002096// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002097
Greg Claytonb72d0f02011-04-12 05:54:46 +00002098 // We currently send down all arguments, attach pids, or attach
2099 // process names in dedicated GDB server packets, so we don't need
2100 // to pass them as arguments. This is currently because of all the
2101 // things we need to setup prior to launching: the environment,
2102 // current working dir, file actions, etc.
2103#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002104 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002105 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002106 {
Greg Claytona2f74232011-02-24 22:24:29 +00002107 // Terminate the debugserver args so we can now append the inferior args
2108 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002109
Greg Claytona2f74232011-02-24 22:24:29 +00002110 for (int i = 0; inferior_argv[i] != NULL; ++i)
2111 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002112 }
2113 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2114 {
2115 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2116 debugserver_args.AppendArgument (arg_cstr);
2117 }
2118 else if (attach_name && attach_name[0])
2119 {
2120 if (wait_for_launch)
2121 debugserver_args.AppendArgument ("--waitfor");
2122 else
2123 debugserver_args.AppendArgument ("--attach");
2124 debugserver_args.AppendArgument (attach_name);
2125 }
Chris Lattner24943d22010-06-08 16:52:24 +00002126#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002127
2128 ProcessLaunchInfo::FileAction file_action;
2129
2130 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2131 // to "/dev/null" if we run into any problems.
2132 file_action.Close (STDIN_FILENO);
2133 launch_info.AppendFileAction (file_action);
2134 file_action.Close (STDOUT_FILENO);
2135 launch_info.AppendFileAction (file_action);
2136 file_action.Close (STDERR_FILENO);
2137 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002138
2139 if (log)
2140 {
2141 StreamString strm;
2142 debugserver_args.Dump (&strm);
2143 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2144 }
2145
Greg Clayton1c4642c2011-11-16 05:37:56 +00002146 launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2147
Greg Claytonb72d0f02011-04-12 05:54:46 +00002148 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002149
Greg Claytonb72d0f02011-04-12 05:54:46 +00002150 if (error.Success ())
2151 m_debugserver_pid = launch_info.GetProcessID();
2152 else
Chris Lattner24943d22010-06-08 16:52:24 +00002153 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2154
2155 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002156 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002157 }
2158 else
2159 {
Greg Clayton9c236732011-10-26 00:56:27 +00002160 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002161 }
2162
2163 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2164 StartAsyncThread ();
2165 }
2166 return error;
2167}
2168
2169bool
2170ProcessGDBRemote::MonitorDebugserverProcess
2171(
2172 void *callback_baton,
2173 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002174 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002175 int signo, // Zero for no signal
2176 int exit_status // Exit value of process if signal is zero
2177)
2178{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002179 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2180 // and might not exist anymore, so we need to carefully try to get the
2181 // target for this process first since we have a race condition when
2182 // we are done running between getting the notice that the inferior
2183 // process has died and the debugserver that was debugging this process.
2184 // In our test suite, we are also continually running process after
2185 // process, so we must be very careful to make sure:
2186 // 1 - process object hasn't been deleted already
2187 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002188
2189 // "debugserver_pid" argument passed in is the process ID for
2190 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002191 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002192
Greg Clayton75ccf502010-08-21 02:22:51 +00002193 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002194
Greg Clayton1c4642c2011-11-16 05:37:56 +00002195 // Get a shared pointer to the target that has a matching process pointer.
2196 // This target could be gone, or the target could already have a new process
2197 // object inside of it
2198 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2199
Greg Clayton72e1c782011-01-22 23:43:18 +00002200 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002201 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 +00002202
Greg Clayton1c4642c2011-11-16 05:37:56 +00002203 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002204 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002205 // We found a process in a target that matches, but another thread
2206 // might be in the process of launching a new process that will
2207 // soon replace it, so get a shared pointer to the process so we
2208 // can keep it alive.
2209 ProcessSP process_sp (target_sp->GetProcessSP());
2210 // Now we have a shared pointer to the process that can't go away on us
2211 // so we now make sure it was the same as the one passed in, and also make
2212 // sure that our previous "process *" didn't get deleted and have a new
2213 // "process *" created in its place with the same pointer. To verify this
2214 // we make sure the process has our debugserver process ID. If we pass all
2215 // of these tests, then we are sure that this process is the one we were
2216 // looking for.
2217 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002218 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002219 // Sleep for a half a second to make sure our inferior process has
2220 // time to set its exit status before we set it incorrectly when
2221 // both the debugserver and the inferior process shut down.
2222 usleep (500000);
2223 // If our process hasn't yet exited, debugserver might have died.
2224 // If the process did exit, the we are reaping it.
2225 const StateType state = process->GetState();
2226
2227 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2228 state != eStateInvalid &&
2229 state != eStateUnloaded &&
2230 state != eStateExited &&
2231 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002232 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002233 char error_str[1024];
2234 if (signo)
2235 {
2236 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2237 if (signal_cstr)
2238 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2239 else
2240 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2241 }
Chris Lattner24943d22010-06-08 16:52:24 +00002242 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002243 {
2244 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2245 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002246
Greg Clayton1c4642c2011-11-16 05:37:56 +00002247 process->SetExitStatus (-1, error_str);
2248 }
2249 // Debugserver has exited we need to let our ProcessGDBRemote
2250 // know that it no longer has a debugserver instance
2251 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002252 }
Chris Lattner24943d22010-06-08 16:52:24 +00002253 }
2254 return true;
2255}
2256
2257void
2258ProcessGDBRemote::KillDebugserverProcess ()
2259{
2260 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2261 {
2262 ::kill (m_debugserver_pid, SIGINT);
2263 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2264 }
2265}
2266
2267void
2268ProcessGDBRemote::Initialize()
2269{
2270 static bool g_initialized = false;
2271
2272 if (g_initialized == false)
2273 {
2274 g_initialized = true;
2275 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2276 GetPluginDescriptionStatic(),
2277 CreateInstance);
2278
2279 Log::Callbacks log_callbacks = {
2280 ProcessGDBRemoteLog::DisableLog,
2281 ProcessGDBRemoteLog::EnableLog,
2282 ProcessGDBRemoteLog::ListLogCategories
2283 };
2284
2285 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2286 }
2287}
2288
2289bool
Chris Lattner24943d22010-06-08 16:52:24 +00002290ProcessGDBRemote::StartAsyncThread ()
2291{
Greg Claytone005f2c2010-11-06 01:53:30 +00002292 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002293
2294 if (log)
2295 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2296
2297 // Create a thread that watches our internal state and controls which
2298 // events make it to clients (into the DCProcess event queue).
2299 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002300 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002301}
2302
2303void
2304ProcessGDBRemote::StopAsyncThread ()
2305{
Greg Claytone005f2c2010-11-06 01:53:30 +00002306 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002307
2308 if (log)
2309 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2310
2311 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002312
2313 // This will shut down the async thread.
2314 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002315
2316 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002317 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002318 {
2319 Host::ThreadJoin (m_async_thread, NULL, NULL);
2320 }
2321}
2322
2323
2324void *
2325ProcessGDBRemote::AsyncThread (void *arg)
2326{
2327 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2328
Greg Claytone005f2c2010-11-06 01:53:30 +00002329 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002330 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002331 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002332
2333 Listener listener ("ProcessGDBRemote::AsyncThread");
2334 EventSP event_sp;
2335 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2336 eBroadcastBitAsyncThreadShouldExit;
2337
2338 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2339 {
Greg Claytona2f74232011-02-24 22:24:29 +00002340 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2341
Chris Lattner24943d22010-06-08 16:52:24 +00002342 bool done = false;
2343 while (!done)
2344 {
2345 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002346 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002347 if (listener.WaitForEvent (NULL, event_sp))
2348 {
2349 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002350 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002351 {
Greg Claytona2f74232011-02-24 22:24:29 +00002352 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002353 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 +00002354
Greg Claytona2f74232011-02-24 22:24:29 +00002355 switch (event_type)
2356 {
2357 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002358 {
Greg Claytona2f74232011-02-24 22:24:29 +00002359 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002360
Greg Claytona2f74232011-02-24 22:24:29 +00002361 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002362 {
Greg Claytona2f74232011-02-24 22:24:29 +00002363 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2364 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2365 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002366 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002367
Greg Claytona2f74232011-02-24 22:24:29 +00002368 if (::strstr (continue_cstr, "vAttach") == NULL)
2369 process->SetPrivateState(eStateRunning);
2370 StringExtractorGDBRemote response;
2371 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002372
Greg Claytona2f74232011-02-24 22:24:29 +00002373 switch (stop_state)
2374 {
2375 case eStateStopped:
2376 case eStateCrashed:
2377 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002378 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002379 process->SetPrivateState (stop_state);
2380 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002381
Greg Claytona2f74232011-02-24 22:24:29 +00002382 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002383 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002384 response.SetFilePos(1);
2385 process->SetExitStatus(response.GetHexU8(), NULL);
2386 done = true;
2387 break;
2388
2389 case eStateInvalid:
2390 process->SetExitStatus(-1, "lost connection");
2391 break;
2392
2393 default:
2394 process->SetPrivateState (stop_state);
2395 break;
2396 }
Chris Lattner24943d22010-06-08 16:52:24 +00002397 }
2398 }
Greg Claytona2f74232011-02-24 22:24:29 +00002399 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002400
Greg Claytona2f74232011-02-24 22:24:29 +00002401 case eBroadcastBitAsyncThreadShouldExit:
2402 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002403 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002404 done = true;
2405 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002406
Greg Claytona2f74232011-02-24 22:24:29 +00002407 default:
2408 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002409 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 +00002410 done = true;
2411 break;
2412 }
2413 }
2414 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2415 {
2416 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2417 {
2418 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002419 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002420 }
Chris Lattner24943d22010-06-08 16:52:24 +00002421 }
2422 }
2423 else
2424 {
2425 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002426 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 +00002427 done = true;
2428 }
2429 }
2430 }
2431
2432 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002433 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002434
2435 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2436 return NULL;
2437}
2438
Chris Lattner24943d22010-06-08 16:52:24 +00002439const char *
2440ProcessGDBRemote::GetDispatchQueueNameForThread
2441(
2442 addr_t thread_dispatch_qaddr,
2443 std::string &dispatch_queue_name
2444)
2445{
2446 dispatch_queue_name.clear();
2447 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2448 {
2449 // Cache the dispatch_queue_offsets_addr value so we don't always have
2450 // to look it up
2451 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2452 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002453 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2454 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002455 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002456 if (module_sp)
2457 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2458
2459 if (dispatch_queue_offsets_symbol == NULL)
2460 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002461 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002462 if (module_sp)
2463 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2464 }
Chris Lattner24943d22010-06-08 16:52:24 +00002465 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002466 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002467
2468 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2469 return NULL;
2470 }
2471
2472 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002473 DataExtractor data (memory_buffer,
2474 sizeof(memory_buffer),
2475 m_target.GetArchitecture().GetByteOrder(),
2476 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002477
2478 // Excerpt from src/queue_private.h
2479 struct dispatch_queue_offsets_s
2480 {
2481 uint16_t dqo_version;
2482 uint16_t dqo_label;
2483 uint16_t dqo_label_size;
2484 } dispatch_queue_offsets;
2485
2486
2487 Error error;
2488 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2489 {
2490 uint32_t data_offset = 0;
2491 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2492 {
2493 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2494 {
2495 data_offset = 0;
2496 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2497 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2498 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2499 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2500 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2501 dispatch_queue_name.erase (bytes_read);
2502 }
2503 }
2504 }
2505 }
2506 if (dispatch_queue_name.empty())
2507 return NULL;
2508 return dispatch_queue_name.c_str();
2509}
2510
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002511//uint32_t
2512//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2513//{
2514// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2515// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2516// if (m_local_debugserver)
2517// {
2518// return Host::ListProcessesMatchingName (name, matches, pids);
2519// }
2520// else
2521// {
2522// // FIXME: Implement talking to the remote debugserver.
2523// return 0;
2524// }
2525//
2526//}
2527//
Jim Ingham55e01d82011-01-22 01:33:44 +00002528bool
2529ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2530 lldb_private::StoppointCallbackContext *context,
2531 lldb::user_id_t break_id,
2532 lldb::user_id_t break_loc_id)
2533{
2534 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2535 // run so I can stop it if that's what I want to do.
2536 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2537 if (log)
2538 log->Printf("Hit New Thread Notification breakpoint.");
2539 return false;
2540}
2541
2542
2543bool
2544ProcessGDBRemote::StartNoticingNewThreads()
2545{
2546 static const char *bp_names[] =
2547 {
2548 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002549 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002550 "_pthread_start",
2551 NULL
2552 };
2553
2554 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2555 size_t num_bps = m_thread_observation_bps.size();
2556 if (num_bps != 0)
2557 {
2558 for (int i = 0; i < num_bps; i++)
2559 {
2560 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2561 if (break_sp)
2562 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002563 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002564 log->Printf("Enabled noticing new thread breakpoint.");
2565 break_sp->SetEnabled(true);
2566 }
2567 }
2568 }
2569 else
2570 {
2571 for (int i = 0; bp_names[i] != NULL; i++)
2572 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002573 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002574 if (breakpoint)
2575 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002576 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002577 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2578 m_thread_observation_bps.push_back(breakpoint->GetID());
2579 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2580 }
2581 else
2582 {
2583 if (log)
2584 log->Printf("Failed to create new thread notification breakpoint.");
2585 return false;
2586 }
2587 }
2588 }
2589
2590 return true;
2591}
2592
2593bool
2594ProcessGDBRemote::StopNoticingNewThreads()
2595{
Jim Inghamff276fe2011-02-08 05:19:01 +00002596 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002597 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002598 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002599 size_t num_bps = m_thread_observation_bps.size();
2600 if (num_bps != 0)
2601 {
2602 for (int i = 0; i < num_bps; i++)
2603 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002604
2605 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2606 if (break_sp)
2607 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002608 break_sp->SetEnabled(false);
2609 }
2610 }
2611 }
2612 return true;
2613}
2614
2615