blob: 7e2ad1c3b229356180ea39c3334feef89b19df58 [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
97Process*
98ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
99{
100 return new ProcessGDBRemote (target, listener);
101}
102
103bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000104ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000105{
106 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000107 Module *exe_module = target.GetExecutableModulePointer();
108 if (exe_module)
109 return exe_module->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000110 // However, if there is no executable module, we return true since we might be preparing to attach.
111 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000112}
113
114//----------------------------------------------------------------------
115// ProcessGDBRemote constructor
116//----------------------------------------------------------------------
117ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
118 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000119 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000120 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000121 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000123 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000124 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000125 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000126 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
127 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000128 m_continue_c_tids (),
129 m_continue_C_tids (),
130 m_continue_s_tids (),
131 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000132 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000133 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000134 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000135 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000136{
Greg Claytonff39f742011-04-01 00:29:43 +0000137 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
138 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000139}
140
141//----------------------------------------------------------------------
142// Destructor
143//----------------------------------------------------------------------
144ProcessGDBRemote::~ProcessGDBRemote()
145{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000146 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000147 {
148 Host::ThreadCancel (m_debugserver_thread, NULL);
149 thread_result_t thread_result;
150 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
151 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
152 }
Chris Lattner24943d22010-06-08 16:52:24 +0000153 // m_mach_process.UnregisterNotificationCallbacks (this);
154 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000155 // We need to call finalize on the process before destroying ourselves
156 // to make sure all of the broadcaster cleanup goes as planned. If we
157 // destruct this class, then Process::~Process() might have problems
158 // trying to fully destroy the broadcaster.
159 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000160}
161
162//----------------------------------------------------------------------
163// PluginInterface
164//----------------------------------------------------------------------
165const char *
166ProcessGDBRemote::GetPluginName()
167{
168 return "Process debugging plug-in that uses the GDB remote protocol";
169}
170
171const char *
172ProcessGDBRemote::GetShortPluginName()
173{
174 return GetPluginNameStatic();
175}
176
177uint32_t
178ProcessGDBRemote::GetPluginVersion()
179{
180 return 1;
181}
182
183void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000184ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000185{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000186 if (!force && m_register_info.GetNumRegisters() > 0)
187 return;
188
189 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000190 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000191 uint32_t reg_offset = 0;
192 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000193 StringExtractorGDBRemote::ResponseType response_type;
194 for (response_type = StringExtractorGDBRemote::eResponse;
195 response_type == StringExtractorGDBRemote::eResponse;
196 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000197 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000198 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
199 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000200 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000201 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000202 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000203 response_type = response.GetResponseType();
204 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000205 {
206 std::string name;
207 std::string value;
208 ConstString reg_name;
209 ConstString alt_name;
210 ConstString set_name;
211 RegisterInfo reg_info = { NULL, // Name
212 NULL, // Alt name
213 0, // byte size
214 reg_offset, // offset
215 eEncodingUint, // encoding
216 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000217 {
218 LLDB_INVALID_REGNUM, // GCC reg num
219 LLDB_INVALID_REGNUM, // DWARF reg num
220 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000221 reg_num, // GDB reg num
222 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000223 }
224 };
225
226 while (response.GetNameColonValue(name, value))
227 {
228 if (name.compare("name") == 0)
229 {
230 reg_name.SetCString(value.c_str());
231 }
232 else if (name.compare("alt-name") == 0)
233 {
234 alt_name.SetCString(value.c_str());
235 }
236 else if (name.compare("bitsize") == 0)
237 {
238 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
239 }
240 else if (name.compare("offset") == 0)
241 {
242 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000243 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000244 {
245 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000246 }
247 }
248 else if (name.compare("encoding") == 0)
249 {
250 if (value.compare("uint") == 0)
251 reg_info.encoding = eEncodingUint;
252 else if (value.compare("sint") == 0)
253 reg_info.encoding = eEncodingSint;
254 else if (value.compare("ieee754") == 0)
255 reg_info.encoding = eEncodingIEEE754;
256 else if (value.compare("vector") == 0)
257 reg_info.encoding = eEncodingVector;
258 }
259 else if (name.compare("format") == 0)
260 {
261 if (value.compare("binary") == 0)
262 reg_info.format = eFormatBinary;
263 else if (value.compare("decimal") == 0)
264 reg_info.format = eFormatDecimal;
265 else if (value.compare("hex") == 0)
266 reg_info.format = eFormatHex;
267 else if (value.compare("float") == 0)
268 reg_info.format = eFormatFloat;
269 else if (value.compare("vector-sint8") == 0)
270 reg_info.format = eFormatVectorOfSInt8;
271 else if (value.compare("vector-uint8") == 0)
272 reg_info.format = eFormatVectorOfUInt8;
273 else if (value.compare("vector-sint16") == 0)
274 reg_info.format = eFormatVectorOfSInt16;
275 else if (value.compare("vector-uint16") == 0)
276 reg_info.format = eFormatVectorOfUInt16;
277 else if (value.compare("vector-sint32") == 0)
278 reg_info.format = eFormatVectorOfSInt32;
279 else if (value.compare("vector-uint32") == 0)
280 reg_info.format = eFormatVectorOfUInt32;
281 else if (value.compare("vector-float32") == 0)
282 reg_info.format = eFormatVectorOfFloat32;
283 else if (value.compare("vector-uint128") == 0)
284 reg_info.format = eFormatVectorOfUInt128;
285 }
286 else if (name.compare("set") == 0)
287 {
288 set_name.SetCString(value.c_str());
289 }
290 else if (name.compare("gcc") == 0)
291 {
292 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
293 }
294 else if (name.compare("dwarf") == 0)
295 {
296 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
297 }
298 else if (name.compare("generic") == 0)
299 {
300 if (value.compare("pc") == 0)
301 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
302 else if (value.compare("sp") == 0)
303 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
304 else if (value.compare("fp") == 0)
305 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
306 else if (value.compare("ra") == 0)
307 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
308 else if (value.compare("flags") == 0)
309 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000310 else if (value.find("arg") == 0)
311 {
312 if (value.size() == 4)
313 {
314 switch (value[3])
315 {
316 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
317 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
318 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
319 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
320 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
321 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
322 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
323 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
324 }
325 }
326 }
Chris Lattner24943d22010-06-08 16:52:24 +0000327 }
328 }
329
Jason Molenda53d96862010-06-11 23:44:18 +0000330 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000331 assert (reg_info.byte_size != 0);
332 reg_offset += reg_info.byte_size;
333 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
334 }
335 }
336 else
337 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000338 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000339 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000340 }
341 }
342
343 if (reg_num == 0)
344 {
345 // We didn't get anything. See if we are debugging ARM and fill with
346 // a hard coded register set until we can get an updated debugserver
347 // down on the devices.
Jason Molenda428b5502011-10-06 01:45:46 +0000348
349 if (!GetTarget().GetArchitecture().IsValid()
350 && m_gdb_comm.GetHostArchitecture().IsValid()
351 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm
352 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
353 {
Chris Lattner24943d22010-06-08 16:52:24 +0000354 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000355 }
356 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
357 {
358 m_register_info.HardcodeARMRegisters();
359 }
Chris Lattner24943d22010-06-08 16:52:24 +0000360 }
361 m_register_info.Finalize ();
362}
363
364Error
365ProcessGDBRemote::WillLaunch (Module* module)
366{
367 return WillLaunchOrAttach ();
368}
369
370Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000371ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000372{
373 return WillLaunchOrAttach ();
374}
375
376Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000377ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000378{
379 return WillLaunchOrAttach ();
380}
381
382Error
Greg Claytone71e2582011-02-04 01:58:07 +0000383ProcessGDBRemote::DoConnectRemote (const char *remote_url)
384{
385 Error error (WillLaunchOrAttach ());
386
387 if (error.Fail())
388 return error;
389
Greg Clayton180546b2011-04-30 01:09:13 +0000390 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000391
392 if (error.Fail())
393 return error;
394 StartAsyncThread ();
395
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000396 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000397 if (pid == LLDB_INVALID_PROCESS_ID)
398 {
399 // We don't have a valid process ID, so note that we are connected
400 // and could now request to launch or attach, or get remote process
401 // listings...
402 SetPrivateState (eStateConnected);
403 }
404 else
405 {
406 // We have a valid process
407 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000408 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000409 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000410 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000411 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000412 if (state == eStateStopped)
413 {
414 SetPrivateState (state);
415 }
416 else
417 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
418 }
419 else
420 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
421 }
422 return error;
423}
424
425Error
Chris Lattner24943d22010-06-08 16:52:24 +0000426ProcessGDBRemote::WillLaunchOrAttach ()
427{
428 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000429 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000430 return error;
431}
432
433//----------------------------------------------------------------------
434// Process Control
435//----------------------------------------------------------------------
436Error
437ProcessGDBRemote::DoLaunch
438(
439 Module* module,
440 char const *argv[],
441 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000442 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000443 const char *stdin_path,
444 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000445 const char *stderr_path,
446 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000447)
448{
Greg Clayton4b407112010-09-30 21:49:03 +0000449 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000450 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
451 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
452 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000453 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000454
455 ObjectFile * object_file = module->GetObjectFile();
456 if (object_file)
457 {
Chris Lattner24943d22010-06-08 16:52:24 +0000458 char host_port[128];
459 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000460 char connect_url[128];
461 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000462
Greg Claytona2f74232011-02-24 22:24:29 +0000463 // Make sure we aren't already connected?
464 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000465 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000466 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000467 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000468 {
Johnny Chenc143d622011-08-09 18:56:45 +0000469 if (log)
470 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000471 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000472 }
Chris Lattner24943d22010-06-08 16:52:24 +0000473
Greg Claytone71e2582011-02-04 01:58:07 +0000474 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000475 }
476
477 if (error.Success())
478 {
479 lldb_utility::PseudoTerminal pty;
480 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000481
482 // If the debugserver is local and we aren't disabling STDIO, lets use
483 // a pseudo terminal to instead of relying on the 'O' packets for stdio
484 // since 'O' packets can really slow down debugging if the inferior
485 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000486 PlatformSP platform_sp (m_target.GetPlatform());
487 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000488 {
489 const char *slave_name = NULL;
490 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000491 {
Greg Claytona2f74232011-02-24 22:24:29 +0000492 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
493 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000494 }
Greg Claytona2f74232011-02-24 22:24:29 +0000495 if (stdin_path == NULL)
496 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000497
Greg Claytona2f74232011-02-24 22:24:29 +0000498 if (stdout_path == NULL)
499 stdout_path = slave_name;
500
501 if (stderr_path == NULL)
502 stderr_path = slave_name;
503 }
504
Greg Claytonafb81862011-03-02 21:34:46 +0000505 // Set STDIN to /dev/null if we want STDIO disabled or if either
506 // STDOUT or STDERR have been set to something and STDIN hasn't
507 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000508 stdin_path = "/dev/null";
509
Greg Claytonafb81862011-03-02 21:34:46 +0000510 // Set STDOUT to /dev/null if we want STDIO disabled or if either
511 // STDIN or STDERR have been set to something and STDOUT hasn't
512 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000513 stdout_path = "/dev/null";
514
Greg Claytonafb81862011-03-02 21:34:46 +0000515 // Set STDERR to /dev/null if we want STDIO disabled or if either
516 // STDIN or STDOUT have been set to something and STDERR hasn't
517 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000518 stderr_path = "/dev/null";
519
520 if (stdin_path)
521 m_gdb_comm.SetSTDIN (stdin_path);
522 if (stdout_path)
523 m_gdb_comm.SetSTDOUT (stdout_path);
524 if (stderr_path)
525 m_gdb_comm.SetSTDERR (stderr_path);
526
527 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
528
Greg Claytona4582402011-05-08 04:53:50 +0000529 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000530
531 if (working_dir && working_dir[0])
532 {
533 m_gdb_comm.SetWorkingDir (working_dir);
534 }
535
536 // Send the environment and the program + arguments after we connect
537 if (envp)
538 {
539 const char *env_entry;
540 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000541 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000542 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000543 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000544 }
Greg Claytona2f74232011-02-24 22:24:29 +0000545 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000546
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000547 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
548 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
Greg Claytona2f74232011-02-24 22:24:29 +0000549 if (arg_packet_err == 0)
550 {
551 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000552 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000553 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000554 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000555 }
556 else
557 {
Greg Claytona2f74232011-02-24 22:24:29 +0000558 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000559 }
Greg Claytona2f74232011-02-24 22:24:29 +0000560 }
561 else
562 {
563 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
564 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000565
566 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000567
Greg Claytona2f74232011-02-24 22:24:29 +0000568 if (GetID() == LLDB_INVALID_PROCESS_ID)
569 {
Johnny Chenc143d622011-08-09 18:56:45 +0000570 if (log)
571 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000572 KillDebugserverProcess ();
573 return error;
574 }
575
Greg Clayton261a18b2011-06-02 22:22:38 +0000576 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000577 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000578 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000579
580 if (!disable_stdio)
581 {
582 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
583 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
584 }
Chris Lattner24943d22010-06-08 16:52:24 +0000585 }
586 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000587 else
588 {
Johnny Chenc143d622011-08-09 18:56:45 +0000589 if (log)
590 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000591 }
Chris Lattner24943d22010-06-08 16:52:24 +0000592 }
593 else
594 {
595 // Set our user ID to an invalid process ID.
596 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000597 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
598 module->GetFileSpec().GetFilename().AsCString(),
599 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000600 }
Chris Lattner24943d22010-06-08 16:52:24 +0000601 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000602
Chris Lattner24943d22010-06-08 16:52:24 +0000603}
604
605
606Error
Greg Claytone71e2582011-02-04 01:58:07 +0000607ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000608{
609 Error error;
610 // Sleep and wait a bit for debugserver to start to listen...
611 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
612 if (conn_ap.get())
613 {
Chris Lattner24943d22010-06-08 16:52:24 +0000614 const uint32_t max_retry_count = 50;
615 uint32_t retry_count = 0;
616 while (!m_gdb_comm.IsConnected())
617 {
Greg Claytone71e2582011-02-04 01:58:07 +0000618 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000619 {
620 m_gdb_comm.SetConnection (conn_ap.release());
621 break;
622 }
623 retry_count++;
624
625 if (retry_count >= max_retry_count)
626 break;
627
628 usleep (100000);
629 }
630 }
631
632 if (!m_gdb_comm.IsConnected())
633 {
634 if (error.Success())
635 error.SetErrorString("not connected to remote gdb server");
636 return error;
637 }
638
Greg Clayton24bc5d92011-03-30 18:16:51 +0000639 // We always seem to be able to open a connection to a local port
640 // so we need to make sure we can then send data to it. If we can't
641 // then we aren't actually connected to anything, so try and do the
642 // handshake with the remote GDB server and make sure that goes
643 // alright.
644 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000645 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000646 m_gdb_comm.Disconnect();
647 if (error.Success())
648 error.SetErrorString("not connected to remote gdb server");
649 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000650 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000651 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
652 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
653 this,
654 m_debugserver_pid,
655 false);
656 m_gdb_comm.ResetDiscoverableSettings();
657 m_gdb_comm.QueryNoAckModeSupported ();
658 m_gdb_comm.GetThreadSuffixSupported ();
659 m_gdb_comm.GetHostInfo ();
660 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000661 return error;
662}
663
664void
665ProcessGDBRemote::DidLaunchOrAttach ()
666{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000667 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
668 if (log)
669 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000670 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000671 {
672 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
673
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000674 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000675
Chris Lattner24943d22010-06-08 16:52:24 +0000676 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000677
Greg Claytoncb8977d2011-03-23 00:09:55 +0000678 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
679 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000680 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000681 ArchSpec &target_arch = GetTarget().GetArchitecture();
682
683 if (target_arch.IsValid())
684 {
685 // If the remote host is ARM and we have apple as the vendor, then
686 // ARM executables and shared libraries can have mixed ARM architectures.
687 // You can have an armv6 executable, and if the host is armv7, then the
688 // system will load the best possible architecture for all shared libraries
689 // it has, so we really need to take the remote host architecture as our
690 // defacto architecture in this case.
691
692 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
693 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
694 {
695 target_arch = gdb_remote_arch;
696 }
697 else
698 {
699 // Fill in what is missing in the triple
700 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
701 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000702 if (target_triple.getVendorName().size() == 0)
703 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000704 target_triple.setVendor (remote_triple.getVendor());
705
Greg Clayton2f085c62011-05-15 01:25:55 +0000706 if (target_triple.getOSName().size() == 0)
707 {
708 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000709
Greg Clayton2f085c62011-05-15 01:25:55 +0000710 if (target_triple.getEnvironmentName().size() == 0)
711 target_triple.setEnvironment (remote_triple.getEnvironment());
712 }
713 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000714 }
715 }
716 else
717 {
718 // The target doesn't have a valid architecture yet, set it from
719 // the architecture we got from the remote GDB server
720 target_arch = gdb_remote_arch;
721 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000722 }
Chris Lattner24943d22010-06-08 16:52:24 +0000723 }
724}
725
726void
727ProcessGDBRemote::DidLaunch ()
728{
729 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000730}
731
732Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000733ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000734{
735 Error error;
736 // Clear out and clean up from any current state
737 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000738 if (attach_pid != LLDB_INVALID_PROCESS_ID)
739 {
Greg Claytona2f74232011-02-24 22:24:29 +0000740 // Make sure we aren't already connected?
741 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000742 {
Greg Claytona2f74232011-02-24 22:24:29 +0000743 char host_port[128];
744 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
745 char connect_url[128];
746 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000747
Greg Claytonb72d0f02011-04-12 05:54:46 +0000748 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000749
750 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000751 {
Greg Claytona2f74232011-02-24 22:24:29 +0000752 const char *error_string = error.AsCString();
753 if (error_string == NULL)
754 error_string = "unable to launch " DEBUGSERVER_BASENAME;
755
756 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000757 }
Greg Claytona2f74232011-02-24 22:24:29 +0000758 else
759 {
760 error = ConnectToDebugserver (connect_url);
761 }
762 }
763
764 if (error.Success())
765 {
766 char packet[64];
767 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
768
769 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000770 }
771 }
Chris Lattner24943d22010-06-08 16:52:24 +0000772 return error;
773}
774
775size_t
776ProcessGDBRemote::AttachInputReaderCallback
777(
778 void *baton,
779 InputReader *reader,
780 lldb::InputReaderAction notification,
781 const char *bytes,
782 size_t bytes_len
783)
784{
785 if (notification == eInputReaderGotToken)
786 {
787 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
788 if (gdb_process->m_waiting_for_attach)
789 gdb_process->m_waiting_for_attach = false;
790 reader->SetIsDone(true);
791 return 1;
792 }
793 return 0;
794}
795
796Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000797ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000798{
799 Error error;
800 // Clear out and clean up from any current state
801 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000802
Chris Lattner24943d22010-06-08 16:52:24 +0000803 if (process_name && process_name[0])
804 {
Greg Claytona2f74232011-02-24 22:24:29 +0000805 // Make sure we aren't already connected?
806 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000807 {
Greg Claytona2f74232011-02-24 22:24:29 +0000808 char host_port[128];
809 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
810 char connect_url[128];
811 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
812
Greg Claytonb72d0f02011-04-12 05:54:46 +0000813 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000814 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000815 {
Greg Claytona2f74232011-02-24 22:24:29 +0000816 const char *error_string = error.AsCString();
817 if (error_string == NULL)
818 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000819
Greg Claytona2f74232011-02-24 22:24:29 +0000820 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000821 }
Greg Claytona2f74232011-02-24 22:24:29 +0000822 else
823 {
824 error = ConnectToDebugserver (connect_url);
825 }
826 }
827
828 if (error.Success())
829 {
830 StreamString packet;
831
832 if (wait_for_launch)
833 packet.PutCString("vAttachWait");
834 else
835 packet.PutCString("vAttachName");
836 packet.PutChar(';');
837 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
838
839 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
840
Chris Lattner24943d22010-06-08 16:52:24 +0000841 }
842 }
Chris Lattner24943d22010-06-08 16:52:24 +0000843 return error;
844}
845
Chris Lattner24943d22010-06-08 16:52:24 +0000846
847void
848ProcessGDBRemote::DidAttach ()
849{
Greg Claytone71e2582011-02-04 01:58:07 +0000850 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000851}
852
853Error
854ProcessGDBRemote::WillResume ()
855{
Greg Claytonc1f45872011-02-12 06:28:37 +0000856 m_continue_c_tids.clear();
857 m_continue_C_tids.clear();
858 m_continue_s_tids.clear();
859 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000860 return Error();
861}
862
863Error
864ProcessGDBRemote::DoResume ()
865{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000866 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000867 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
868 if (log)
869 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000870
871 Listener listener ("gdb-remote.resume-packet-sent");
872 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
873 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000874 StreamString continue_packet;
875 bool continue_packet_error = false;
876 if (m_gdb_comm.HasAnyVContSupport ())
877 {
878 continue_packet.PutCString ("vCont");
879
880 if (!m_continue_c_tids.empty())
881 {
882 if (m_gdb_comm.GetVContSupported ('c'))
883 {
884 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)
885 continue_packet.Printf(";c:%4.4x", *t_pos);
886 }
887 else
888 continue_packet_error = true;
889 }
890
891 if (!continue_packet_error && !m_continue_C_tids.empty())
892 {
893 if (m_gdb_comm.GetVContSupported ('C'))
894 {
895 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)
896 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
897 }
898 else
899 continue_packet_error = true;
900 }
Greg Claytonb749a262010-12-03 06:02:24 +0000901
Greg Claytonc1f45872011-02-12 06:28:37 +0000902 if (!continue_packet_error && !m_continue_s_tids.empty())
903 {
904 if (m_gdb_comm.GetVContSupported ('s'))
905 {
906 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)
907 continue_packet.Printf(";s:%4.4x", *t_pos);
908 }
909 else
910 continue_packet_error = true;
911 }
912
913 if (!continue_packet_error && !m_continue_S_tids.empty())
914 {
915 if (m_gdb_comm.GetVContSupported ('S'))
916 {
917 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)
918 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
919 }
920 else
921 continue_packet_error = true;
922 }
923
924 if (continue_packet_error)
925 continue_packet.GetString().clear();
926 }
927 else
928 continue_packet_error = true;
929
930 if (continue_packet_error)
931 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000932 // Either no vCont support, or we tried to use part of the vCont
933 // packet that wasn't supported by the remote GDB server.
934 // We need to try and make a simple packet that can do our continue
935 const size_t num_threads = GetThreadList().GetSize();
936 const size_t num_continue_c_tids = m_continue_c_tids.size();
937 const size_t num_continue_C_tids = m_continue_C_tids.size();
938 const size_t num_continue_s_tids = m_continue_s_tids.size();
939 const size_t num_continue_S_tids = m_continue_S_tids.size();
940 if (num_continue_c_tids > 0)
941 {
942 if (num_continue_c_tids == num_threads)
943 {
944 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000945 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000946 continue_packet.PutChar ('c');
947 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000948 }
949 else if (num_continue_c_tids == 1 &&
950 num_continue_C_tids == 0 &&
951 num_continue_s_tids == 0 &&
952 num_continue_S_tids == 0 )
953 {
954 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000955 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000956 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000957 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000958 }
959 }
960
Greg Claytonde1dd812011-06-24 03:21:43 +0000961 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000962 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000963 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
964 num_continue_C_tids > 0 &&
965 num_continue_s_tids == 0 &&
966 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000967 {
968 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000969 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +0000970 if (num_continue_C_tids > 1)
971 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000972 // More that one thread with a signal, yet we don't have
973 // vCont support and we are being asked to resume each
974 // thread with a signal, we need to make sure they are
975 // all the same signal, or we can't issue the continue
976 // accurately with the current support...
977 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +0000978 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000979 continue_packet_error = false;
980 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
981 {
982 if (m_continue_C_tids[i].second != continue_signo)
983 continue_packet_error = true;
984 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000985 }
Greg Claytonde1dd812011-06-24 03:21:43 +0000986 if (!continue_packet_error)
987 m_gdb_comm.SetCurrentThreadForRun (-1);
988 }
989 else
990 {
991 // Set the continue thread ID
992 continue_packet_error = false;
993 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000994 }
995 if (!continue_packet_error)
996 {
997 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +0000998 continue_packet.Printf("C%2.2x", continue_signo);
999 }
1000 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001001 }
1002
Greg Claytonde1dd812011-06-24 03:21:43 +00001003 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001004 {
1005 if (num_continue_s_tids == num_threads)
1006 {
1007 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001008 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001009 continue_packet.PutChar ('s');
1010 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001011 }
1012 else if (num_continue_c_tids == 0 &&
1013 num_continue_C_tids == 0 &&
1014 num_continue_s_tids == 1 &&
1015 num_continue_S_tids == 0 )
1016 {
1017 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001018 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001019 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001020 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001021 }
1022 }
1023
1024 if (!continue_packet_error && num_continue_S_tids > 0)
1025 {
1026 if (num_continue_S_tids == num_threads)
1027 {
1028 const int step_signo = m_continue_S_tids.front().second;
1029 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001030 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001031 if (num_continue_S_tids > 1)
1032 {
1033 for (size_t i=1; i<num_threads; ++i)
1034 {
1035 if (m_continue_S_tids[i].second != step_signo)
1036 continue_packet_error = true;
1037 }
1038 }
1039 if (!continue_packet_error)
1040 {
1041 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001042 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001043 continue_packet.Printf("S%2.2x", step_signo);
1044 }
1045 }
1046 else if (num_continue_c_tids == 0 &&
1047 num_continue_C_tids == 0 &&
1048 num_continue_s_tids == 0 &&
1049 num_continue_S_tids == 1 )
1050 {
1051 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001052 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001053 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001054 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001055 }
1056 }
1057 }
1058
1059 if (continue_packet_error)
1060 {
1061 error.SetErrorString ("can't make continue packet for this resume");
1062 }
1063 else
1064 {
1065 EventSP event_sp;
1066 TimeValue timeout;
1067 timeout = TimeValue::Now();
1068 timeout.OffsetWithSeconds (5);
1069 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1070
1071 if (listener.WaitForEvent (&timeout, event_sp) == false)
1072 error.SetErrorString("Resume timed out.");
1073 }
Greg Claytonb749a262010-12-03 06:02:24 +00001074 }
1075
Jim Ingham3ae449a2010-11-17 02:32:00 +00001076 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001077}
1078
Chris Lattner24943d22010-06-08 16:52:24 +00001079uint32_t
Greg Clayton37f962e2011-08-22 02:49:39 +00001080ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001081{
1082 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001083 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001084 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001085 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001086 // Update the thread list's stop id immediately so we don't recurse into this function.
Chris Lattner24943d22010-06-08 16:52:24 +00001087
Greg Clayton37f962e2011-08-22 02:49:39 +00001088 std::vector<lldb::tid_t> thread_ids;
1089 bool sequence_mutex_unavailable = false;
1090 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1091 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001092 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001093 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001094 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001095 tid_t tid = thread_ids[i];
1096 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1097 if (!thread_sp)
1098 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1099 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001100 }
Chris Lattner24943d22010-06-08 16:52:24 +00001101 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001102
1103 if (sequence_mutex_unavailable == false)
1104 SetThreadStopInfo (m_last_stop_packet);
1105 return new_thread_list.GetSize(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001106}
1107
1108
1109StateType
1110ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1111{
Greg Clayton261a18b2011-06-02 22:22:38 +00001112 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001113 const char stop_type = stop_packet.GetChar();
1114 switch (stop_type)
1115 {
1116 case 'T':
1117 case 'S':
1118 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001119 if (GetStopID() == 0)
1120 {
1121 // Our first stop, make sure we have a process ID, and also make
1122 // sure we know about our registers
1123 if (GetID() == LLDB_INVALID_PROCESS_ID)
1124 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001125 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001126 if (pid != LLDB_INVALID_PROCESS_ID)
1127 SetID (pid);
1128 }
1129 BuildDynamicRegisterInfo (true);
1130 }
Chris Lattner24943d22010-06-08 16:52:24 +00001131 // Stop with signal and thread info
1132 const uint8_t signo = stop_packet.GetHexU8();
1133 std::string name;
1134 std::string value;
1135 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001136 std::string reason;
1137 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001138 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001139 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001140 uint32_t tid = LLDB_INVALID_THREAD_ID;
1141 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1142 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001143 ThreadSP thread_sp;
1144
Chris Lattner24943d22010-06-08 16:52:24 +00001145 while (stop_packet.GetNameColonValue(name, value))
1146 {
1147 if (name.compare("metype") == 0)
1148 {
1149 // exception type in big endian hex
1150 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1151 }
1152 else if (name.compare("mecount") == 0)
1153 {
1154 // exception count in big endian hex
1155 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1156 }
1157 else if (name.compare("medata") == 0)
1158 {
1159 // exception data in big endian hex
1160 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1161 }
1162 else if (name.compare("thread") == 0)
1163 {
1164 // thread in big endian hex
1165 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001166 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001167 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001168 if (!thread_sp)
1169 {
1170 // Create the thread if we need to
1171 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1172 m_thread_list.AddThread(thread_sp);
1173 }
Chris Lattner24943d22010-06-08 16:52:24 +00001174 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001175 else if (name.compare("hexname") == 0)
1176 {
1177 StringExtractor name_extractor;
1178 // Swap "value" over into "name_extractor"
1179 name_extractor.GetStringRef().swap(value);
1180 // Now convert the HEX bytes into a string value
1181 name_extractor.GetHexByteString (value);
1182 thread_name.swap (value);
1183 }
Chris Lattner24943d22010-06-08 16:52:24 +00001184 else if (name.compare("name") == 0)
1185 {
1186 thread_name.swap (value);
1187 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001188 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001189 {
1190 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1191 }
Greg Clayton65611552011-06-04 01:26:29 +00001192 else if (name.compare("reason") == 0)
1193 {
1194 reason.swap(value);
1195 }
1196 else if (name.compare("description") == 0)
1197 {
1198 StringExtractor desc_extractor;
1199 // Swap "value" over into "name_extractor"
1200 desc_extractor.GetStringRef().swap(value);
1201 // Now convert the HEX bytes into a string value
1202 desc_extractor.GetHexByteString (thread_name);
1203 }
Greg Claytona875b642011-01-09 21:07:35 +00001204 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1205 {
1206 // We have a register number that contains an expedited
1207 // register value. Lets supply this register to our thread
1208 // so it won't have to go and read it.
1209 if (thread_sp)
1210 {
1211 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1212
1213 if (reg != UINT32_MAX)
1214 {
1215 StringExtractor reg_value_extractor;
1216 // Swap "value" over into "reg_value_extractor"
1217 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001218 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1219 {
1220 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1221 name.c_str(),
1222 reg,
1223 reg,
1224 reg_value_extractor.GetStringRef().c_str(),
1225 stop_packet.GetStringRef().c_str());
1226 }
Greg Claytona875b642011-01-09 21:07:35 +00001227 }
1228 }
1229 }
Chris Lattner24943d22010-06-08 16:52:24 +00001230 }
Chris Lattner24943d22010-06-08 16:52:24 +00001231
1232 if (thread_sp)
1233 {
1234 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1235
1236 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001237 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001238 if (exc_type != 0)
1239 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001240 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001241
1242 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1243 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001244 exc_data_size,
1245 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001246 exc_data_size >= 2 ? exc_data[1] : 0,
1247 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001248 }
Greg Clayton65611552011-06-04 01:26:29 +00001249 else
Chris Lattner24943d22010-06-08 16:52:24 +00001250 {
Greg Clayton65611552011-06-04 01:26:29 +00001251 bool handled = false;
1252 if (!reason.empty())
1253 {
1254 if (reason.compare("trace") == 0)
1255 {
1256 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1257 handled = true;
1258 }
1259 else if (reason.compare("breakpoint") == 0)
1260 {
1261 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1262 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1263 if (bp_site_sp)
1264 {
1265 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1266 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1267 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1268 if (bp_site_sp->ValidForThisThread (gdb_thread))
1269 {
1270 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1271 handled = true;
1272 }
1273 }
1274
1275 if (!handled)
1276 {
1277 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1278 }
1279 }
1280 else if (reason.compare("trap") == 0)
1281 {
1282 // Let the trap just use the standard signal stop reason below...
1283 }
1284 else if (reason.compare("watchpoint") == 0)
1285 {
1286 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1287 // TODO: locate the watchpoint somehow...
1288 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1289 handled = true;
1290 }
1291 else if (reason.compare("exception") == 0)
1292 {
1293 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1294 handled = true;
1295 }
1296 }
1297
1298 if (signo)
1299 {
1300 if (signo == SIGTRAP)
1301 {
1302 // Currently we are going to assume SIGTRAP means we are either
1303 // hitting a breakpoint or hardware single stepping.
1304 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1305 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1306 if (bp_site_sp)
1307 {
1308 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1309 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1310 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1311 if (bp_site_sp->ValidForThisThread (gdb_thread))
1312 {
1313 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1314 handled = true;
1315 }
1316 }
1317 if (!handled)
1318 {
1319 // TODO: check for breakpoint or trap opcode in case there is a hard
1320 // coded software trap
1321 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1322 handled = true;
1323 }
1324 }
1325 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001326 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001327 }
1328 else
1329 {
Greg Clayton643ee732010-08-04 01:40:35 +00001330 StopInfoSP invalid_stop_info_sp;
1331 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001332 }
Greg Clayton65611552011-06-04 01:26:29 +00001333
1334 if (!description.empty())
1335 {
1336 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1337 if (stop_info_sp)
1338 {
1339 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001340 }
Greg Clayton65611552011-06-04 01:26:29 +00001341 else
1342 {
1343 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1344 }
1345 }
1346 }
Chris Lattner24943d22010-06-08 16:52:24 +00001347 }
1348 return eStateStopped;
1349 }
1350 break;
1351
1352 case 'W':
1353 // process exited
1354 return eStateExited;
1355
1356 default:
1357 break;
1358 }
1359 return eStateInvalid;
1360}
1361
1362void
1363ProcessGDBRemote::RefreshStateAfterStop ()
1364{
Chris Lattner24943d22010-06-08 16:52:24 +00001365 // Let all threads recover from stopping and do any clean up based
1366 // on the previous thread state (if any).
1367 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001368 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001369}
1370
1371Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001372ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001373{
1374 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001375
Greg Claytona4881d02011-01-22 07:12:45 +00001376 bool timed_out = false;
1377 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001378
1379 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001380 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001381 // We are being asked to halt during an attach. We need to just close
1382 // our file handle and debugserver will go away, and we can be done...
1383 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001384 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001385 else
1386 {
1387 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1388 {
1389 if (timed_out)
1390 error.SetErrorString("timed out sending interrupt packet");
1391 else
1392 error.SetErrorString("unknown error sending interrupt packet");
1393 }
1394 }
Chris Lattner24943d22010-06-08 16:52:24 +00001395 return error;
1396}
1397
1398Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001399ProcessGDBRemote::InterruptIfRunning
1400(
1401 bool discard_thread_plans,
1402 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001403 EventSP &stop_event_sp
1404)
Chris Lattner24943d22010-06-08 16:52:24 +00001405{
1406 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001407
Greg Clayton2860ba92011-01-23 19:58:49 +00001408 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1409
Greg Clayton68ca8232011-01-25 02:58:48 +00001410 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001411 const bool is_running = m_gdb_comm.IsRunning();
1412 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001413 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001414 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001415 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001416 is_running);
1417
Greg Clayton2860ba92011-01-23 19:58:49 +00001418 if (discard_thread_plans)
1419 {
1420 if (log)
1421 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1422 m_thread_list.DiscardThreadPlans();
1423 }
1424 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001425 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001426 if (catch_stop_event)
1427 {
1428 if (log)
1429 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1430 PausePrivateStateThread();
1431 paused_private_state_thread = true;
1432 }
1433
Greg Clayton4fb400f2010-09-27 21:07:38 +00001434 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001435 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001436 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001437
Greg Clayton72e1c782011-01-22 23:43:18 +00001438 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001439 {
1440 if (timed_out)
1441 error.SetErrorString("timed out sending interrupt packet");
1442 else
1443 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001444 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001445 ResumePrivateStateThread();
1446 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001447 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001448
Greg Clayton72e1c782011-01-22 23:43:18 +00001449 if (catch_stop_event)
1450 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001451 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001452 TimeValue timeout_time;
1453 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001454 timeout_time.OffsetWithSeconds(5);
1455 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001456
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001457 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001458 if (log)
1459 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001460
Greg Clayton2860ba92011-01-23 19:58:49 +00001461 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001462 error.SetErrorString("unable to verify target stopped");
1463 }
1464
Greg Clayton68ca8232011-01-25 02:58:48 +00001465 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001466 {
1467 if (log)
1468 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001469 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001470 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001471 }
Chris Lattner24943d22010-06-08 16:52:24 +00001472 return error;
1473}
1474
Greg Clayton4fb400f2010-09-27 21:07:38 +00001475Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001476ProcessGDBRemote::WillDetach ()
1477{
Greg Clayton2860ba92011-01-23 19:58:49 +00001478 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1479 if (log)
1480 log->Printf ("ProcessGDBRemote::WillDetach()");
1481
Greg Clayton72e1c782011-01-22 23:43:18 +00001482 bool discard_thread_plans = true;
1483 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001484 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001485 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001486}
1487
1488Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001489ProcessGDBRemote::DoDetach()
1490{
1491 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001492 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001493 if (log)
1494 log->Printf ("ProcessGDBRemote::DoDetach()");
1495
1496 DisableAllBreakpointSites ();
1497
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001498 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001499
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001500 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1501 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001502 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001503 if (response_size)
1504 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1505 else
1506 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001507 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001508 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001509 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001510
Greg Clayton4fb400f2010-09-27 21:07:38 +00001511 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001512 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001513
1514 SetPrivateState (eStateDetached);
1515 ResumePrivateStateThread();
1516
1517 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001518 return error;
1519}
Chris Lattner24943d22010-06-08 16:52:24 +00001520
1521Error
1522ProcessGDBRemote::DoDestroy ()
1523{
1524 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001525 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001526 if (log)
1527 log->Printf ("ProcessGDBRemote::DoDestroy()");
1528
1529 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001530 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001531 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001532 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001533 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001534 // We are being asked to halt during an attach. We need to just close
1535 // our file handle and debugserver will go away, and we can be done...
1536 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001537 }
1538 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001539 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001540
1541 StringExtractorGDBRemote response;
1542 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001543 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001544 {
1545 char packet_cmd = response.GetChar(0);
1546
1547 if (packet_cmd == 'W' || packet_cmd == 'X')
1548 {
1549 m_last_stop_packet = response;
1550 SetExitStatus(response.GetHexU8(), NULL);
1551 }
1552 }
1553 else
1554 {
1555 SetExitStatus(SIGABRT, NULL);
1556 //error.SetErrorString("kill packet failed");
1557 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001558 }
1559 }
Chris Lattner24943d22010-06-08 16:52:24 +00001560 StopAsyncThread ();
1561 m_gdb_comm.StopReadThread();
1562 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001563 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001564 return error;
1565}
1566
Chris Lattner24943d22010-06-08 16:52:24 +00001567//------------------------------------------------------------------
1568// Process Queries
1569//------------------------------------------------------------------
1570
1571bool
1572ProcessGDBRemote::IsAlive ()
1573{
Greg Clayton58e844b2010-12-08 05:08:21 +00001574 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001575}
1576
1577addr_t
1578ProcessGDBRemote::GetImageInfoAddress()
1579{
1580 if (!m_gdb_comm.IsRunning())
1581 {
1582 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001583 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001584 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001585 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001586 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1587 }
1588 }
1589 return LLDB_INVALID_ADDRESS;
1590}
1591
Chris Lattner24943d22010-06-08 16:52:24 +00001592//------------------------------------------------------------------
1593// Process Memory
1594//------------------------------------------------------------------
1595size_t
1596ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1597{
1598 if (size > m_max_memory_size)
1599 {
1600 // Keep memory read sizes down to a sane limit. This function will be
1601 // called multiple times in order to complete the task by
1602 // lldb_private::Process so it is ok to do this.
1603 size = m_max_memory_size;
1604 }
1605
1606 char packet[64];
1607 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1608 assert (packet_len + 1 < sizeof(packet));
1609 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001610 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001611 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001612 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001613 {
1614 error.Clear();
1615 return response.GetHexBytes(buf, size, '\xdd');
1616 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001617 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001618 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001619 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001620 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1621 else
1622 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1623 }
1624 else
1625 {
1626 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1627 }
1628 return 0;
1629}
1630
1631size_t
1632ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1633{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001634 if (size > m_max_memory_size)
1635 {
1636 // Keep memory read sizes down to a sane limit. This function will be
1637 // called multiple times in order to complete the task by
1638 // lldb_private::Process so it is ok to do this.
1639 size = m_max_memory_size;
1640 }
1641
Chris Lattner24943d22010-06-08 16:52:24 +00001642 StreamString packet;
1643 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001644 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001645 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001646 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001647 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001648 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001649 {
1650 error.Clear();
1651 return size;
1652 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001653 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001654 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001655 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001656 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1657 else
1658 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1659 }
1660 else
1661 {
1662 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1663 }
1664 return 0;
1665}
1666
1667lldb::addr_t
1668ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1669{
Greg Clayton989816b2011-05-14 01:50:35 +00001670 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1671
Greg Clayton2f085c62011-05-15 01:25:55 +00001672 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001673 switch (supported)
1674 {
1675 case eLazyBoolCalculate:
1676 case eLazyBoolYes:
1677 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1678 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1679 return allocated_addr;
1680
1681 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001682 // Call mmap() to create memory in the inferior..
1683 unsigned prot = 0;
1684 if (permissions & lldb::ePermissionsReadable)
1685 prot |= eMmapProtRead;
1686 if (permissions & lldb::ePermissionsWritable)
1687 prot |= eMmapProtWrite;
1688 if (permissions & lldb::ePermissionsExecutable)
1689 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001690
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001691 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1692 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1693 m_addr_to_mmap_size[allocated_addr] = size;
1694 else
1695 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001696 break;
1697 }
1698
Chris Lattner24943d22010-06-08 16:52:24 +00001699 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001700 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001701 else
1702 error.Clear();
1703 return allocated_addr;
1704}
1705
1706Error
1707ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1708{
1709 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001710 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1711
1712 switch (supported)
1713 {
1714 case eLazyBoolCalculate:
1715 // We should never be deallocating memory without allocating memory
1716 // first so we should never get eLazyBoolCalculate
1717 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1718 break;
1719
1720 case eLazyBoolYes:
1721 if (!m_gdb_comm.DeallocateMemory (addr))
1722 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1723 break;
1724
1725 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001726 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001727 {
1728 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001729 if (pos != m_addr_to_mmap_size.end() &&
1730 InferiorCallMunmap(this, addr, pos->second))
1731 m_addr_to_mmap_size.erase (pos);
1732 else
1733 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001734 }
1735 break;
1736 }
1737
Chris Lattner24943d22010-06-08 16:52:24 +00001738 return error;
1739}
1740
1741
1742//------------------------------------------------------------------
1743// Process STDIO
1744//------------------------------------------------------------------
1745
1746size_t
1747ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1748{
1749 Mutex::Locker locker(m_stdio_mutex);
1750 size_t bytes_available = m_stdout_data.size();
1751 if (bytes_available > 0)
1752 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001753 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1754 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001755 log->Printf ("ProcessGDBRemote::%s (&%p[%lu]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001756 if (bytes_available > buf_size)
1757 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001758 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001759 m_stdout_data.erase(0, buf_size);
1760 bytes_available = buf_size;
1761 }
1762 else
1763 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001764 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001765 m_stdout_data.clear();
1766
1767 //ResetEventBits(eBroadcastBitSTDOUT);
1768 }
1769 }
1770 return bytes_available;
1771}
1772
1773size_t
1774ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1775{
1776 // Can we get STDERR through the remote protocol?
1777 return 0;
1778}
1779
1780size_t
1781ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1782{
1783 if (m_stdio_communication.IsConnected())
1784 {
1785 ConnectionStatus status;
1786 m_stdio_communication.Write(src, src_len, status, NULL);
1787 }
1788 return 0;
1789}
1790
1791Error
1792ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1793{
1794 Error error;
1795 assert (bp_site != NULL);
1796
Greg Claytone005f2c2010-11-06 01:53:30 +00001797 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001798 user_id_t site_id = bp_site->GetID();
1799 const addr_t addr = bp_site->GetLoadAddress();
1800 if (log)
1801 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1802
1803 if (bp_site->IsEnabled())
1804 {
1805 if (log)
1806 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1807 return error;
1808 }
1809 else
1810 {
1811 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1812
1813 if (bp_site->HardwarePreferred())
1814 {
1815 // Try and set hardware breakpoint, and if that fails, fall through
1816 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001817 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001818 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001819 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001820 {
1821 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001822 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001823 return error;
1824 }
Chris Lattner24943d22010-06-08 16:52:24 +00001825 }
1826 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001827
1828 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001829 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001830 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1831 {
1832 bp_site->SetEnabled(true);
1833 bp_site->SetType (BreakpointSite::eExternal);
1834 return error;
1835 }
Chris Lattner24943d22010-06-08 16:52:24 +00001836 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001837
1838 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001839 }
1840
1841 if (log)
1842 {
1843 const char *err_string = error.AsCString();
1844 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1845 bp_site->GetLoadAddress(),
1846 err_string ? err_string : "NULL");
1847 }
1848 // We shouldn't reach here on a successful breakpoint enable...
1849 if (error.Success())
1850 error.SetErrorToGenericError();
1851 return error;
1852}
1853
1854Error
1855ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1856{
1857 Error error;
1858 assert (bp_site != NULL);
1859 addr_t addr = bp_site->GetLoadAddress();
1860 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001861 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001862 if (log)
1863 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1864
1865 if (bp_site->IsEnabled())
1866 {
1867 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1868
Greg Claytonb72d0f02011-04-12 05:54:46 +00001869 BreakpointSite::Type bp_type = bp_site->GetType();
1870 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001871 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001872 case BreakpointSite::eSoftware:
1873 error = DisableSoftwareBreakpoint (bp_site);
1874 break;
1875
1876 case BreakpointSite::eHardware:
1877 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1878 error.SetErrorToGenericError();
1879 break;
1880
1881 case BreakpointSite::eExternal:
1882 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1883 error.SetErrorToGenericError();
1884 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001885 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001886 if (error.Success())
1887 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001888 }
1889 else
1890 {
1891 if (log)
1892 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1893 return error;
1894 }
1895
1896 if (error.Success())
1897 error.SetErrorToGenericError();
1898 return error;
1899}
1900
Johnny Chen21900fb2011-09-06 22:38:36 +00001901// Pre-requisite: wp != NULL.
1902static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00001903GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00001904{
1905 assert(wp);
1906 bool watch_read = wp->WatchpointRead();
1907 bool watch_write = wp->WatchpointWrite();
1908
1909 // watch_read and watch_write cannot both be false.
1910 assert(watch_read || watch_write);
1911 if (watch_read && watch_write)
1912 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001913 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00001914 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00001915 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00001916 return eWatchpointWrite;
1917}
1918
Chris Lattner24943d22010-06-08 16:52:24 +00001919Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001920ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001921{
1922 Error error;
1923 if (wp)
1924 {
1925 user_id_t watchID = wp->GetID();
1926 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001927 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001928 if (log)
1929 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1930 if (wp->IsEnabled())
1931 {
1932 if (log)
1933 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1934 return error;
1935 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001936
1937 GDBStoppointType type = GetGDBStoppointType(wp);
1938 // Pass down an appropriate z/Z packet...
1939 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00001940 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001941 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
1942 {
1943 wp->SetEnabled(true);
1944 return error;
1945 }
1946 else
1947 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001948 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001949 else
1950 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00001951 }
1952 else
1953 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001954 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001955 }
1956 if (error.Success())
1957 error.SetErrorToGenericError();
1958 return error;
1959}
1960
1961Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001962ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001963{
1964 Error error;
1965 if (wp)
1966 {
1967 user_id_t watchID = wp->GetID();
1968
Greg Claytone005f2c2010-11-06 01:53:30 +00001969 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001970
1971 addr_t addr = wp->GetLoadAddress();
1972 if (log)
1973 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1974
Johnny Chen21900fb2011-09-06 22:38:36 +00001975 if (!wp->IsEnabled())
1976 {
1977 if (log)
1978 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
1979 return error;
1980 }
1981
Chris Lattner24943d22010-06-08 16:52:24 +00001982 if (wp->IsHardware())
1983 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001984 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00001985 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00001986 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
1987 {
1988 wp->SetEnabled(false);
1989 return error;
1990 }
1991 else
1992 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001993 }
1994 // TODO: clear software watchpoints if we implement them
1995 }
1996 else
1997 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001998 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001999 }
2000 if (error.Success())
2001 error.SetErrorToGenericError();
2002 return error;
2003}
2004
2005void
2006ProcessGDBRemote::Clear()
2007{
2008 m_flags = 0;
2009 m_thread_list.Clear();
2010 {
2011 Mutex::Locker locker(m_stdio_mutex);
2012 m_stdout_data.clear();
2013 }
Chris Lattner24943d22010-06-08 16:52:24 +00002014}
2015
2016Error
2017ProcessGDBRemote::DoSignal (int signo)
2018{
2019 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002020 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002021 if (log)
2022 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2023
2024 if (!m_gdb_comm.SendAsyncSignal (signo))
2025 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2026 return error;
2027}
2028
Chris Lattner24943d22010-06-08 16:52:24 +00002029Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002030ProcessGDBRemote::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 +00002031{
2032 Error error;
2033 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2034 {
2035 // If we locate debugserver, keep that located version around
2036 static FileSpec g_debugserver_file_spec;
2037
Greg Claytonb72d0f02011-04-12 05:54:46 +00002038 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002039 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002040 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002041
2042 // Always check to see if we have an environment override for the path
2043 // to the debugserver to use and use it if we do.
2044 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2045 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002046 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002047 else
2048 debugserver_file_spec = g_debugserver_file_spec;
2049 bool debugserver_exists = debugserver_file_spec.Exists();
2050 if (!debugserver_exists)
2051 {
2052 // The debugserver binary is in the LLDB.framework/Resources
2053 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002054 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002055 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002056 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002057 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002058 if (debugserver_exists)
2059 {
2060 g_debugserver_file_spec = debugserver_file_spec;
2061 }
2062 else
2063 {
2064 g_debugserver_file_spec.Clear();
2065 debugserver_file_spec.Clear();
2066 }
Chris Lattner24943d22010-06-08 16:52:24 +00002067 }
2068 }
2069
2070 if (debugserver_exists)
2071 {
2072 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2073
2074 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002075
Greg Claytone005f2c2010-11-06 01:53:30 +00002076 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002077
Greg Claytonb72d0f02011-04-12 05:54:46 +00002078 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002079 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002080
Chris Lattner24943d22010-06-08 16:52:24 +00002081 // Start args with "debugserver /file/path -r --"
2082 debugserver_args.AppendArgument(debugserver_path);
2083 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002084 // use native registers, not the GDB registers
2085 debugserver_args.AppendArgument("--native-regs");
2086 // make debugserver run in its own session so signals generated by
2087 // special terminal key sequences (^C) don't affect debugserver
2088 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002089
Chris Lattner24943d22010-06-08 16:52:24 +00002090 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2091 if (env_debugserver_log_file)
2092 {
2093 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2094 debugserver_args.AppendArgument(arg_cstr);
2095 }
2096
2097 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2098 if (env_debugserver_log_flags)
2099 {
2100 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2101 debugserver_args.AppendArgument(arg_cstr);
2102 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002103// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002104// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002105
Greg Claytonb72d0f02011-04-12 05:54:46 +00002106 // We currently send down all arguments, attach pids, or attach
2107 // process names in dedicated GDB server packets, so we don't need
2108 // to pass them as arguments. This is currently because of all the
2109 // things we need to setup prior to launching: the environment,
2110 // current working dir, file actions, etc.
2111#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002112 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002113 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002114 {
Greg Claytona2f74232011-02-24 22:24:29 +00002115 // Terminate the debugserver args so we can now append the inferior args
2116 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002117
Greg Claytona2f74232011-02-24 22:24:29 +00002118 for (int i = 0; inferior_argv[i] != NULL; ++i)
2119 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002120 }
2121 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2122 {
2123 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2124 debugserver_args.AppendArgument (arg_cstr);
2125 }
2126 else if (attach_name && attach_name[0])
2127 {
2128 if (wait_for_launch)
2129 debugserver_args.AppendArgument ("--waitfor");
2130 else
2131 debugserver_args.AppendArgument ("--attach");
2132 debugserver_args.AppendArgument (attach_name);
2133 }
Chris Lattner24943d22010-06-08 16:52:24 +00002134#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002135
2136 ProcessLaunchInfo::FileAction file_action;
2137
2138 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2139 // to "/dev/null" if we run into any problems.
2140 file_action.Close (STDIN_FILENO);
2141 launch_info.AppendFileAction (file_action);
2142 file_action.Close (STDOUT_FILENO);
2143 launch_info.AppendFileAction (file_action);
2144 file_action.Close (STDERR_FILENO);
2145 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002146
2147 if (log)
2148 {
2149 StreamString strm;
2150 debugserver_args.Dump (&strm);
2151 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2152 }
2153
Greg Claytonb72d0f02011-04-12 05:54:46 +00002154 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002155
Greg Claytonb72d0f02011-04-12 05:54:46 +00002156 if (error.Success ())
2157 m_debugserver_pid = launch_info.GetProcessID();
2158 else
Chris Lattner24943d22010-06-08 16:52:24 +00002159 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2160
2161 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002162 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002163 }
2164 else
2165 {
2166 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2167 }
2168
2169 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2170 StartAsyncThread ();
2171 }
2172 return error;
2173}
2174
2175bool
2176ProcessGDBRemote::MonitorDebugserverProcess
2177(
2178 void *callback_baton,
2179 lldb::pid_t debugserver_pid,
2180 int signo, // Zero for no signal
2181 int exit_status // Exit value of process if signal is zero
2182)
2183{
2184 // We pass in the ProcessGDBRemote inferior process it and name it
2185 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2186 // pointer value itself, thus we need the double cast...
2187
2188 // "debugserver_pid" argument passed in is the process ID for
2189 // debugserver that we are tracking...
2190
Greg Clayton75ccf502010-08-21 02:22:51 +00002191 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002192
2193 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2194 if (log)
2195 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2196
Greg Clayton75ccf502010-08-21 02:22:51 +00002197 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002198 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002199 // Sleep for a half a second to make sure our inferior process has
2200 // time to set its exit status before we set it incorrectly when
2201 // both the debugserver and the inferior process shut down.
2202 usleep (500000);
2203 // If our process hasn't yet exited, debugserver might have died.
2204 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002205 const StateType state = process->GetState();
2206
2207 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2208 state != eStateInvalid &&
2209 state != eStateUnloaded &&
2210 state != eStateExited &&
2211 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002212 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002213 char error_str[1024];
2214 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002215 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002216 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2217 if (signal_cstr)
2218 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002219 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002220 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002221 }
2222 else
2223 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002224 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
Chris Lattner24943d22010-06-08 16:52:24 +00002225 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002226
2227 process->SetExitStatus (-1, error_str);
2228 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002229 // Debugserver has exited we need to let our ProcessGDBRemote
2230 // know that it no longer has a debugserver instance
2231 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2232 // We are returning true to this function below, so we can
2233 // forget about the monitor handle.
2234 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002235 }
2236 return true;
2237}
2238
2239void
2240ProcessGDBRemote::KillDebugserverProcess ()
2241{
2242 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2243 {
2244 ::kill (m_debugserver_pid, SIGINT);
2245 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2246 }
2247}
2248
2249void
2250ProcessGDBRemote::Initialize()
2251{
2252 static bool g_initialized = false;
2253
2254 if (g_initialized == false)
2255 {
2256 g_initialized = true;
2257 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2258 GetPluginDescriptionStatic(),
2259 CreateInstance);
2260
2261 Log::Callbacks log_callbacks = {
2262 ProcessGDBRemoteLog::DisableLog,
2263 ProcessGDBRemoteLog::EnableLog,
2264 ProcessGDBRemoteLog::ListLogCategories
2265 };
2266
2267 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2268 }
2269}
2270
2271bool
Chris Lattner24943d22010-06-08 16:52:24 +00002272ProcessGDBRemote::StartAsyncThread ()
2273{
Greg Claytone005f2c2010-11-06 01:53:30 +00002274 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002275
2276 if (log)
2277 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2278
2279 // Create a thread that watches our internal state and controls which
2280 // events make it to clients (into the DCProcess event queue).
2281 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002282 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002283}
2284
2285void
2286ProcessGDBRemote::StopAsyncThread ()
2287{
Greg Claytone005f2c2010-11-06 01:53:30 +00002288 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002289
2290 if (log)
2291 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2292
2293 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2294
2295 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002296 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002297 {
2298 Host::ThreadJoin (m_async_thread, NULL, NULL);
2299 }
2300}
2301
2302
2303void *
2304ProcessGDBRemote::AsyncThread (void *arg)
2305{
2306 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2307
Greg Claytone005f2c2010-11-06 01:53:30 +00002308 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002309 if (log)
2310 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2311
2312 Listener listener ("ProcessGDBRemote::AsyncThread");
2313 EventSP event_sp;
2314 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2315 eBroadcastBitAsyncThreadShouldExit;
2316
2317 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2318 {
Greg Claytona2f74232011-02-24 22:24:29 +00002319 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2320
Chris Lattner24943d22010-06-08 16:52:24 +00002321 bool done = false;
2322 while (!done)
2323 {
2324 if (log)
2325 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2326 if (listener.WaitForEvent (NULL, event_sp))
2327 {
2328 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002329 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002330 {
Greg Claytona2f74232011-02-24 22:24:29 +00002331 if (log)
2332 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002333
Greg Claytona2f74232011-02-24 22:24:29 +00002334 switch (event_type)
2335 {
2336 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002337 {
Greg Claytona2f74232011-02-24 22:24:29 +00002338 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002339
Greg Claytona2f74232011-02-24 22:24:29 +00002340 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002341 {
Greg Claytona2f74232011-02-24 22:24:29 +00002342 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2343 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2344 if (log)
2345 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002346
Greg Claytona2f74232011-02-24 22:24:29 +00002347 if (::strstr (continue_cstr, "vAttach") == NULL)
2348 process->SetPrivateState(eStateRunning);
2349 StringExtractorGDBRemote response;
2350 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002351
Greg Claytona2f74232011-02-24 22:24:29 +00002352 switch (stop_state)
2353 {
2354 case eStateStopped:
2355 case eStateCrashed:
2356 case eStateSuspended:
2357 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002358 process->SetPrivateState (stop_state);
2359 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002360
Greg Claytona2f74232011-02-24 22:24:29 +00002361 case eStateExited:
2362 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002363 response.SetFilePos(1);
2364 process->SetExitStatus(response.GetHexU8(), NULL);
2365 done = true;
2366 break;
2367
2368 case eStateInvalid:
2369 process->SetExitStatus(-1, "lost connection");
2370 break;
2371
2372 default:
2373 process->SetPrivateState (stop_state);
2374 break;
2375 }
Chris Lattner24943d22010-06-08 16:52:24 +00002376 }
2377 }
Greg Claytona2f74232011-02-24 22:24:29 +00002378 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002379
Greg Claytona2f74232011-02-24 22:24:29 +00002380 case eBroadcastBitAsyncThreadShouldExit:
2381 if (log)
2382 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2383 done = true;
2384 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002385
Greg Claytona2f74232011-02-24 22:24:29 +00002386 default:
2387 if (log)
2388 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2389 done = true;
2390 break;
2391 }
2392 }
2393 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2394 {
2395 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2396 {
2397 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002398 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002399 }
Chris Lattner24943d22010-06-08 16:52:24 +00002400 }
2401 }
2402 else
2403 {
2404 if (log)
2405 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2406 done = true;
2407 }
2408 }
2409 }
2410
2411 if (log)
2412 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2413
2414 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2415 return NULL;
2416}
2417
Chris Lattner24943d22010-06-08 16:52:24 +00002418const char *
2419ProcessGDBRemote::GetDispatchQueueNameForThread
2420(
2421 addr_t thread_dispatch_qaddr,
2422 std::string &dispatch_queue_name
2423)
2424{
2425 dispatch_queue_name.clear();
2426 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2427 {
2428 // Cache the dispatch_queue_offsets_addr value so we don't always have
2429 // to look it up
2430 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2431 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002432 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2433 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002434 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002435 if (module_sp)
2436 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2437
2438 if (dispatch_queue_offsets_symbol == NULL)
2439 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002440 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002441 if (module_sp)
2442 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2443 }
Chris Lattner24943d22010-06-08 16:52:24 +00002444 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002445 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002446
2447 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2448 return NULL;
2449 }
2450
2451 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002452 DataExtractor data (memory_buffer,
2453 sizeof(memory_buffer),
2454 m_target.GetArchitecture().GetByteOrder(),
2455 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002456
2457 // Excerpt from src/queue_private.h
2458 struct dispatch_queue_offsets_s
2459 {
2460 uint16_t dqo_version;
2461 uint16_t dqo_label;
2462 uint16_t dqo_label_size;
2463 } dispatch_queue_offsets;
2464
2465
2466 Error error;
2467 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2468 {
2469 uint32_t data_offset = 0;
2470 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2471 {
2472 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2473 {
2474 data_offset = 0;
2475 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2476 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2477 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2478 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2479 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2480 dispatch_queue_name.erase (bytes_read);
2481 }
2482 }
2483 }
2484 }
2485 if (dispatch_queue_name.empty())
2486 return NULL;
2487 return dispatch_queue_name.c_str();
2488}
2489
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002490//uint32_t
2491//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2492//{
2493// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2494// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2495// if (m_local_debugserver)
2496// {
2497// return Host::ListProcessesMatchingName (name, matches, pids);
2498// }
2499// else
2500// {
2501// // FIXME: Implement talking to the remote debugserver.
2502// return 0;
2503// }
2504//
2505//}
2506//
Jim Ingham55e01d82011-01-22 01:33:44 +00002507bool
2508ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2509 lldb_private::StoppointCallbackContext *context,
2510 lldb::user_id_t break_id,
2511 lldb::user_id_t break_loc_id)
2512{
2513 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2514 // run so I can stop it if that's what I want to do.
2515 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2516 if (log)
2517 log->Printf("Hit New Thread Notification breakpoint.");
2518 return false;
2519}
2520
2521
2522bool
2523ProcessGDBRemote::StartNoticingNewThreads()
2524{
2525 static const char *bp_names[] =
2526 {
2527 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002528 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002529 "_pthread_start",
2530 NULL
2531 };
2532
2533 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2534 size_t num_bps = m_thread_observation_bps.size();
2535 if (num_bps != 0)
2536 {
2537 for (int i = 0; i < num_bps; i++)
2538 {
2539 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2540 if (break_sp)
2541 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002542 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002543 log->Printf("Enabled noticing new thread breakpoint.");
2544 break_sp->SetEnabled(true);
2545 }
2546 }
2547 }
2548 else
2549 {
2550 for (int i = 0; bp_names[i] != NULL; i++)
2551 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002552 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002553 if (breakpoint)
2554 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002555 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002556 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2557 m_thread_observation_bps.push_back(breakpoint->GetID());
2558 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2559 }
2560 else
2561 {
2562 if (log)
2563 log->Printf("Failed to create new thread notification breakpoint.");
2564 return false;
2565 }
2566 }
2567 }
2568
2569 return true;
2570}
2571
2572bool
2573ProcessGDBRemote::StopNoticingNewThreads()
2574{
Jim Inghamff276fe2011-02-08 05:19:01 +00002575 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002576 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002577 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002578 size_t num_bps = m_thread_observation_bps.size();
2579 if (num_bps != 0)
2580 {
2581 for (int i = 0; i < num_bps; i++)
2582 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002583
2584 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2585 if (break_sp)
2586 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002587 break_sp->SetEnabled(false);
2588 }
2589 }
2590 }
2591 return true;
2592}
2593
2594