blob: d39fbe4d6225462e68cf6dc3355e29b0da8fe60d [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
25#include "lldb/Breakpoint/WatchpointLocation.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.
Greg Clayton940b1032011-02-23 00:35:02 +0000348 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000349 m_register_info.HardcodeARMRegisters();
350 }
351 m_register_info.Finalize ();
352}
353
354Error
355ProcessGDBRemote::WillLaunch (Module* module)
356{
357 return WillLaunchOrAttach ();
358}
359
360Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000361ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000362{
363 return WillLaunchOrAttach ();
364}
365
366Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000367ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000368{
369 return WillLaunchOrAttach ();
370}
371
372Error
Greg Claytone71e2582011-02-04 01:58:07 +0000373ProcessGDBRemote::DoConnectRemote (const char *remote_url)
374{
375 Error error (WillLaunchOrAttach ());
376
377 if (error.Fail())
378 return error;
379
Greg Clayton180546b2011-04-30 01:09:13 +0000380 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000381
382 if (error.Fail())
383 return error;
384 StartAsyncThread ();
385
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000386 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000387 if (pid == LLDB_INVALID_PROCESS_ID)
388 {
389 // We don't have a valid process ID, so note that we are connected
390 // and could now request to launch or attach, or get remote process
391 // listings...
392 SetPrivateState (eStateConnected);
393 }
394 else
395 {
396 // We have a valid process
397 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000398 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000399 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000400 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000401 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000402 if (state == eStateStopped)
403 {
404 SetPrivateState (state);
405 }
406 else
407 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
408 }
409 else
410 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
411 }
412 return error;
413}
414
415Error
Chris Lattner24943d22010-06-08 16:52:24 +0000416ProcessGDBRemote::WillLaunchOrAttach ()
417{
418 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000419 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000420 return error;
421}
422
423//----------------------------------------------------------------------
424// Process Control
425//----------------------------------------------------------------------
426Error
427ProcessGDBRemote::DoLaunch
428(
429 Module* module,
430 char const *argv[],
431 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000432 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000433 const char *stdin_path,
434 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000435 const char *stderr_path,
436 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000437)
438{
Greg Clayton4b407112010-09-30 21:49:03 +0000439 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000440 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
441 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
442 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000443 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000444
445 ObjectFile * object_file = module->GetObjectFile();
446 if (object_file)
447 {
Chris Lattner24943d22010-06-08 16:52:24 +0000448 char host_port[128];
449 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000450 char connect_url[128];
451 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000452
Greg Claytona2f74232011-02-24 22:24:29 +0000453 // Make sure we aren't already connected?
454 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000455 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000456 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000457 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000458 {
Johnny Chenc143d622011-08-09 18:56:45 +0000459 if (log)
460 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000461 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000462 }
Chris Lattner24943d22010-06-08 16:52:24 +0000463
Greg Claytone71e2582011-02-04 01:58:07 +0000464 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000465 }
466
467 if (error.Success())
468 {
469 lldb_utility::PseudoTerminal pty;
470 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000471
472 // If the debugserver is local and we aren't disabling STDIO, lets use
473 // a pseudo terminal to instead of relying on the 'O' packets for stdio
474 // since 'O' packets can really slow down debugging if the inferior
475 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000476 PlatformSP platform_sp (m_target.GetPlatform());
477 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000478 {
479 const char *slave_name = NULL;
480 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000481 {
Greg Claytona2f74232011-02-24 22:24:29 +0000482 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
483 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000484 }
Greg Claytona2f74232011-02-24 22:24:29 +0000485 if (stdin_path == NULL)
486 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000487
Greg Claytona2f74232011-02-24 22:24:29 +0000488 if (stdout_path == NULL)
489 stdout_path = slave_name;
490
491 if (stderr_path == NULL)
492 stderr_path = slave_name;
493 }
494
Greg Claytonafb81862011-03-02 21:34:46 +0000495 // Set STDIN to /dev/null if we want STDIO disabled or if either
496 // STDOUT or STDERR have been set to something and STDIN hasn't
497 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000498 stdin_path = "/dev/null";
499
Greg Claytonafb81862011-03-02 21:34:46 +0000500 // Set STDOUT to /dev/null if we want STDIO disabled or if either
501 // STDIN or STDERR have been set to something and STDOUT hasn't
502 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000503 stdout_path = "/dev/null";
504
Greg Claytonafb81862011-03-02 21:34:46 +0000505 // Set STDERR to /dev/null if we want STDIO disabled or if either
506 // STDIN or STDOUT have been set to something and STDERR hasn't
507 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000508 stderr_path = "/dev/null";
509
510 if (stdin_path)
511 m_gdb_comm.SetSTDIN (stdin_path);
512 if (stdout_path)
513 m_gdb_comm.SetSTDOUT (stdout_path);
514 if (stderr_path)
515 m_gdb_comm.SetSTDERR (stderr_path);
516
517 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
518
Greg Claytona4582402011-05-08 04:53:50 +0000519 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000520
521 if (working_dir && working_dir[0])
522 {
523 m_gdb_comm.SetWorkingDir (working_dir);
524 }
525
526 // Send the environment and the program + arguments after we connect
527 if (envp)
528 {
529 const char *env_entry;
530 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000531 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000532 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000533 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000534 }
Greg Claytona2f74232011-02-24 22:24:29 +0000535 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000536
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000537 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
538 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
Greg Claytona2f74232011-02-24 22:24:29 +0000539 if (arg_packet_err == 0)
540 {
541 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000542 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000543 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000544 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000545 }
546 else
547 {
Greg Claytona2f74232011-02-24 22:24:29 +0000548 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000549 }
Greg Claytona2f74232011-02-24 22:24:29 +0000550 }
551 else
552 {
553 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
554 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000555
556 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000557
Greg Claytona2f74232011-02-24 22:24:29 +0000558 if (GetID() == LLDB_INVALID_PROCESS_ID)
559 {
Johnny Chenc143d622011-08-09 18:56:45 +0000560 if (log)
561 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000562 KillDebugserverProcess ();
563 return error;
564 }
565
Greg Clayton261a18b2011-06-02 22:22:38 +0000566 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000567 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000568 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000569
570 if (!disable_stdio)
571 {
572 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
573 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
574 }
Chris Lattner24943d22010-06-08 16:52:24 +0000575 }
576 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000577 else
578 {
Johnny Chenc143d622011-08-09 18:56:45 +0000579 if (log)
580 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000581 }
Chris Lattner24943d22010-06-08 16:52:24 +0000582 }
583 else
584 {
585 // Set our user ID to an invalid process ID.
586 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000587 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
588 module->GetFileSpec().GetFilename().AsCString(),
589 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000590 }
Chris Lattner24943d22010-06-08 16:52:24 +0000591 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000592
Chris Lattner24943d22010-06-08 16:52:24 +0000593}
594
595
596Error
Greg Claytone71e2582011-02-04 01:58:07 +0000597ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000598{
599 Error error;
600 // Sleep and wait a bit for debugserver to start to listen...
601 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
602 if (conn_ap.get())
603 {
Chris Lattner24943d22010-06-08 16:52:24 +0000604 const uint32_t max_retry_count = 50;
605 uint32_t retry_count = 0;
606 while (!m_gdb_comm.IsConnected())
607 {
Greg Claytone71e2582011-02-04 01:58:07 +0000608 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000609 {
610 m_gdb_comm.SetConnection (conn_ap.release());
611 break;
612 }
613 retry_count++;
614
615 if (retry_count >= max_retry_count)
616 break;
617
618 usleep (100000);
619 }
620 }
621
622 if (!m_gdb_comm.IsConnected())
623 {
624 if (error.Success())
625 error.SetErrorString("not connected to remote gdb server");
626 return error;
627 }
628
Greg Clayton24bc5d92011-03-30 18:16:51 +0000629 // We always seem to be able to open a connection to a local port
630 // so we need to make sure we can then send data to it. If we can't
631 // then we aren't actually connected to anything, so try and do the
632 // handshake with the remote GDB server and make sure that goes
633 // alright.
634 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000635 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000636 m_gdb_comm.Disconnect();
637 if (error.Success())
638 error.SetErrorString("not connected to remote gdb server");
639 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000640 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000641 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
642 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
643 this,
644 m_debugserver_pid,
645 false);
646 m_gdb_comm.ResetDiscoverableSettings();
647 m_gdb_comm.QueryNoAckModeSupported ();
648 m_gdb_comm.GetThreadSuffixSupported ();
649 m_gdb_comm.GetHostInfo ();
650 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000651 return error;
652}
653
654void
655ProcessGDBRemote::DidLaunchOrAttach ()
656{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000657 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
658 if (log)
659 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000660 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000661 {
662 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
663
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000664 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000665
Chris Lattner24943d22010-06-08 16:52:24 +0000666 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000667
Greg Claytoncb8977d2011-03-23 00:09:55 +0000668 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
669 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000670 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000671 ArchSpec &target_arch = GetTarget().GetArchitecture();
672
673 if (target_arch.IsValid())
674 {
675 // If the remote host is ARM and we have apple as the vendor, then
676 // ARM executables and shared libraries can have mixed ARM architectures.
677 // You can have an armv6 executable, and if the host is armv7, then the
678 // system will load the best possible architecture for all shared libraries
679 // it has, so we really need to take the remote host architecture as our
680 // defacto architecture in this case.
681
682 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
683 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
684 {
685 target_arch = gdb_remote_arch;
686 }
687 else
688 {
689 // Fill in what is missing in the triple
690 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
691 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000692 if (target_triple.getVendorName().size() == 0)
693 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000694 target_triple.setVendor (remote_triple.getVendor());
695
Greg Clayton2f085c62011-05-15 01:25:55 +0000696 if (target_triple.getOSName().size() == 0)
697 {
698 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000699
Greg Clayton2f085c62011-05-15 01:25:55 +0000700 if (target_triple.getEnvironmentName().size() == 0)
701 target_triple.setEnvironment (remote_triple.getEnvironment());
702 }
703 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000704 }
705 }
706 else
707 {
708 // The target doesn't have a valid architecture yet, set it from
709 // the architecture we got from the remote GDB server
710 target_arch = gdb_remote_arch;
711 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000712 }
Chris Lattner24943d22010-06-08 16:52:24 +0000713 }
714}
715
716void
717ProcessGDBRemote::DidLaunch ()
718{
719 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000720}
721
722Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000723ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000724{
725 Error error;
726 // Clear out and clean up from any current state
727 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000728 if (attach_pid != LLDB_INVALID_PROCESS_ID)
729 {
Greg Claytona2f74232011-02-24 22:24:29 +0000730 // Make sure we aren't already connected?
731 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000732 {
Greg Claytona2f74232011-02-24 22:24:29 +0000733 char host_port[128];
734 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
735 char connect_url[128];
736 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000737
Greg Claytonb72d0f02011-04-12 05:54:46 +0000738 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000739
740 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000741 {
Greg Claytona2f74232011-02-24 22:24:29 +0000742 const char *error_string = error.AsCString();
743 if (error_string == NULL)
744 error_string = "unable to launch " DEBUGSERVER_BASENAME;
745
746 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000747 }
Greg Claytona2f74232011-02-24 22:24:29 +0000748 else
749 {
750 error = ConnectToDebugserver (connect_url);
751 }
752 }
753
754 if (error.Success())
755 {
756 char packet[64];
757 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
758
759 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000760 }
761 }
Chris Lattner24943d22010-06-08 16:52:24 +0000762 return error;
763}
764
765size_t
766ProcessGDBRemote::AttachInputReaderCallback
767(
768 void *baton,
769 InputReader *reader,
770 lldb::InputReaderAction notification,
771 const char *bytes,
772 size_t bytes_len
773)
774{
775 if (notification == eInputReaderGotToken)
776 {
777 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
778 if (gdb_process->m_waiting_for_attach)
779 gdb_process->m_waiting_for_attach = false;
780 reader->SetIsDone(true);
781 return 1;
782 }
783 return 0;
784}
785
786Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000787ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000788{
789 Error error;
790 // Clear out and clean up from any current state
791 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000792
Chris Lattner24943d22010-06-08 16:52:24 +0000793 if (process_name && process_name[0])
794 {
Greg Claytona2f74232011-02-24 22:24:29 +0000795 // Make sure we aren't already connected?
796 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000797 {
Greg Claytona2f74232011-02-24 22:24:29 +0000798 char host_port[128];
799 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
800 char connect_url[128];
801 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
802
Greg Claytonb72d0f02011-04-12 05:54:46 +0000803 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000804 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000805 {
Greg Claytona2f74232011-02-24 22:24:29 +0000806 const char *error_string = error.AsCString();
807 if (error_string == NULL)
808 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000809
Greg Claytona2f74232011-02-24 22:24:29 +0000810 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000811 }
Greg Claytona2f74232011-02-24 22:24:29 +0000812 else
813 {
814 error = ConnectToDebugserver (connect_url);
815 }
816 }
817
818 if (error.Success())
819 {
820 StreamString packet;
821
822 if (wait_for_launch)
823 packet.PutCString("vAttachWait");
824 else
825 packet.PutCString("vAttachName");
826 packet.PutChar(';');
827 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
828
829 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
830
Chris Lattner24943d22010-06-08 16:52:24 +0000831 }
832 }
Chris Lattner24943d22010-06-08 16:52:24 +0000833 return error;
834}
835
Chris Lattner24943d22010-06-08 16:52:24 +0000836
837void
838ProcessGDBRemote::DidAttach ()
839{
Greg Claytone71e2582011-02-04 01:58:07 +0000840 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000841}
842
843Error
844ProcessGDBRemote::WillResume ()
845{
Greg Claytonc1f45872011-02-12 06:28:37 +0000846 m_continue_c_tids.clear();
847 m_continue_C_tids.clear();
848 m_continue_s_tids.clear();
849 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000850 return Error();
851}
852
853Error
854ProcessGDBRemote::DoResume ()
855{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000856 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000857 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
858 if (log)
859 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000860
861 Listener listener ("gdb-remote.resume-packet-sent");
862 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
863 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000864 StreamString continue_packet;
865 bool continue_packet_error = false;
866 if (m_gdb_comm.HasAnyVContSupport ())
867 {
868 continue_packet.PutCString ("vCont");
869
870 if (!m_continue_c_tids.empty())
871 {
872 if (m_gdb_comm.GetVContSupported ('c'))
873 {
874 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)
875 continue_packet.Printf(";c:%4.4x", *t_pos);
876 }
877 else
878 continue_packet_error = true;
879 }
880
881 if (!continue_packet_error && !m_continue_C_tids.empty())
882 {
883 if (m_gdb_comm.GetVContSupported ('C'))
884 {
885 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)
886 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
887 }
888 else
889 continue_packet_error = true;
890 }
Greg Claytonb749a262010-12-03 06:02:24 +0000891
Greg Claytonc1f45872011-02-12 06:28:37 +0000892 if (!continue_packet_error && !m_continue_s_tids.empty())
893 {
894 if (m_gdb_comm.GetVContSupported ('s'))
895 {
896 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)
897 continue_packet.Printf(";s:%4.4x", *t_pos);
898 }
899 else
900 continue_packet_error = true;
901 }
902
903 if (!continue_packet_error && !m_continue_S_tids.empty())
904 {
905 if (m_gdb_comm.GetVContSupported ('S'))
906 {
907 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)
908 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
909 }
910 else
911 continue_packet_error = true;
912 }
913
914 if (continue_packet_error)
915 continue_packet.GetString().clear();
916 }
917 else
918 continue_packet_error = true;
919
920 if (continue_packet_error)
921 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000922 // Either no vCont support, or we tried to use part of the vCont
923 // packet that wasn't supported by the remote GDB server.
924 // We need to try and make a simple packet that can do our continue
925 const size_t num_threads = GetThreadList().GetSize();
926 const size_t num_continue_c_tids = m_continue_c_tids.size();
927 const size_t num_continue_C_tids = m_continue_C_tids.size();
928 const size_t num_continue_s_tids = m_continue_s_tids.size();
929 const size_t num_continue_S_tids = m_continue_S_tids.size();
930 if (num_continue_c_tids > 0)
931 {
932 if (num_continue_c_tids == num_threads)
933 {
934 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000935 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000936 continue_packet.PutChar ('c');
937 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000938 }
939 else if (num_continue_c_tids == 1 &&
940 num_continue_C_tids == 0 &&
941 num_continue_s_tids == 0 &&
942 num_continue_S_tids == 0 )
943 {
944 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000945 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000946 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000947 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000948 }
949 }
950
Greg Claytonde1dd812011-06-24 03:21:43 +0000951 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000952 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000953 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
954 num_continue_C_tids > 0 &&
955 num_continue_s_tids == 0 &&
956 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000957 {
958 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000959 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +0000960 if (num_continue_C_tids > 1)
961 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000962 // More that one thread with a signal, yet we don't have
963 // vCont support and we are being asked to resume each
964 // thread with a signal, we need to make sure they are
965 // all the same signal, or we can't issue the continue
966 // accurately with the current support...
967 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +0000968 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000969 continue_packet_error = false;
970 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
971 {
972 if (m_continue_C_tids[i].second != continue_signo)
973 continue_packet_error = true;
974 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000975 }
Greg Claytonde1dd812011-06-24 03:21:43 +0000976 if (!continue_packet_error)
977 m_gdb_comm.SetCurrentThreadForRun (-1);
978 }
979 else
980 {
981 // Set the continue thread ID
982 continue_packet_error = false;
983 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000984 }
985 if (!continue_packet_error)
986 {
987 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +0000988 continue_packet.Printf("C%2.2x", continue_signo);
989 }
990 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000991 }
992
Greg Claytonde1dd812011-06-24 03:21:43 +0000993 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000994 {
995 if (num_continue_s_tids == num_threads)
996 {
997 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000998 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000999 continue_packet.PutChar ('s');
1000 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001001 }
1002 else if (num_continue_c_tids == 0 &&
1003 num_continue_C_tids == 0 &&
1004 num_continue_s_tids == 1 &&
1005 num_continue_S_tids == 0 )
1006 {
1007 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001008 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001009 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001010 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001011 }
1012 }
1013
1014 if (!continue_packet_error && num_continue_S_tids > 0)
1015 {
1016 if (num_continue_S_tids == num_threads)
1017 {
1018 const int step_signo = m_continue_S_tids.front().second;
1019 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001020 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001021 if (num_continue_S_tids > 1)
1022 {
1023 for (size_t i=1; i<num_threads; ++i)
1024 {
1025 if (m_continue_S_tids[i].second != step_signo)
1026 continue_packet_error = true;
1027 }
1028 }
1029 if (!continue_packet_error)
1030 {
1031 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001032 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001033 continue_packet.Printf("S%2.2x", step_signo);
1034 }
1035 }
1036 else if (num_continue_c_tids == 0 &&
1037 num_continue_C_tids == 0 &&
1038 num_continue_s_tids == 0 &&
1039 num_continue_S_tids == 1 )
1040 {
1041 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001042 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001043 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001044 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001045 }
1046 }
1047 }
1048
1049 if (continue_packet_error)
1050 {
1051 error.SetErrorString ("can't make continue packet for this resume");
1052 }
1053 else
1054 {
1055 EventSP event_sp;
1056 TimeValue timeout;
1057 timeout = TimeValue::Now();
1058 timeout.OffsetWithSeconds (5);
1059 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1060
1061 if (listener.WaitForEvent (&timeout, event_sp) == false)
1062 error.SetErrorString("Resume timed out.");
1063 }
Greg Claytonb749a262010-12-03 06:02:24 +00001064 }
1065
Jim Ingham3ae449a2010-11-17 02:32:00 +00001066 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001067}
1068
Chris Lattner24943d22010-06-08 16:52:24 +00001069uint32_t
Greg Clayton37f962e2011-08-22 02:49:39 +00001070ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001071{
1072 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001073 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001074 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001075 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001076 // Update the thread list's stop id immediately so we don't recurse into this function.
Chris Lattner24943d22010-06-08 16:52:24 +00001077
Greg Clayton37f962e2011-08-22 02:49:39 +00001078 std::vector<lldb::tid_t> thread_ids;
1079 bool sequence_mutex_unavailable = false;
1080 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1081 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001082 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001083 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001084 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001085 tid_t tid = thread_ids[i];
1086 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1087 if (!thread_sp)
1088 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1089 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001090 }
Chris Lattner24943d22010-06-08 16:52:24 +00001091 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001092
1093 if (sequence_mutex_unavailable == false)
1094 SetThreadStopInfo (m_last_stop_packet);
1095 return new_thread_list.GetSize(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001096}
1097
1098
1099StateType
1100ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1101{
Greg Clayton261a18b2011-06-02 22:22:38 +00001102 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001103 const char stop_type = stop_packet.GetChar();
1104 switch (stop_type)
1105 {
1106 case 'T':
1107 case 'S':
1108 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001109 if (GetStopID() == 0)
1110 {
1111 // Our first stop, make sure we have a process ID, and also make
1112 // sure we know about our registers
1113 if (GetID() == LLDB_INVALID_PROCESS_ID)
1114 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001115 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001116 if (pid != LLDB_INVALID_PROCESS_ID)
1117 SetID (pid);
1118 }
1119 BuildDynamicRegisterInfo (true);
1120 }
Chris Lattner24943d22010-06-08 16:52:24 +00001121 // Stop with signal and thread info
1122 const uint8_t signo = stop_packet.GetHexU8();
1123 std::string name;
1124 std::string value;
1125 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001126 std::string reason;
1127 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001128 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001129 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001130 uint32_t tid = LLDB_INVALID_THREAD_ID;
1131 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1132 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001133 ThreadSP thread_sp;
1134
Chris Lattner24943d22010-06-08 16:52:24 +00001135 while (stop_packet.GetNameColonValue(name, value))
1136 {
1137 if (name.compare("metype") == 0)
1138 {
1139 // exception type in big endian hex
1140 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1141 }
1142 else if (name.compare("mecount") == 0)
1143 {
1144 // exception count in big endian hex
1145 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1146 }
1147 else if (name.compare("medata") == 0)
1148 {
1149 // exception data in big endian hex
1150 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1151 }
1152 else if (name.compare("thread") == 0)
1153 {
1154 // thread in big endian hex
1155 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001156 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001157 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001158 if (!thread_sp)
1159 {
1160 // Create the thread if we need to
1161 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1162 m_thread_list.AddThread(thread_sp);
1163 }
Chris Lattner24943d22010-06-08 16:52:24 +00001164 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001165 else if (name.compare("hexname") == 0)
1166 {
1167 StringExtractor name_extractor;
1168 // Swap "value" over into "name_extractor"
1169 name_extractor.GetStringRef().swap(value);
1170 // Now convert the HEX bytes into a string value
1171 name_extractor.GetHexByteString (value);
1172 thread_name.swap (value);
1173 }
Chris Lattner24943d22010-06-08 16:52:24 +00001174 else if (name.compare("name") == 0)
1175 {
1176 thread_name.swap (value);
1177 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001178 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001179 {
1180 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1181 }
Greg Clayton65611552011-06-04 01:26:29 +00001182 else if (name.compare("reason") == 0)
1183 {
1184 reason.swap(value);
1185 }
1186 else if (name.compare("description") == 0)
1187 {
1188 StringExtractor desc_extractor;
1189 // Swap "value" over into "name_extractor"
1190 desc_extractor.GetStringRef().swap(value);
1191 // Now convert the HEX bytes into a string value
1192 desc_extractor.GetHexByteString (thread_name);
1193 }
Greg Claytona875b642011-01-09 21:07:35 +00001194 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1195 {
1196 // We have a register number that contains an expedited
1197 // register value. Lets supply this register to our thread
1198 // so it won't have to go and read it.
1199 if (thread_sp)
1200 {
1201 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1202
1203 if (reg != UINT32_MAX)
1204 {
1205 StringExtractor reg_value_extractor;
1206 // Swap "value" over into "reg_value_extractor"
1207 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001208 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1209 {
1210 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1211 name.c_str(),
1212 reg,
1213 reg,
1214 reg_value_extractor.GetStringRef().c_str(),
1215 stop_packet.GetStringRef().c_str());
1216 }
Greg Claytona875b642011-01-09 21:07:35 +00001217 }
1218 }
1219 }
Chris Lattner24943d22010-06-08 16:52:24 +00001220 }
Chris Lattner24943d22010-06-08 16:52:24 +00001221
1222 if (thread_sp)
1223 {
1224 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1225
1226 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001227 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001228 if (exc_type != 0)
1229 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001230 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001231
1232 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1233 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001234 exc_data_size,
1235 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001236 exc_data_size >= 2 ? exc_data[1] : 0,
1237 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001238 }
Greg Clayton65611552011-06-04 01:26:29 +00001239 else
Chris Lattner24943d22010-06-08 16:52:24 +00001240 {
Greg Clayton65611552011-06-04 01:26:29 +00001241 bool handled = false;
1242 if (!reason.empty())
1243 {
1244 if (reason.compare("trace") == 0)
1245 {
1246 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1247 handled = true;
1248 }
1249 else if (reason.compare("breakpoint") == 0)
1250 {
1251 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1252 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1253 if (bp_site_sp)
1254 {
1255 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1256 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1257 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1258 if (bp_site_sp->ValidForThisThread (gdb_thread))
1259 {
1260 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1261 handled = true;
1262 }
1263 }
1264
1265 if (!handled)
1266 {
1267 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1268 }
1269 }
1270 else if (reason.compare("trap") == 0)
1271 {
1272 // Let the trap just use the standard signal stop reason below...
1273 }
1274 else if (reason.compare("watchpoint") == 0)
1275 {
1276 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1277 // TODO: locate the watchpoint somehow...
1278 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1279 handled = true;
1280 }
1281 else if (reason.compare("exception") == 0)
1282 {
1283 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1284 handled = true;
1285 }
1286 }
1287
1288 if (signo)
1289 {
1290 if (signo == SIGTRAP)
1291 {
1292 // Currently we are going to assume SIGTRAP means we are either
1293 // hitting a breakpoint or hardware single stepping.
1294 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1295 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1296 if (bp_site_sp)
1297 {
1298 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1299 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1300 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1301 if (bp_site_sp->ValidForThisThread (gdb_thread))
1302 {
1303 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1304 handled = true;
1305 }
1306 }
1307 if (!handled)
1308 {
1309 // TODO: check for breakpoint or trap opcode in case there is a hard
1310 // coded software trap
1311 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1312 handled = true;
1313 }
1314 }
1315 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001316 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001317 }
1318 else
1319 {
Greg Clayton643ee732010-08-04 01:40:35 +00001320 StopInfoSP invalid_stop_info_sp;
1321 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001322 }
Greg Clayton65611552011-06-04 01:26:29 +00001323
1324 if (!description.empty())
1325 {
1326 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1327 if (stop_info_sp)
1328 {
1329 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001330 }
Greg Clayton65611552011-06-04 01:26:29 +00001331 else
1332 {
1333 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1334 }
1335 }
1336 }
Chris Lattner24943d22010-06-08 16:52:24 +00001337 }
1338 return eStateStopped;
1339 }
1340 break;
1341
1342 case 'W':
1343 // process exited
1344 return eStateExited;
1345
1346 default:
1347 break;
1348 }
1349 return eStateInvalid;
1350}
1351
1352void
1353ProcessGDBRemote::RefreshStateAfterStop ()
1354{
Chris Lattner24943d22010-06-08 16:52:24 +00001355 // Let all threads recover from stopping and do any clean up based
1356 // on the previous thread state (if any).
1357 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001358 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001359}
1360
1361Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001362ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001363{
1364 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001365
Greg Claytona4881d02011-01-22 07:12:45 +00001366 bool timed_out = false;
1367 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001368
1369 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001370 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001371 // We are being asked to halt during an attach. We need to just close
1372 // our file handle and debugserver will go away, and we can be done...
1373 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001374 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001375 else
1376 {
1377 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1378 {
1379 if (timed_out)
1380 error.SetErrorString("timed out sending interrupt packet");
1381 else
1382 error.SetErrorString("unknown error sending interrupt packet");
1383 }
1384 }
Chris Lattner24943d22010-06-08 16:52:24 +00001385 return error;
1386}
1387
1388Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001389ProcessGDBRemote::InterruptIfRunning
1390(
1391 bool discard_thread_plans,
1392 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001393 EventSP &stop_event_sp
1394)
Chris Lattner24943d22010-06-08 16:52:24 +00001395{
1396 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001397
Greg Clayton2860ba92011-01-23 19:58:49 +00001398 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1399
Greg Clayton68ca8232011-01-25 02:58:48 +00001400 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001401 const bool is_running = m_gdb_comm.IsRunning();
1402 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001403 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001404 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001405 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001406 is_running);
1407
Greg Clayton2860ba92011-01-23 19:58:49 +00001408 if (discard_thread_plans)
1409 {
1410 if (log)
1411 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1412 m_thread_list.DiscardThreadPlans();
1413 }
1414 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001415 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001416 if (catch_stop_event)
1417 {
1418 if (log)
1419 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1420 PausePrivateStateThread();
1421 paused_private_state_thread = true;
1422 }
1423
Greg Clayton4fb400f2010-09-27 21:07:38 +00001424 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001425 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001426 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001427
Greg Clayton72e1c782011-01-22 23:43:18 +00001428 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001429 {
1430 if (timed_out)
1431 error.SetErrorString("timed out sending interrupt packet");
1432 else
1433 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001434 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001435 ResumePrivateStateThread();
1436 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001437 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001438
Greg Clayton72e1c782011-01-22 23:43:18 +00001439 if (catch_stop_event)
1440 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001441 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001442 TimeValue timeout_time;
1443 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001444 timeout_time.OffsetWithSeconds(5);
1445 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001446
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001447 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001448 if (log)
1449 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001450
Greg Clayton2860ba92011-01-23 19:58:49 +00001451 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001452 error.SetErrorString("unable to verify target stopped");
1453 }
1454
Greg Clayton68ca8232011-01-25 02:58:48 +00001455 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001456 {
1457 if (log)
1458 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001459 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001460 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001461 }
Chris Lattner24943d22010-06-08 16:52:24 +00001462 return error;
1463}
1464
Greg Clayton4fb400f2010-09-27 21:07:38 +00001465Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001466ProcessGDBRemote::WillDetach ()
1467{
Greg Clayton2860ba92011-01-23 19:58:49 +00001468 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1469 if (log)
1470 log->Printf ("ProcessGDBRemote::WillDetach()");
1471
Greg Clayton72e1c782011-01-22 23:43:18 +00001472 bool discard_thread_plans = true;
1473 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001474 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001475 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001476}
1477
1478Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001479ProcessGDBRemote::DoDetach()
1480{
1481 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001482 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001483 if (log)
1484 log->Printf ("ProcessGDBRemote::DoDetach()");
1485
1486 DisableAllBreakpointSites ();
1487
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001488 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001489
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001490 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1491 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001492 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001493 if (response_size)
1494 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1495 else
1496 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001497 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001498 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001499 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001500
Greg Clayton4fb400f2010-09-27 21:07:38 +00001501 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001502 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001503
1504 SetPrivateState (eStateDetached);
1505 ResumePrivateStateThread();
1506
1507 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001508 return error;
1509}
Chris Lattner24943d22010-06-08 16:52:24 +00001510
1511Error
1512ProcessGDBRemote::DoDestroy ()
1513{
1514 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001515 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001516 if (log)
1517 log->Printf ("ProcessGDBRemote::DoDestroy()");
1518
1519 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001520 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001521 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001522 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001523 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001524 // We are being asked to halt during an attach. We need to just close
1525 // our file handle and debugserver will go away, and we can be done...
1526 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001527 }
1528 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001529 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001530
1531 StringExtractorGDBRemote response;
1532 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001533 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001534 {
1535 char packet_cmd = response.GetChar(0);
1536
1537 if (packet_cmd == 'W' || packet_cmd == 'X')
1538 {
1539 m_last_stop_packet = response;
1540 SetExitStatus(response.GetHexU8(), NULL);
1541 }
1542 }
1543 else
1544 {
1545 SetExitStatus(SIGABRT, NULL);
1546 //error.SetErrorString("kill packet failed");
1547 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001548 }
1549 }
Chris Lattner24943d22010-06-08 16:52:24 +00001550 StopAsyncThread ();
1551 m_gdb_comm.StopReadThread();
1552 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001553 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001554 return error;
1555}
1556
Chris Lattner24943d22010-06-08 16:52:24 +00001557//------------------------------------------------------------------
1558// Process Queries
1559//------------------------------------------------------------------
1560
1561bool
1562ProcessGDBRemote::IsAlive ()
1563{
Greg Clayton58e844b2010-12-08 05:08:21 +00001564 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001565}
1566
1567addr_t
1568ProcessGDBRemote::GetImageInfoAddress()
1569{
1570 if (!m_gdb_comm.IsRunning())
1571 {
1572 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001573 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001574 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001575 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001576 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1577 }
1578 }
1579 return LLDB_INVALID_ADDRESS;
1580}
1581
Chris Lattner24943d22010-06-08 16:52:24 +00001582//------------------------------------------------------------------
1583// Process Memory
1584//------------------------------------------------------------------
1585size_t
1586ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1587{
1588 if (size > m_max_memory_size)
1589 {
1590 // Keep memory read sizes down to a sane limit. This function will be
1591 // called multiple times in order to complete the task by
1592 // lldb_private::Process so it is ok to do this.
1593 size = m_max_memory_size;
1594 }
1595
1596 char packet[64];
1597 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1598 assert (packet_len + 1 < sizeof(packet));
1599 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001600 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001601 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001602 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001603 {
1604 error.Clear();
1605 return response.GetHexBytes(buf, size, '\xdd');
1606 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001607 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001608 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001609 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001610 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1611 else
1612 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1613 }
1614 else
1615 {
1616 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1617 }
1618 return 0;
1619}
1620
1621size_t
1622ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1623{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001624 if (size > m_max_memory_size)
1625 {
1626 // Keep memory read sizes down to a sane limit. This function will be
1627 // called multiple times in order to complete the task by
1628 // lldb_private::Process so it is ok to do this.
1629 size = m_max_memory_size;
1630 }
1631
Chris Lattner24943d22010-06-08 16:52:24 +00001632 StreamString packet;
1633 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001634 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001635 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001636 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001637 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001638 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001639 {
1640 error.Clear();
1641 return size;
1642 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001643 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001644 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001645 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001646 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1647 else
1648 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1649 }
1650 else
1651 {
1652 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1653 }
1654 return 0;
1655}
1656
1657lldb::addr_t
1658ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1659{
Greg Clayton989816b2011-05-14 01:50:35 +00001660 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1661
Greg Clayton2f085c62011-05-15 01:25:55 +00001662 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001663 switch (supported)
1664 {
1665 case eLazyBoolCalculate:
1666 case eLazyBoolYes:
1667 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1668 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1669 return allocated_addr;
1670
1671 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001672 // Call mmap() to create memory in the inferior..
1673 unsigned prot = 0;
1674 if (permissions & lldb::ePermissionsReadable)
1675 prot |= eMmapProtRead;
1676 if (permissions & lldb::ePermissionsWritable)
1677 prot |= eMmapProtWrite;
1678 if (permissions & lldb::ePermissionsExecutable)
1679 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001680
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001681 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1682 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1683 m_addr_to_mmap_size[allocated_addr] = size;
1684 else
1685 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001686 break;
1687 }
1688
Chris Lattner24943d22010-06-08 16:52:24 +00001689 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001690 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001691 else
1692 error.Clear();
1693 return allocated_addr;
1694}
1695
1696Error
1697ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1698{
1699 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001700 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1701
1702 switch (supported)
1703 {
1704 case eLazyBoolCalculate:
1705 // We should never be deallocating memory without allocating memory
1706 // first so we should never get eLazyBoolCalculate
1707 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1708 break;
1709
1710 case eLazyBoolYes:
1711 if (!m_gdb_comm.DeallocateMemory (addr))
1712 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1713 break;
1714
1715 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001716 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001717 {
1718 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001719 if (pos != m_addr_to_mmap_size.end() &&
1720 InferiorCallMunmap(this, addr, pos->second))
1721 m_addr_to_mmap_size.erase (pos);
1722 else
1723 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001724 }
1725 break;
1726 }
1727
Chris Lattner24943d22010-06-08 16:52:24 +00001728 return error;
1729}
1730
1731
1732//------------------------------------------------------------------
1733// Process STDIO
1734//------------------------------------------------------------------
1735
1736size_t
1737ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1738{
1739 Mutex::Locker locker(m_stdio_mutex);
1740 size_t bytes_available = m_stdout_data.size();
1741 if (bytes_available > 0)
1742 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001743 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1744 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001745 log->Printf ("ProcessGDBRemote::%s (&%p[%lu]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001746 if (bytes_available > buf_size)
1747 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001748 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001749 m_stdout_data.erase(0, buf_size);
1750 bytes_available = buf_size;
1751 }
1752 else
1753 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001754 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001755 m_stdout_data.clear();
1756
1757 //ResetEventBits(eBroadcastBitSTDOUT);
1758 }
1759 }
1760 return bytes_available;
1761}
1762
1763size_t
1764ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1765{
1766 // Can we get STDERR through the remote protocol?
1767 return 0;
1768}
1769
1770size_t
1771ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1772{
1773 if (m_stdio_communication.IsConnected())
1774 {
1775 ConnectionStatus status;
1776 m_stdio_communication.Write(src, src_len, status, NULL);
1777 }
1778 return 0;
1779}
1780
1781Error
1782ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1783{
1784 Error error;
1785 assert (bp_site != NULL);
1786
Greg Claytone005f2c2010-11-06 01:53:30 +00001787 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001788 user_id_t site_id = bp_site->GetID();
1789 const addr_t addr = bp_site->GetLoadAddress();
1790 if (log)
1791 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1792
1793 if (bp_site->IsEnabled())
1794 {
1795 if (log)
1796 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1797 return error;
1798 }
1799 else
1800 {
1801 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1802
1803 if (bp_site->HardwarePreferred())
1804 {
1805 // Try and set hardware breakpoint, and if that fails, fall through
1806 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001807 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001808 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001809 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001810 {
1811 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001812 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001813 return error;
1814 }
Chris Lattner24943d22010-06-08 16:52:24 +00001815 }
1816 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001817
1818 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001819 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001820 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1821 {
1822 bp_site->SetEnabled(true);
1823 bp_site->SetType (BreakpointSite::eExternal);
1824 return error;
1825 }
Chris Lattner24943d22010-06-08 16:52:24 +00001826 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001827
1828 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001829 }
1830
1831 if (log)
1832 {
1833 const char *err_string = error.AsCString();
1834 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1835 bp_site->GetLoadAddress(),
1836 err_string ? err_string : "NULL");
1837 }
1838 // We shouldn't reach here on a successful breakpoint enable...
1839 if (error.Success())
1840 error.SetErrorToGenericError();
1841 return error;
1842}
1843
1844Error
1845ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1846{
1847 Error error;
1848 assert (bp_site != NULL);
1849 addr_t addr = bp_site->GetLoadAddress();
1850 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001851 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001852 if (log)
1853 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1854
1855 if (bp_site->IsEnabled())
1856 {
1857 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1858
Greg Claytonb72d0f02011-04-12 05:54:46 +00001859 BreakpointSite::Type bp_type = bp_site->GetType();
1860 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001861 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001862 case BreakpointSite::eSoftware:
1863 error = DisableSoftwareBreakpoint (bp_site);
1864 break;
1865
1866 case BreakpointSite::eHardware:
1867 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1868 error.SetErrorToGenericError();
1869 break;
1870
1871 case BreakpointSite::eExternal:
1872 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1873 error.SetErrorToGenericError();
1874 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001875 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001876 if (error.Success())
1877 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001878 }
1879 else
1880 {
1881 if (log)
1882 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1883 return error;
1884 }
1885
1886 if (error.Success())
1887 error.SetErrorToGenericError();
1888 return error;
1889}
1890
Johnny Chen21900fb2011-09-06 22:38:36 +00001891// Pre-requisite: wp != NULL.
1892static GDBStoppointType
1893GetGDBStoppointType (WatchpointLocation *wp)
1894{
1895 assert(wp);
1896 bool watch_read = wp->WatchpointRead();
1897 bool watch_write = wp->WatchpointWrite();
1898
1899 // watch_read and watch_write cannot both be false.
1900 assert(watch_read || watch_write);
1901 if (watch_read && watch_write)
1902 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001903 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00001904 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00001905 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00001906 return eWatchpointWrite;
1907}
1908
Chris Lattner24943d22010-06-08 16:52:24 +00001909Error
1910ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1911{
1912 Error error;
1913 if (wp)
1914 {
1915 user_id_t watchID = wp->GetID();
1916 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001917 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001918 if (log)
1919 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1920 if (wp->IsEnabled())
1921 {
1922 if (log)
1923 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1924 return error;
1925 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001926
1927 GDBStoppointType type = GetGDBStoppointType(wp);
1928 // Pass down an appropriate z/Z packet...
1929 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00001930 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001931 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
1932 {
1933 wp->SetEnabled(true);
1934 return error;
1935 }
1936 else
1937 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001938 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001939 else
1940 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00001941 }
1942 else
1943 {
1944 error.SetErrorString("Watchpoint location argument was NULL.");
1945 }
1946 if (error.Success())
1947 error.SetErrorToGenericError();
1948 return error;
1949}
1950
1951Error
1952ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1953{
1954 Error error;
1955 if (wp)
1956 {
1957 user_id_t watchID = wp->GetID();
1958
Greg Claytone005f2c2010-11-06 01:53:30 +00001959 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001960
1961 addr_t addr = wp->GetLoadAddress();
1962 if (log)
1963 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1964
Johnny Chen21900fb2011-09-06 22:38:36 +00001965 if (!wp->IsEnabled())
1966 {
1967 if (log)
1968 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
1969 return error;
1970 }
1971
Chris Lattner24943d22010-06-08 16:52:24 +00001972 if (wp->IsHardware())
1973 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001974 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00001975 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00001976 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
1977 {
1978 wp->SetEnabled(false);
1979 return error;
1980 }
1981 else
1982 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001983 }
1984 // TODO: clear software watchpoints if we implement them
1985 }
1986 else
1987 {
1988 error.SetErrorString("Watchpoint location argument was NULL.");
1989 }
1990 if (error.Success())
1991 error.SetErrorToGenericError();
1992 return error;
1993}
1994
1995void
1996ProcessGDBRemote::Clear()
1997{
1998 m_flags = 0;
1999 m_thread_list.Clear();
2000 {
2001 Mutex::Locker locker(m_stdio_mutex);
2002 m_stdout_data.clear();
2003 }
Chris Lattner24943d22010-06-08 16:52:24 +00002004}
2005
2006Error
2007ProcessGDBRemote::DoSignal (int signo)
2008{
2009 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002010 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002011 if (log)
2012 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2013
2014 if (!m_gdb_comm.SendAsyncSignal (signo))
2015 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2016 return error;
2017}
2018
Chris Lattner24943d22010-06-08 16:52:24 +00002019Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002020ProcessGDBRemote::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 +00002021{
2022 Error error;
2023 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2024 {
2025 // If we locate debugserver, keep that located version around
2026 static FileSpec g_debugserver_file_spec;
2027
Greg Claytonb72d0f02011-04-12 05:54:46 +00002028 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002029 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002030 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002031
2032 // Always check to see if we have an environment override for the path
2033 // to the debugserver to use and use it if we do.
2034 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2035 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002036 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002037 else
2038 debugserver_file_spec = g_debugserver_file_spec;
2039 bool debugserver_exists = debugserver_file_spec.Exists();
2040 if (!debugserver_exists)
2041 {
2042 // The debugserver binary is in the LLDB.framework/Resources
2043 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002044 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002045 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002046 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002047 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002048 if (debugserver_exists)
2049 {
2050 g_debugserver_file_spec = debugserver_file_spec;
2051 }
2052 else
2053 {
2054 g_debugserver_file_spec.Clear();
2055 debugserver_file_spec.Clear();
2056 }
Chris Lattner24943d22010-06-08 16:52:24 +00002057 }
2058 }
2059
2060 if (debugserver_exists)
2061 {
2062 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2063
2064 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002065
Greg Claytone005f2c2010-11-06 01:53:30 +00002066 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002067
Greg Claytonb72d0f02011-04-12 05:54:46 +00002068 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002069 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002070
Chris Lattner24943d22010-06-08 16:52:24 +00002071 // Start args with "debugserver /file/path -r --"
2072 debugserver_args.AppendArgument(debugserver_path);
2073 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002074 // use native registers, not the GDB registers
2075 debugserver_args.AppendArgument("--native-regs");
2076 // make debugserver run in its own session so signals generated by
2077 // special terminal key sequences (^C) don't affect debugserver
2078 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002079
Chris Lattner24943d22010-06-08 16:52:24 +00002080 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2081 if (env_debugserver_log_file)
2082 {
2083 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2084 debugserver_args.AppendArgument(arg_cstr);
2085 }
2086
2087 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2088 if (env_debugserver_log_flags)
2089 {
2090 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2091 debugserver_args.AppendArgument(arg_cstr);
2092 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002093// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002094// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002095
Greg Claytonb72d0f02011-04-12 05:54:46 +00002096 // We currently send down all arguments, attach pids, or attach
2097 // process names in dedicated GDB server packets, so we don't need
2098 // to pass them as arguments. This is currently because of all the
2099 // things we need to setup prior to launching: the environment,
2100 // current working dir, file actions, etc.
2101#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002102 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002103 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002104 {
Greg Claytona2f74232011-02-24 22:24:29 +00002105 // Terminate the debugserver args so we can now append the inferior args
2106 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002107
Greg Claytona2f74232011-02-24 22:24:29 +00002108 for (int i = 0; inferior_argv[i] != NULL; ++i)
2109 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002110 }
2111 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2112 {
2113 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2114 debugserver_args.AppendArgument (arg_cstr);
2115 }
2116 else if (attach_name && attach_name[0])
2117 {
2118 if (wait_for_launch)
2119 debugserver_args.AppendArgument ("--waitfor");
2120 else
2121 debugserver_args.AppendArgument ("--attach");
2122 debugserver_args.AppendArgument (attach_name);
2123 }
Chris Lattner24943d22010-06-08 16:52:24 +00002124#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002125
2126 ProcessLaunchInfo::FileAction file_action;
2127
2128 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2129 // to "/dev/null" if we run into any problems.
2130 file_action.Close (STDIN_FILENO);
2131 launch_info.AppendFileAction (file_action);
2132 file_action.Close (STDOUT_FILENO);
2133 launch_info.AppendFileAction (file_action);
2134 file_action.Close (STDERR_FILENO);
2135 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002136
2137 if (log)
2138 {
2139 StreamString strm;
2140 debugserver_args.Dump (&strm);
2141 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2142 }
2143
Greg Claytonb72d0f02011-04-12 05:54:46 +00002144 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002145
Greg Claytonb72d0f02011-04-12 05:54:46 +00002146 if (error.Success ())
2147 m_debugserver_pid = launch_info.GetProcessID();
2148 else
Chris Lattner24943d22010-06-08 16:52:24 +00002149 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2150
2151 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002152 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002153 }
2154 else
2155 {
2156 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2157 }
2158
2159 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2160 StartAsyncThread ();
2161 }
2162 return error;
2163}
2164
2165bool
2166ProcessGDBRemote::MonitorDebugserverProcess
2167(
2168 void *callback_baton,
2169 lldb::pid_t debugserver_pid,
2170 int signo, // Zero for no signal
2171 int exit_status // Exit value of process if signal is zero
2172)
2173{
2174 // We pass in the ProcessGDBRemote inferior process it and name it
2175 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2176 // pointer value itself, thus we need the double cast...
2177
2178 // "debugserver_pid" argument passed in is the process ID for
2179 // debugserver that we are tracking...
2180
Greg Clayton75ccf502010-08-21 02:22:51 +00002181 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002182
2183 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2184 if (log)
2185 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2186
Greg Clayton75ccf502010-08-21 02:22:51 +00002187 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002188 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002189 // Sleep for a half a second to make sure our inferior process has
2190 // time to set its exit status before we set it incorrectly when
2191 // both the debugserver and the inferior process shut down.
2192 usleep (500000);
2193 // If our process hasn't yet exited, debugserver might have died.
2194 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002195 const StateType state = process->GetState();
2196
2197 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2198 state != eStateInvalid &&
2199 state != eStateUnloaded &&
2200 state != eStateExited &&
2201 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002202 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002203 char error_str[1024];
2204 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002205 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002206 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2207 if (signal_cstr)
2208 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002209 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002210 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002211 }
2212 else
2213 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002214 ::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 +00002215 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002216
2217 process->SetExitStatus (-1, error_str);
2218 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002219 // Debugserver has exited we need to let our ProcessGDBRemote
2220 // know that it no longer has a debugserver instance
2221 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2222 // We are returning true to this function below, so we can
2223 // forget about the monitor handle.
2224 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002225 }
2226 return true;
2227}
2228
2229void
2230ProcessGDBRemote::KillDebugserverProcess ()
2231{
2232 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2233 {
2234 ::kill (m_debugserver_pid, SIGINT);
2235 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2236 }
2237}
2238
2239void
2240ProcessGDBRemote::Initialize()
2241{
2242 static bool g_initialized = false;
2243
2244 if (g_initialized == false)
2245 {
2246 g_initialized = true;
2247 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2248 GetPluginDescriptionStatic(),
2249 CreateInstance);
2250
2251 Log::Callbacks log_callbacks = {
2252 ProcessGDBRemoteLog::DisableLog,
2253 ProcessGDBRemoteLog::EnableLog,
2254 ProcessGDBRemoteLog::ListLogCategories
2255 };
2256
2257 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2258 }
2259}
2260
2261bool
Chris Lattner24943d22010-06-08 16:52:24 +00002262ProcessGDBRemote::StartAsyncThread ()
2263{
Greg Claytone005f2c2010-11-06 01:53:30 +00002264 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002265
2266 if (log)
2267 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2268
2269 // Create a thread that watches our internal state and controls which
2270 // events make it to clients (into the DCProcess event queue).
2271 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002272 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002273}
2274
2275void
2276ProcessGDBRemote::StopAsyncThread ()
2277{
Greg Claytone005f2c2010-11-06 01:53:30 +00002278 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002279
2280 if (log)
2281 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2282
2283 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2284
2285 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002286 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002287 {
2288 Host::ThreadJoin (m_async_thread, NULL, NULL);
2289 }
2290}
2291
2292
2293void *
2294ProcessGDBRemote::AsyncThread (void *arg)
2295{
2296 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2297
Greg Claytone005f2c2010-11-06 01:53:30 +00002298 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002299 if (log)
2300 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2301
2302 Listener listener ("ProcessGDBRemote::AsyncThread");
2303 EventSP event_sp;
2304 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2305 eBroadcastBitAsyncThreadShouldExit;
2306
2307 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2308 {
Greg Claytona2f74232011-02-24 22:24:29 +00002309 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2310
Chris Lattner24943d22010-06-08 16:52:24 +00002311 bool done = false;
2312 while (!done)
2313 {
2314 if (log)
2315 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2316 if (listener.WaitForEvent (NULL, event_sp))
2317 {
2318 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002319 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002320 {
Greg Claytona2f74232011-02-24 22:24:29 +00002321 if (log)
2322 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 +00002323
Greg Claytona2f74232011-02-24 22:24:29 +00002324 switch (event_type)
2325 {
2326 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002327 {
Greg Claytona2f74232011-02-24 22:24:29 +00002328 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002329
Greg Claytona2f74232011-02-24 22:24:29 +00002330 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002331 {
Greg Claytona2f74232011-02-24 22:24:29 +00002332 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2333 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2334 if (log)
2335 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002336
Greg Claytona2f74232011-02-24 22:24:29 +00002337 if (::strstr (continue_cstr, "vAttach") == NULL)
2338 process->SetPrivateState(eStateRunning);
2339 StringExtractorGDBRemote response;
2340 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002341
Greg Claytona2f74232011-02-24 22:24:29 +00002342 switch (stop_state)
2343 {
2344 case eStateStopped:
2345 case eStateCrashed:
2346 case eStateSuspended:
2347 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002348 process->SetPrivateState (stop_state);
2349 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002350
Greg Claytona2f74232011-02-24 22:24:29 +00002351 case eStateExited:
2352 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002353 response.SetFilePos(1);
2354 process->SetExitStatus(response.GetHexU8(), NULL);
2355 done = true;
2356 break;
2357
2358 case eStateInvalid:
2359 process->SetExitStatus(-1, "lost connection");
2360 break;
2361
2362 default:
2363 process->SetPrivateState (stop_state);
2364 break;
2365 }
Chris Lattner24943d22010-06-08 16:52:24 +00002366 }
2367 }
Greg Claytona2f74232011-02-24 22:24:29 +00002368 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002369
Greg Claytona2f74232011-02-24 22:24:29 +00002370 case eBroadcastBitAsyncThreadShouldExit:
2371 if (log)
2372 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2373 done = true;
2374 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002375
Greg Claytona2f74232011-02-24 22:24:29 +00002376 default:
2377 if (log)
2378 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2379 done = true;
2380 break;
2381 }
2382 }
2383 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2384 {
2385 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2386 {
2387 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002388 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002389 }
Chris Lattner24943d22010-06-08 16:52:24 +00002390 }
2391 }
2392 else
2393 {
2394 if (log)
2395 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2396 done = true;
2397 }
2398 }
2399 }
2400
2401 if (log)
2402 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2403
2404 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2405 return NULL;
2406}
2407
Chris Lattner24943d22010-06-08 16:52:24 +00002408const char *
2409ProcessGDBRemote::GetDispatchQueueNameForThread
2410(
2411 addr_t thread_dispatch_qaddr,
2412 std::string &dispatch_queue_name
2413)
2414{
2415 dispatch_queue_name.clear();
2416 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2417 {
2418 // Cache the dispatch_queue_offsets_addr value so we don't always have
2419 // to look it up
2420 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2421 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002422 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2423 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002424 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002425 if (module_sp)
2426 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2427
2428 if (dispatch_queue_offsets_symbol == NULL)
2429 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002430 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002431 if (module_sp)
2432 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2433 }
Chris Lattner24943d22010-06-08 16:52:24 +00002434 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002435 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002436
2437 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2438 return NULL;
2439 }
2440
2441 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002442 DataExtractor data (memory_buffer,
2443 sizeof(memory_buffer),
2444 m_target.GetArchitecture().GetByteOrder(),
2445 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002446
2447 // Excerpt from src/queue_private.h
2448 struct dispatch_queue_offsets_s
2449 {
2450 uint16_t dqo_version;
2451 uint16_t dqo_label;
2452 uint16_t dqo_label_size;
2453 } dispatch_queue_offsets;
2454
2455
2456 Error error;
2457 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2458 {
2459 uint32_t data_offset = 0;
2460 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2461 {
2462 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2463 {
2464 data_offset = 0;
2465 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2466 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2467 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2468 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2469 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2470 dispatch_queue_name.erase (bytes_read);
2471 }
2472 }
2473 }
2474 }
2475 if (dispatch_queue_name.empty())
2476 return NULL;
2477 return dispatch_queue_name.c_str();
2478}
2479
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002480//uint32_t
2481//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2482//{
2483// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2484// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2485// if (m_local_debugserver)
2486// {
2487// return Host::ListProcessesMatchingName (name, matches, pids);
2488// }
2489// else
2490// {
2491// // FIXME: Implement talking to the remote debugserver.
2492// return 0;
2493// }
2494//
2495//}
2496//
Jim Ingham55e01d82011-01-22 01:33:44 +00002497bool
2498ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2499 lldb_private::StoppointCallbackContext *context,
2500 lldb::user_id_t break_id,
2501 lldb::user_id_t break_loc_id)
2502{
2503 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2504 // run so I can stop it if that's what I want to do.
2505 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2506 if (log)
2507 log->Printf("Hit New Thread Notification breakpoint.");
2508 return false;
2509}
2510
2511
2512bool
2513ProcessGDBRemote::StartNoticingNewThreads()
2514{
2515 static const char *bp_names[] =
2516 {
2517 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002518 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002519 "_pthread_start",
2520 NULL
2521 };
2522
2523 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2524 size_t num_bps = m_thread_observation_bps.size();
2525 if (num_bps != 0)
2526 {
2527 for (int i = 0; i < num_bps; i++)
2528 {
2529 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2530 if (break_sp)
2531 {
2532 if (log)
2533 log->Printf("Enabled noticing new thread breakpoint.");
2534 break_sp->SetEnabled(true);
2535 }
2536 }
2537 }
2538 else
2539 {
2540 for (int i = 0; bp_names[i] != NULL; i++)
2541 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002542 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002543 if (breakpoint)
2544 {
2545 if (log)
2546 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2547 m_thread_observation_bps.push_back(breakpoint->GetID());
2548 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2549 }
2550 else
2551 {
2552 if (log)
2553 log->Printf("Failed to create new thread notification breakpoint.");
2554 return false;
2555 }
2556 }
2557 }
2558
2559 return true;
2560}
2561
2562bool
2563ProcessGDBRemote::StopNoticingNewThreads()
2564{
Jim Inghamff276fe2011-02-08 05:19:01 +00002565 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2566 if (log)
2567 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002568 size_t num_bps = m_thread_observation_bps.size();
2569 if (num_bps != 0)
2570 {
2571 for (int i = 0; i < num_bps; i++)
2572 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002573
2574 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2575 if (break_sp)
2576 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002577 break_sp->SetEnabled(false);
2578 }
2579 }
2580 }
2581 return true;
2582}
2583
2584