blob: 8b0c47c250104284714932a9206821c26cc0d732 [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"
Greg Clayton54e7afa2010-07-09 20:39:50 +000048#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "GDBRemoteRegisterContext.h"
50#include "ProcessGDBRemote.h"
51#include "ProcessGDBRemoteLog.h"
52#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000053#include "StopInfoMachException.h"
54
Chris Lattner24943d22010-06-08 16:52:24 +000055
Chris Lattner24943d22010-06-08 16:52:24 +000056
57#define DEBUGSERVER_BASENAME "debugserver"
58using namespace lldb;
59using namespace lldb_private;
60
Jim Inghamf9600482011-03-29 21:45:47 +000061static bool rand_initialized = false;
62
Chris Lattner24943d22010-06-08 16:52:24 +000063static inline uint16_t
64get_random_port ()
65{
Jim Inghamf9600482011-03-29 21:45:47 +000066 if (!rand_initialized)
67 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000068 time_t seed = time(NULL);
69
Jim Inghamf9600482011-03-29 21:45:47 +000070 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000071 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000072 }
Stephen Wilson50daf772011-03-25 18:16:28 +000073 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000074}
75
76
77const char *
78ProcessGDBRemote::GetPluginNameStatic()
79{
Greg Claytonb1888f22011-03-19 01:12:21 +000080 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000081}
82
83const char *
84ProcessGDBRemote::GetPluginDescriptionStatic()
85{
86 return "GDB Remote protocol based debugging plug-in.";
87}
88
89void
90ProcessGDBRemote::Terminate()
91{
92 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
93}
94
95
96Process*
97ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
98{
99 return new ProcessGDBRemote (target, listener);
100}
101
102bool
103ProcessGDBRemote::CanDebug(Target &target)
104{
105 // For now we are just making sure the file exists for a given module
106 ModuleSP exe_module_sp(target.GetExecutableModule());
107 if (exe_module_sp.get())
108 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000109 // However, if there is no executable module, we return true since we might be preparing to attach.
110 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000111}
112
113//----------------------------------------------------------------------
114// ProcessGDBRemote constructor
115//----------------------------------------------------------------------
116ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
117 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000118 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000119 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000120 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000121 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000122 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000123 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000124 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000125 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
126 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000127 m_continue_c_tids (),
128 m_continue_C_tids (),
129 m_continue_s_tids (),
130 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000131 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000132 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000133 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000134 m_local_debugserver (true),
135 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();
155}
156
157//----------------------------------------------------------------------
158// PluginInterface
159//----------------------------------------------------------------------
160const char *
161ProcessGDBRemote::GetPluginName()
162{
163 return "Process debugging plug-in that uses the GDB remote protocol";
164}
165
166const char *
167ProcessGDBRemote::GetShortPluginName()
168{
169 return GetPluginNameStatic();
170}
171
172uint32_t
173ProcessGDBRemote::GetPluginVersion()
174{
175 return 1;
176}
177
178void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000179ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000180{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000181 if (!force && m_register_info.GetNumRegisters() > 0)
182 return;
183
184 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000185 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000186 uint32_t reg_offset = 0;
187 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000188 StringExtractorGDBRemote::ResponseType response_type;
189 for (response_type = StringExtractorGDBRemote::eResponse;
190 response_type == StringExtractorGDBRemote::eResponse;
191 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000192 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000193 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
194 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000195 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000196 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000197 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000198 response_type = response.GetResponseType();
199 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000200 {
201 std::string name;
202 std::string value;
203 ConstString reg_name;
204 ConstString alt_name;
205 ConstString set_name;
206 RegisterInfo reg_info = { NULL, // Name
207 NULL, // Alt name
208 0, // byte size
209 reg_offset, // offset
210 eEncodingUint, // encoding
211 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000212 {
213 LLDB_INVALID_REGNUM, // GCC reg num
214 LLDB_INVALID_REGNUM, // DWARF reg num
215 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000216 reg_num, // GDB reg num
217 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000218 }
219 };
220
221 while (response.GetNameColonValue(name, value))
222 {
223 if (name.compare("name") == 0)
224 {
225 reg_name.SetCString(value.c_str());
226 }
227 else if (name.compare("alt-name") == 0)
228 {
229 alt_name.SetCString(value.c_str());
230 }
231 else if (name.compare("bitsize") == 0)
232 {
233 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
234 }
235 else if (name.compare("offset") == 0)
236 {
237 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000238 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000239 {
240 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000241 }
242 }
243 else if (name.compare("encoding") == 0)
244 {
245 if (value.compare("uint") == 0)
246 reg_info.encoding = eEncodingUint;
247 else if (value.compare("sint") == 0)
248 reg_info.encoding = eEncodingSint;
249 else if (value.compare("ieee754") == 0)
250 reg_info.encoding = eEncodingIEEE754;
251 else if (value.compare("vector") == 0)
252 reg_info.encoding = eEncodingVector;
253 }
254 else if (name.compare("format") == 0)
255 {
256 if (value.compare("binary") == 0)
257 reg_info.format = eFormatBinary;
258 else if (value.compare("decimal") == 0)
259 reg_info.format = eFormatDecimal;
260 else if (value.compare("hex") == 0)
261 reg_info.format = eFormatHex;
262 else if (value.compare("float") == 0)
263 reg_info.format = eFormatFloat;
264 else if (value.compare("vector-sint8") == 0)
265 reg_info.format = eFormatVectorOfSInt8;
266 else if (value.compare("vector-uint8") == 0)
267 reg_info.format = eFormatVectorOfUInt8;
268 else if (value.compare("vector-sint16") == 0)
269 reg_info.format = eFormatVectorOfSInt16;
270 else if (value.compare("vector-uint16") == 0)
271 reg_info.format = eFormatVectorOfUInt16;
272 else if (value.compare("vector-sint32") == 0)
273 reg_info.format = eFormatVectorOfSInt32;
274 else if (value.compare("vector-uint32") == 0)
275 reg_info.format = eFormatVectorOfUInt32;
276 else if (value.compare("vector-float32") == 0)
277 reg_info.format = eFormatVectorOfFloat32;
278 else if (value.compare("vector-uint128") == 0)
279 reg_info.format = eFormatVectorOfUInt128;
280 }
281 else if (name.compare("set") == 0)
282 {
283 set_name.SetCString(value.c_str());
284 }
285 else if (name.compare("gcc") == 0)
286 {
287 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
288 }
289 else if (name.compare("dwarf") == 0)
290 {
291 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
292 }
293 else if (name.compare("generic") == 0)
294 {
295 if (value.compare("pc") == 0)
296 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
297 else if (value.compare("sp") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
299 else if (value.compare("fp") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
301 else if (value.compare("ra") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
303 else if (value.compare("flags") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000305 else if (value.find("arg") == 0)
306 {
307 if (value.size() == 4)
308 {
309 switch (value[3])
310 {
311 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
312 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
313 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
314 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
315 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
316 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
317 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
318 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
319 }
320 }
321 }
Chris Lattner24943d22010-06-08 16:52:24 +0000322 }
323 }
324
Jason Molenda53d96862010-06-11 23:44:18 +0000325 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000326 assert (reg_info.byte_size != 0);
327 reg_offset += reg_info.byte_size;
328 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
329 }
330 }
331 else
332 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000333 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000334 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000335 }
336 }
337
338 if (reg_num == 0)
339 {
340 // We didn't get anything. See if we are debugging ARM and fill with
341 // a hard coded register set until we can get an updated debugserver
342 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000343 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000344 m_register_info.HardcodeARMRegisters();
345 }
346 m_register_info.Finalize ();
347}
348
349Error
350ProcessGDBRemote::WillLaunch (Module* module)
351{
352 return WillLaunchOrAttach ();
353}
354
355Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000356ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000357{
358 return WillLaunchOrAttach ();
359}
360
361Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000362ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000363{
364 return WillLaunchOrAttach ();
365}
366
367Error
Greg Claytone71e2582011-02-04 01:58:07 +0000368ProcessGDBRemote::DoConnectRemote (const char *remote_url)
369{
370 Error error (WillLaunchOrAttach ());
371
372 if (error.Fail())
373 return error;
374
Greg Clayton180546b2011-04-30 01:09:13 +0000375 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000376
377 if (error.Fail())
378 return error;
379 StartAsyncThread ();
380
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000381 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000382 if (pid == LLDB_INVALID_PROCESS_ID)
383 {
384 // We don't have a valid process ID, so note that we are connected
385 // and could now request to launch or attach, or get remote process
386 // listings...
387 SetPrivateState (eStateConnected);
388 }
389 else
390 {
391 // We have a valid process
392 SetID (pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000393 UpdateThreadListIfNeeded ();
Greg Clayton261a18b2011-06-02 22:22:38 +0000394 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000395 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000396 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000397 if (state == eStateStopped)
398 {
399 SetPrivateState (state);
400 }
401 else
402 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
403 }
404 else
405 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
406 }
407 return error;
408}
409
410Error
Chris Lattner24943d22010-06-08 16:52:24 +0000411ProcessGDBRemote::WillLaunchOrAttach ()
412{
413 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000414 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000415 return error;
416}
417
418//----------------------------------------------------------------------
419// Process Control
420//----------------------------------------------------------------------
421Error
422ProcessGDBRemote::DoLaunch
423(
424 Module* module,
425 char const *argv[],
426 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000427 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000428 const char *stdin_path,
429 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000430 const char *stderr_path,
431 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000432)
433{
Greg Clayton4b407112010-09-30 21:49:03 +0000434 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000435 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
436 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
437 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000438
439 ObjectFile * object_file = module->GetObjectFile();
440 if (object_file)
441 {
Chris Lattner24943d22010-06-08 16:52:24 +0000442 char host_port[128];
443 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000444 char connect_url[128];
445 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000446
Greg Claytona2f74232011-02-24 22:24:29 +0000447 // Make sure we aren't already connected?
448 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000449 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000450 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000451 if (error.Fail())
452 return error;
453
Greg Claytone71e2582011-02-04 01:58:07 +0000454 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000455 }
456
457 if (error.Success())
458 {
459 lldb_utility::PseudoTerminal pty;
460 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000461
462 // If the debugserver is local and we aren't disabling STDIO, lets use
463 // a pseudo terminal to instead of relying on the 'O' packets for stdio
464 // since 'O' packets can really slow down debugging if the inferior
465 // does a lot of output.
466 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000467 {
468 const char *slave_name = NULL;
469 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000470 {
Greg Claytona2f74232011-02-24 22:24:29 +0000471 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
472 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000473 }
Greg Claytona2f74232011-02-24 22:24:29 +0000474 if (stdin_path == NULL)
475 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000476
Greg Claytona2f74232011-02-24 22:24:29 +0000477 if (stdout_path == NULL)
478 stdout_path = slave_name;
479
480 if (stderr_path == NULL)
481 stderr_path = slave_name;
482 }
483
Greg Claytonafb81862011-03-02 21:34:46 +0000484 // Set STDIN to /dev/null if we want STDIO disabled or if either
485 // STDOUT or STDERR have been set to something and STDIN hasn't
486 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000487 stdin_path = "/dev/null";
488
Greg Claytonafb81862011-03-02 21:34:46 +0000489 // Set STDOUT to /dev/null if we want STDIO disabled or if either
490 // STDIN or STDERR have been set to something and STDOUT hasn't
491 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000492 stdout_path = "/dev/null";
493
Greg Claytonafb81862011-03-02 21:34:46 +0000494 // Set STDERR to /dev/null if we want STDIO disabled or if either
495 // STDIN or STDOUT have been set to something and STDERR hasn't
496 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000497 stderr_path = "/dev/null";
498
499 if (stdin_path)
500 m_gdb_comm.SetSTDIN (stdin_path);
501 if (stdout_path)
502 m_gdb_comm.SetSTDOUT (stdout_path);
503 if (stderr_path)
504 m_gdb_comm.SetSTDERR (stderr_path);
505
506 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
507
Greg Claytona4582402011-05-08 04:53:50 +0000508 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000509
510 if (working_dir && working_dir[0])
511 {
512 m_gdb_comm.SetWorkingDir (working_dir);
513 }
514
515 // Send the environment and the program + arguments after we connect
516 if (envp)
517 {
518 const char *env_entry;
519 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000520 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000521 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000522 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000523 }
Greg Claytona2f74232011-02-24 22:24:29 +0000524 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000525
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000526 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
527 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
528 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000529 if (arg_packet_err == 0)
530 {
531 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000532 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000533 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000534 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000535 }
536 else
537 {
Greg Claytona2f74232011-02-24 22:24:29 +0000538 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000539 }
Greg Claytona2f74232011-02-24 22:24:29 +0000540 }
541 else
542 {
543 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
544 }
Chris Lattner24943d22010-06-08 16:52:24 +0000545
Greg Claytona2f74232011-02-24 22:24:29 +0000546 if (GetID() == LLDB_INVALID_PROCESS_ID)
547 {
548 KillDebugserverProcess ();
549 return error;
550 }
551
Greg Clayton261a18b2011-06-02 22:22:38 +0000552 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000553 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000554 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000555
556 if (!disable_stdio)
557 {
558 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
559 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
560 }
Chris Lattner24943d22010-06-08 16:52:24 +0000561 }
562 }
Chris Lattner24943d22010-06-08 16:52:24 +0000563 }
564 else
565 {
566 // Set our user ID to an invalid process ID.
567 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000568 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
569 module->GetFileSpec().GetFilename().AsCString(),
570 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000571 }
Chris Lattner24943d22010-06-08 16:52:24 +0000572 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000573
Chris Lattner24943d22010-06-08 16:52:24 +0000574}
575
576
577Error
Greg Claytone71e2582011-02-04 01:58:07 +0000578ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000579{
580 Error error;
581 // Sleep and wait a bit for debugserver to start to listen...
582 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
583 if (conn_ap.get())
584 {
Chris Lattner24943d22010-06-08 16:52:24 +0000585 const uint32_t max_retry_count = 50;
586 uint32_t retry_count = 0;
587 while (!m_gdb_comm.IsConnected())
588 {
Greg Claytone71e2582011-02-04 01:58:07 +0000589 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000590 {
591 m_gdb_comm.SetConnection (conn_ap.release());
592 break;
593 }
594 retry_count++;
595
596 if (retry_count >= max_retry_count)
597 break;
598
599 usleep (100000);
600 }
601 }
602
603 if (!m_gdb_comm.IsConnected())
604 {
605 if (error.Success())
606 error.SetErrorString("not connected to remote gdb server");
607 return error;
608 }
609
Greg Clayton24bc5d92011-03-30 18:16:51 +0000610 // We always seem to be able to open a connection to a local port
611 // so we need to make sure we can then send data to it. If we can't
612 // then we aren't actually connected to anything, so try and do the
613 // handshake with the remote GDB server and make sure that goes
614 // alright.
615 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000616 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000617 m_gdb_comm.Disconnect();
618 if (error.Success())
619 error.SetErrorString("not connected to remote gdb server");
620 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000621 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000622 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
623 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
624 this,
625 m_debugserver_pid,
626 false);
627 m_gdb_comm.ResetDiscoverableSettings();
628 m_gdb_comm.QueryNoAckModeSupported ();
629 m_gdb_comm.GetThreadSuffixSupported ();
630 m_gdb_comm.GetHostInfo ();
631 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000632 return error;
633}
634
635void
636ProcessGDBRemote::DidLaunchOrAttach ()
637{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000638 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
639 if (log)
640 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000641 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000642 {
643 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
644
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000645 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000646
Chris Lattner24943d22010-06-08 16:52:24 +0000647 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000648
Greg Claytoncb8977d2011-03-23 00:09:55 +0000649 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
650 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000651 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000652 ArchSpec &target_arch = GetTarget().GetArchitecture();
653
654 if (target_arch.IsValid())
655 {
656 // If the remote host is ARM and we have apple as the vendor, then
657 // ARM executables and shared libraries can have mixed ARM architectures.
658 // You can have an armv6 executable, and if the host is armv7, then the
659 // system will load the best possible architecture for all shared libraries
660 // it has, so we really need to take the remote host architecture as our
661 // defacto architecture in this case.
662
663 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
664 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
665 {
666 target_arch = gdb_remote_arch;
667 }
668 else
669 {
670 // Fill in what is missing in the triple
671 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
672 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000673 if (target_triple.getVendorName().size() == 0)
674 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000675 target_triple.setVendor (remote_triple.getVendor());
676
Greg Clayton2f085c62011-05-15 01:25:55 +0000677 if (target_triple.getOSName().size() == 0)
678 {
679 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000680
Greg Clayton2f085c62011-05-15 01:25:55 +0000681 if (target_triple.getEnvironmentName().size() == 0)
682 target_triple.setEnvironment (remote_triple.getEnvironment());
683 }
684 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000685 }
686 }
687 else
688 {
689 // The target doesn't have a valid architecture yet, set it from
690 // the architecture we got from the remote GDB server
691 target_arch = gdb_remote_arch;
692 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000693 }
Chris Lattner24943d22010-06-08 16:52:24 +0000694 }
695}
696
697void
698ProcessGDBRemote::DidLaunch ()
699{
700 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000701}
702
703Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000704ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000705{
706 Error error;
707 // Clear out and clean up from any current state
708 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000709 if (attach_pid != LLDB_INVALID_PROCESS_ID)
710 {
Greg Claytona2f74232011-02-24 22:24:29 +0000711 // Make sure we aren't already connected?
712 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000713 {
Greg Claytona2f74232011-02-24 22:24:29 +0000714 char host_port[128];
715 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
716 char connect_url[128];
717 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000718
Greg Claytonb72d0f02011-04-12 05:54:46 +0000719 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000720
721 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000722 {
Greg Claytona2f74232011-02-24 22:24:29 +0000723 const char *error_string = error.AsCString();
724 if (error_string == NULL)
725 error_string = "unable to launch " DEBUGSERVER_BASENAME;
726
727 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000728 }
Greg Claytona2f74232011-02-24 22:24:29 +0000729 else
730 {
731 error = ConnectToDebugserver (connect_url);
732 }
733 }
734
735 if (error.Success())
736 {
737 char packet[64];
738 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
739
740 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000741 }
742 }
Chris Lattner24943d22010-06-08 16:52:24 +0000743 return error;
744}
745
746size_t
747ProcessGDBRemote::AttachInputReaderCallback
748(
749 void *baton,
750 InputReader *reader,
751 lldb::InputReaderAction notification,
752 const char *bytes,
753 size_t bytes_len
754)
755{
756 if (notification == eInputReaderGotToken)
757 {
758 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
759 if (gdb_process->m_waiting_for_attach)
760 gdb_process->m_waiting_for_attach = false;
761 reader->SetIsDone(true);
762 return 1;
763 }
764 return 0;
765}
766
767Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000768ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000769{
770 Error error;
771 // Clear out and clean up from any current state
772 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000773
Chris Lattner24943d22010-06-08 16:52:24 +0000774 if (process_name && process_name[0])
775 {
Greg Claytona2f74232011-02-24 22:24:29 +0000776 // Make sure we aren't already connected?
777 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000778 {
Greg Claytona2f74232011-02-24 22:24:29 +0000779 char host_port[128];
780 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
781 char connect_url[128];
782 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
783
Greg Claytonb72d0f02011-04-12 05:54:46 +0000784 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000785 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000786 {
Greg Claytona2f74232011-02-24 22:24:29 +0000787 const char *error_string = error.AsCString();
788 if (error_string == NULL)
789 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000790
Greg Claytona2f74232011-02-24 22:24:29 +0000791 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000792 }
Greg Claytona2f74232011-02-24 22:24:29 +0000793 else
794 {
795 error = ConnectToDebugserver (connect_url);
796 }
797 }
798
799 if (error.Success())
800 {
801 StreamString packet;
802
803 if (wait_for_launch)
804 packet.PutCString("vAttachWait");
805 else
806 packet.PutCString("vAttachName");
807 packet.PutChar(';');
808 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
809
810 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
811
Chris Lattner24943d22010-06-08 16:52:24 +0000812 }
813 }
Chris Lattner24943d22010-06-08 16:52:24 +0000814 return error;
815}
816
Chris Lattner24943d22010-06-08 16:52:24 +0000817
818void
819ProcessGDBRemote::DidAttach ()
820{
Greg Claytone71e2582011-02-04 01:58:07 +0000821 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000822}
823
824Error
825ProcessGDBRemote::WillResume ()
826{
Greg Claytonc1f45872011-02-12 06:28:37 +0000827 m_continue_c_tids.clear();
828 m_continue_C_tids.clear();
829 m_continue_s_tids.clear();
830 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000831 return Error();
832}
833
834Error
835ProcessGDBRemote::DoResume ()
836{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000837 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000838 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
839 if (log)
840 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000841
842 Listener listener ("gdb-remote.resume-packet-sent");
843 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
844 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000845 StreamString continue_packet;
846 bool continue_packet_error = false;
847 if (m_gdb_comm.HasAnyVContSupport ())
848 {
849 continue_packet.PutCString ("vCont");
850
851 if (!m_continue_c_tids.empty())
852 {
853 if (m_gdb_comm.GetVContSupported ('c'))
854 {
855 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)
856 continue_packet.Printf(";c:%4.4x", *t_pos);
857 }
858 else
859 continue_packet_error = true;
860 }
861
862 if (!continue_packet_error && !m_continue_C_tids.empty())
863 {
864 if (m_gdb_comm.GetVContSupported ('C'))
865 {
866 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)
867 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
868 }
869 else
870 continue_packet_error = true;
871 }
Greg Claytonb749a262010-12-03 06:02:24 +0000872
Greg Claytonc1f45872011-02-12 06:28:37 +0000873 if (!continue_packet_error && !m_continue_s_tids.empty())
874 {
875 if (m_gdb_comm.GetVContSupported ('s'))
876 {
877 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)
878 continue_packet.Printf(";s:%4.4x", *t_pos);
879 }
880 else
881 continue_packet_error = true;
882 }
883
884 if (!continue_packet_error && !m_continue_S_tids.empty())
885 {
886 if (m_gdb_comm.GetVContSupported ('S'))
887 {
888 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)
889 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
890 }
891 else
892 continue_packet_error = true;
893 }
894
895 if (continue_packet_error)
896 continue_packet.GetString().clear();
897 }
898 else
899 continue_packet_error = true;
900
901 if (continue_packet_error)
902 {
903 continue_packet_error = false;
904 // Either no vCont support, or we tried to use part of the vCont
905 // packet that wasn't supported by the remote GDB server.
906 // We need to try and make a simple packet that can do our continue
907 const size_t num_threads = GetThreadList().GetSize();
908 const size_t num_continue_c_tids = m_continue_c_tids.size();
909 const size_t num_continue_C_tids = m_continue_C_tids.size();
910 const size_t num_continue_s_tids = m_continue_s_tids.size();
911 const size_t num_continue_S_tids = m_continue_S_tids.size();
912 if (num_continue_c_tids > 0)
913 {
914 if (num_continue_c_tids == num_threads)
915 {
916 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000917 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000918 continue_packet.PutChar ('c');
919 }
920 else if (num_continue_c_tids == 1 &&
921 num_continue_C_tids == 0 &&
922 num_continue_s_tids == 0 &&
923 num_continue_S_tids == 0 )
924 {
925 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000926 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000927 continue_packet.PutChar ('c');
928 }
929 else
930 {
931 // We can't represent this continue packet....
932 continue_packet_error = true;
933 }
934 }
935
936 if (!continue_packet_error && num_continue_C_tids > 0)
937 {
938 if (num_continue_C_tids == num_threads)
939 {
940 const int continue_signo = m_continue_C_tids.front().second;
941 if (num_continue_C_tids > 1)
942 {
943 for (size_t i=1; i<num_threads; ++i)
944 {
945 if (m_continue_C_tids[i].second != continue_signo)
946 continue_packet_error = true;
947 }
948 }
949 if (!continue_packet_error)
950 {
951 // Add threads continuing with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000952 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000953 continue_packet.Printf("C%2.2x", continue_signo);
954 }
955 }
956 else if (num_continue_c_tids == 0 &&
957 num_continue_C_tids == 1 &&
958 num_continue_s_tids == 0 &&
959 num_continue_S_tids == 0 )
960 {
961 // Only one thread is continuing with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +0000962 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000963 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
964 }
965 else
966 {
967 // We can't represent this continue packet....
968 continue_packet_error = true;
969 }
970 }
971
972 if (!continue_packet_error && num_continue_s_tids > 0)
973 {
974 if (num_continue_s_tids == num_threads)
975 {
976 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000977 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +0000978 continue_packet.PutChar ('s');
979 }
980 else if (num_continue_c_tids == 0 &&
981 num_continue_C_tids == 0 &&
982 num_continue_s_tids == 1 &&
983 num_continue_S_tids == 0 )
984 {
985 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +0000986 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000987 continue_packet.PutChar ('s');
988 }
989 else
990 {
991 // We can't represent this continue packet....
992 continue_packet_error = true;
993 }
994 }
995
996 if (!continue_packet_error && num_continue_S_tids > 0)
997 {
998 if (num_continue_S_tids == num_threads)
999 {
1000 const int step_signo = m_continue_S_tids.front().second;
1001 // Are all threads trying to step with the same signal?
1002 if (num_continue_S_tids > 1)
1003 {
1004 for (size_t i=1; i<num_threads; ++i)
1005 {
1006 if (m_continue_S_tids[i].second != step_signo)
1007 continue_packet_error = true;
1008 }
1009 }
1010 if (!continue_packet_error)
1011 {
1012 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001013 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001014 continue_packet.Printf("S%2.2x", step_signo);
1015 }
1016 }
1017 else if (num_continue_c_tids == 0 &&
1018 num_continue_C_tids == 0 &&
1019 num_continue_s_tids == 0 &&
1020 num_continue_S_tids == 1 )
1021 {
1022 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001023 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001024 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1025 }
1026 else
1027 {
1028 // We can't represent this continue packet....
1029 continue_packet_error = true;
1030 }
1031 }
1032 }
1033
1034 if (continue_packet_error)
1035 {
1036 error.SetErrorString ("can't make continue packet for this resume");
1037 }
1038 else
1039 {
1040 EventSP event_sp;
1041 TimeValue timeout;
1042 timeout = TimeValue::Now();
1043 timeout.OffsetWithSeconds (5);
1044 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1045
1046 if (listener.WaitForEvent (&timeout, event_sp) == false)
1047 error.SetErrorString("Resume timed out.");
1048 }
Greg Claytonb749a262010-12-03 06:02:24 +00001049 }
1050
Jim Ingham3ae449a2010-11-17 02:32:00 +00001051 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001052}
1053
Chris Lattner24943d22010-06-08 16:52:24 +00001054uint32_t
1055ProcessGDBRemote::UpdateThreadListIfNeeded ()
1056{
1057 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001058 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001059 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001060 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1061
Greg Clayton5205f0b2010-09-03 17:10:42 +00001062 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001063 const uint32_t stop_id = GetStopID();
1064 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1065 {
1066 // Update the thread list's stop id immediately so we don't recurse into this function.
1067 ThreadList curr_thread_list (this);
1068 curr_thread_list.SetStopID(stop_id);
1069
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001070 std::vector<lldb::tid_t> thread_ids;
1071 bool sequence_mutex_unavailable = false;
1072 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1073 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001074 {
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001075 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001076 {
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001077 tid_t tid = thread_ids[i];
1078 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
1079 if (!thread_sp)
1080 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1081 curr_thread_list.AddThread(thread_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001082 }
1083 }
1084
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001085 if (sequence_mutex_unavailable == false)
1086 {
1087 m_thread_list = curr_thread_list;
1088 SetThreadStopInfo (m_last_stop_packet);
1089 }
Chris Lattner24943d22010-06-08 16:52:24 +00001090 }
1091 return GetThreadList().GetSize(false);
1092}
1093
1094
1095StateType
1096ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1097{
Greg Clayton261a18b2011-06-02 22:22:38 +00001098 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001099 const char stop_type = stop_packet.GetChar();
1100 switch (stop_type)
1101 {
1102 case 'T':
1103 case 'S':
1104 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001105 if (GetStopID() == 0)
1106 {
1107 // Our first stop, make sure we have a process ID, and also make
1108 // sure we know about our registers
1109 if (GetID() == LLDB_INVALID_PROCESS_ID)
1110 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001111 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001112 if (pid != LLDB_INVALID_PROCESS_ID)
1113 SetID (pid);
1114 }
1115 BuildDynamicRegisterInfo (true);
1116 }
Chris Lattner24943d22010-06-08 16:52:24 +00001117 // Stop with signal and thread info
1118 const uint8_t signo = stop_packet.GetHexU8();
1119 std::string name;
1120 std::string value;
1121 std::string thread_name;
1122 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001123 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001124 uint32_t tid = LLDB_INVALID_THREAD_ID;
1125 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1126 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001127 ThreadSP thread_sp;
1128
Chris Lattner24943d22010-06-08 16:52:24 +00001129 while (stop_packet.GetNameColonValue(name, value))
1130 {
1131 if (name.compare("metype") == 0)
1132 {
1133 // exception type in big endian hex
1134 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1135 }
1136 else if (name.compare("mecount") == 0)
1137 {
1138 // exception count in big endian hex
1139 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1140 }
1141 else if (name.compare("medata") == 0)
1142 {
1143 // exception data in big endian hex
1144 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1145 }
1146 else if (name.compare("thread") == 0)
1147 {
1148 // thread in big endian hex
1149 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001150 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001151 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001152 if (!thread_sp)
1153 {
1154 // Create the thread if we need to
1155 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1156 m_thread_list.AddThread(thread_sp);
1157 }
Chris Lattner24943d22010-06-08 16:52:24 +00001158 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001159 else if (name.compare("hexname") == 0)
1160 {
1161 StringExtractor name_extractor;
1162 // Swap "value" over into "name_extractor"
1163 name_extractor.GetStringRef().swap(value);
1164 // Now convert the HEX bytes into a string value
1165 name_extractor.GetHexByteString (value);
1166 thread_name.swap (value);
1167 }
Chris Lattner24943d22010-06-08 16:52:24 +00001168 else if (name.compare("name") == 0)
1169 {
1170 thread_name.swap (value);
1171 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001172 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001173 {
1174 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1175 }
Greg Claytona875b642011-01-09 21:07:35 +00001176 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1177 {
1178 // We have a register number that contains an expedited
1179 // register value. Lets supply this register to our thread
1180 // so it won't have to go and read it.
1181 if (thread_sp)
1182 {
1183 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1184
1185 if (reg != UINT32_MAX)
1186 {
1187 StringExtractor reg_value_extractor;
1188 // Swap "value" over into "reg_value_extractor"
1189 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001190 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1191 {
1192 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1193 name.c_str(),
1194 reg,
1195 reg,
1196 reg_value_extractor.GetStringRef().c_str(),
1197 stop_packet.GetStringRef().c_str());
1198 }
Greg Claytona875b642011-01-09 21:07:35 +00001199 }
1200 }
1201 }
Chris Lattner24943d22010-06-08 16:52:24 +00001202 }
Chris Lattner24943d22010-06-08 16:52:24 +00001203
1204 if (thread_sp)
1205 {
1206 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1207
1208 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001209 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001210 if (exc_type != 0)
1211 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001212 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001213
1214 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1215 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001216 exc_data_size,
1217 exc_data_size >= 1 ? exc_data[0] : 0,
1218 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001219 }
1220 else if (signo)
1221 {
Greg Clayton643ee732010-08-04 01:40:35 +00001222 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001223 }
1224 else
1225 {
Greg Clayton643ee732010-08-04 01:40:35 +00001226 StopInfoSP invalid_stop_info_sp;
1227 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001228 }
1229 }
1230 return eStateStopped;
1231 }
1232 break;
1233
1234 case 'W':
1235 // process exited
1236 return eStateExited;
1237
1238 default:
1239 break;
1240 }
1241 return eStateInvalid;
1242}
1243
1244void
1245ProcessGDBRemote::RefreshStateAfterStop ()
1246{
Chris Lattner24943d22010-06-08 16:52:24 +00001247 // Let all threads recover from stopping and do any clean up based
1248 // on the previous thread state (if any).
1249 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001250 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001251}
1252
1253Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001254ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001255{
1256 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001257
Greg Claytona4881d02011-01-22 07:12:45 +00001258 bool timed_out = false;
1259 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001260
1261 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001262 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001263 // We are being asked to halt during an attach. We need to just close
1264 // our file handle and debugserver will go away, and we can be done...
1265 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001266 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001267 else
1268 {
1269 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1270 {
1271 if (timed_out)
1272 error.SetErrorString("timed out sending interrupt packet");
1273 else
1274 error.SetErrorString("unknown error sending interrupt packet");
1275 }
1276 }
Chris Lattner24943d22010-06-08 16:52:24 +00001277 return error;
1278}
1279
1280Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001281ProcessGDBRemote::InterruptIfRunning
1282(
1283 bool discard_thread_plans,
1284 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001285 EventSP &stop_event_sp
1286)
Chris Lattner24943d22010-06-08 16:52:24 +00001287{
1288 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001289
Greg Clayton2860ba92011-01-23 19:58:49 +00001290 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1291
Greg Clayton68ca8232011-01-25 02:58:48 +00001292 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001293 const bool is_running = m_gdb_comm.IsRunning();
1294 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001295 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001296 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001297 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001298 is_running);
1299
Greg Clayton2860ba92011-01-23 19:58:49 +00001300 if (discard_thread_plans)
1301 {
1302 if (log)
1303 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1304 m_thread_list.DiscardThreadPlans();
1305 }
1306 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001307 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001308 if (catch_stop_event)
1309 {
1310 if (log)
1311 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1312 PausePrivateStateThread();
1313 paused_private_state_thread = true;
1314 }
1315
Greg Clayton4fb400f2010-09-27 21:07:38 +00001316 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001317 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001318 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001319
Greg Clayton72e1c782011-01-22 23:43:18 +00001320 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001321 {
1322 if (timed_out)
1323 error.SetErrorString("timed out sending interrupt packet");
1324 else
1325 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001326 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001327 ResumePrivateStateThread();
1328 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001329 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001330
Greg Clayton72e1c782011-01-22 23:43:18 +00001331 if (catch_stop_event)
1332 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001333 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001334 TimeValue timeout_time;
1335 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001336 timeout_time.OffsetWithSeconds(5);
1337 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001338
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001339 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001340 if (log)
1341 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001342
Greg Clayton2860ba92011-01-23 19:58:49 +00001343 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001344 error.SetErrorString("unable to verify target stopped");
1345 }
1346
Greg Clayton68ca8232011-01-25 02:58:48 +00001347 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001348 {
1349 if (log)
1350 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001351 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001352 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001353 }
Chris Lattner24943d22010-06-08 16:52:24 +00001354 return error;
1355}
1356
Greg Clayton4fb400f2010-09-27 21:07:38 +00001357Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001358ProcessGDBRemote::WillDetach ()
1359{
Greg Clayton2860ba92011-01-23 19:58:49 +00001360 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1361 if (log)
1362 log->Printf ("ProcessGDBRemote::WillDetach()");
1363
Greg Clayton72e1c782011-01-22 23:43:18 +00001364 bool discard_thread_plans = true;
1365 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001366 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001367 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001368}
1369
1370Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001371ProcessGDBRemote::DoDetach()
1372{
1373 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001374 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001375 if (log)
1376 log->Printf ("ProcessGDBRemote::DoDetach()");
1377
1378 DisableAllBreakpointSites ();
1379
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001380 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001381
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001382 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1383 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001384 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001385 if (response_size)
1386 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1387 else
1388 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001389 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001390 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001391 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001392
Greg Clayton4fb400f2010-09-27 21:07:38 +00001393 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001394 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001395
1396 SetPrivateState (eStateDetached);
1397 ResumePrivateStateThread();
1398
1399 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001400 return error;
1401}
Chris Lattner24943d22010-06-08 16:52:24 +00001402
1403Error
1404ProcessGDBRemote::DoDestroy ()
1405{
1406 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001407 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001408 if (log)
1409 log->Printf ("ProcessGDBRemote::DoDestroy()");
1410
1411 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001412 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001413 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001414 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001415 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001416 // We are being asked to halt during an attach. We need to just close
1417 // our file handle and debugserver will go away, and we can be done...
1418 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001419 }
1420 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001421 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001422
1423 StringExtractorGDBRemote response;
1424 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001425 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001426 {
1427 char packet_cmd = response.GetChar(0);
1428
1429 if (packet_cmd == 'W' || packet_cmd == 'X')
1430 {
1431 m_last_stop_packet = response;
1432 SetExitStatus(response.GetHexU8(), NULL);
1433 }
1434 }
1435 else
1436 {
1437 SetExitStatus(SIGABRT, NULL);
1438 //error.SetErrorString("kill packet failed");
1439 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001440 }
1441 }
Chris Lattner24943d22010-06-08 16:52:24 +00001442 StopAsyncThread ();
1443 m_gdb_comm.StopReadThread();
1444 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001445 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001446 return error;
1447}
1448
Chris Lattner24943d22010-06-08 16:52:24 +00001449//------------------------------------------------------------------
1450// Process Queries
1451//------------------------------------------------------------------
1452
1453bool
1454ProcessGDBRemote::IsAlive ()
1455{
Greg Clayton58e844b2010-12-08 05:08:21 +00001456 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001457}
1458
1459addr_t
1460ProcessGDBRemote::GetImageInfoAddress()
1461{
1462 if (!m_gdb_comm.IsRunning())
1463 {
1464 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001465 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001466 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001467 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001468 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1469 }
1470 }
1471 return LLDB_INVALID_ADDRESS;
1472}
1473
Chris Lattner24943d22010-06-08 16:52:24 +00001474//------------------------------------------------------------------
1475// Process Memory
1476//------------------------------------------------------------------
1477size_t
1478ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1479{
1480 if (size > m_max_memory_size)
1481 {
1482 // Keep memory read sizes down to a sane limit. This function will be
1483 // called multiple times in order to complete the task by
1484 // lldb_private::Process so it is ok to do this.
1485 size = m_max_memory_size;
1486 }
1487
1488 char packet[64];
1489 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1490 assert (packet_len + 1 < sizeof(packet));
1491 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001492 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001493 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001494 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001495 {
1496 error.Clear();
1497 return response.GetHexBytes(buf, size, '\xdd');
1498 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001499 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001500 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001501 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001502 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1503 else
1504 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1505 }
1506 else
1507 {
1508 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1509 }
1510 return 0;
1511}
1512
1513size_t
1514ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1515{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001516 if (size > m_max_memory_size)
1517 {
1518 // Keep memory read sizes down to a sane limit. This function will be
1519 // called multiple times in order to complete the task by
1520 // lldb_private::Process so it is ok to do this.
1521 size = m_max_memory_size;
1522 }
1523
Chris Lattner24943d22010-06-08 16:52:24 +00001524 StreamString packet;
1525 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001526 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001527 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001528 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001529 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001530 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001531 {
1532 error.Clear();
1533 return size;
1534 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001535 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001536 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001537 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001538 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1539 else
1540 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1541 }
1542 else
1543 {
1544 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1545 }
1546 return 0;
1547}
1548
1549lldb::addr_t
1550ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1551{
Greg Clayton989816b2011-05-14 01:50:35 +00001552 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1553
Greg Clayton2f085c62011-05-15 01:25:55 +00001554 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001555 switch (supported)
1556 {
1557 case eLazyBoolCalculate:
1558 case eLazyBoolYes:
1559 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1560 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1561 return allocated_addr;
1562
1563 case eLazyBoolNo:
1564 // Call mmap() to create executable memory in the inferior..
1565 {
1566 Thread *thread = GetThreadList().GetSelectedThread().get();
1567 if (thread == NULL)
1568 thread = GetThreadList().GetThreadAtIndex(0).get();
1569
1570 const bool append = true;
1571 const bool include_symbols = true;
1572 SymbolContextList sc_list;
1573 const uint32_t count = m_target.GetImages().FindFunctions (ConstString ("mmap"),
1574 eFunctionNameTypeFull,
1575 include_symbols,
1576 append,
1577 sc_list);
1578 if (count > 0)
1579 {
1580 SymbolContext sc;
1581 if (sc_list.GetContextAtIndex(0, sc))
1582 {
1583 const uint32_t range_scope = eSymbolContextFunction | eSymbolContextSymbol;
1584 const bool use_inline_block_range = false;
1585 const bool stop_other_threads = true;
1586 const bool discard_on_error = true;
1587 const bool try_all_threads = true;
1588 const uint32_t single_thread_timeout_usec = 500000;
1589 addr_t arg1_addr = 0;
1590 addr_t arg2_len = size;
1591 addr_t arg3_prot = PROT_NONE;
Greg Clayton30581972011-05-17 03:51:29 +00001592 addr_t arg4_flags = MAP_ANON | MAP_PRIVATE;
Greg Clayton989816b2011-05-14 01:50:35 +00001593 addr_t arg5_fd = -1;
1594 addr_t arg6_offset = 0;
1595 if (permissions & lldb::ePermissionsReadable)
1596 arg3_prot |= PROT_READ;
1597 if (permissions & lldb::ePermissionsWritable)
1598 arg3_prot |= PROT_WRITE;
1599 if (permissions & lldb::ePermissionsExecutable)
1600 arg3_prot |= PROT_EXEC;
1601
1602 AddressRange mmap_range;
1603 if (sc.GetAddressRange(range_scope, 0, use_inline_block_range, mmap_range))
1604 {
Greg Clayton2f085c62011-05-15 01:25:55 +00001605 ThreadPlanCallFunction *call_function_thread_plan = new ThreadPlanCallFunction (*thread,
1606 mmap_range.GetBaseAddress(),
1607 stop_other_threads,
1608 discard_on_error,
1609 &arg1_addr,
1610 &arg2_len,
1611 &arg3_prot,
1612 &arg4_flags,
1613 &arg5_fd,
1614 &arg6_offset);
1615 lldb::ThreadPlanSP call_plan_sp (call_function_thread_plan);
Greg Clayton989816b2011-05-14 01:50:35 +00001616 if (call_plan_sp)
1617 {
Greg Clayton2f085c62011-05-15 01:25:55 +00001618 ValueSP return_value_sp (new Value);
1619 ClangASTContext *clang_ast_context = m_target.GetScratchClangASTContext();
1620 lldb::clang_type_t clang_void_ptr_type = clang_ast_context->GetVoidPtrType(false);
1621 return_value_sp->SetValueType (Value::eValueTypeScalar);
1622 return_value_sp->SetContext (Value::eContextTypeClangType, clang_void_ptr_type);
1623 call_function_thread_plan->RequestReturnValue (return_value_sp);
1624
Greg Clayton989816b2011-05-14 01:50:35 +00001625 StreamFile error_strm;
1626 StackFrame *frame = thread->GetStackFrameAtIndex (0).get();
1627 if (frame)
1628 {
1629 ExecutionContext exe_ctx;
1630 frame->CalculateExecutionContext (exe_ctx);
Greg Clayton2f085c62011-05-15 01:25:55 +00001631 ExecutionResults result = RunThreadPlan (exe_ctx,
1632 call_plan_sp,
1633 stop_other_threads,
1634 try_all_threads,
1635 discard_on_error,
1636 single_thread_timeout_usec,
1637 error_strm);
1638 if (result == eExecutionCompleted)
1639 {
1640 allocated_addr = return_value_sp->GetScalar().ULongLong();
Greg Clayton9d2b3212011-05-15 23:56:52 +00001641 if (GetAddressByteSize() == 4)
1642 {
1643 if (allocated_addr == UINT32_MAX)
1644 allocated_addr = LLDB_INVALID_ADDRESS;
1645 }
1646 if (allocated_addr != LLDB_INVALID_ADDRESS)
1647 m_addr_to_mmap_size[allocated_addr] = size;
Greg Clayton2f085c62011-05-15 01:25:55 +00001648 }
Greg Clayton989816b2011-05-14 01:50:35 +00001649 }
1650 }
1651 }
1652 }
1653 }
1654 }
1655 break;
1656 }
1657
Chris Lattner24943d22010-06-08 16:52:24 +00001658 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001659 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001660 else
1661 error.Clear();
1662 return allocated_addr;
1663}
1664
1665Error
1666ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1667{
1668 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001669 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1670
1671 switch (supported)
1672 {
1673 case eLazyBoolCalculate:
1674 // We should never be deallocating memory without allocating memory
1675 // first so we should never get eLazyBoolCalculate
1676 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1677 break;
1678
1679 case eLazyBoolYes:
1680 if (!m_gdb_comm.DeallocateMemory (addr))
1681 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1682 break;
1683
1684 case eLazyBoolNo:
1685 // Call munmap() to create executable memory in the inferior..
1686 {
1687 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
1688 if (pos != m_addr_to_mmap_size.end())
1689 {
1690 Thread *thread = GetThreadList().GetSelectedThread().get();
1691 if (thread == NULL)
1692 thread = GetThreadList().GetThreadAtIndex(0).get();
1693
1694 const bool append = true;
1695 const bool include_symbols = true;
1696 SymbolContextList sc_list;
1697 const uint32_t count = m_target.GetImages().FindFunctions (ConstString ("munmap"),
1698 eFunctionNameTypeFull,
1699 include_symbols,
1700 append,
1701 sc_list);
1702 if (count > 0)
1703 {
1704 SymbolContext sc;
1705 if (sc_list.GetContextAtIndex(0, sc))
1706 {
1707 const uint32_t range_scope = eSymbolContextFunction | eSymbolContextSymbol;
1708 const bool use_inline_block_range = false;
1709 const bool stop_other_threads = true;
1710 const bool discard_on_error = true;
1711 const bool try_all_threads = true;
1712 const uint32_t single_thread_timeout_usec = 500000;
1713 addr_t arg1_addr = addr;
1714 addr_t arg2_len = pos->second;
1715
1716 AddressRange munmap_range;
1717 if (sc.GetAddressRange(range_scope, 0, use_inline_block_range, munmap_range))
1718 {
1719 lldb::ThreadPlanSP call_plan_sp (new ThreadPlanCallFunction (*thread,
1720 munmap_range.GetBaseAddress(),
1721 stop_other_threads,
1722 discard_on_error,
1723 &arg1_addr,
1724 &arg2_len));
1725 if (call_plan_sp)
1726 {
1727 StreamFile error_strm;
1728 StackFrame *frame = thread->GetStackFrameAtIndex (0).get();
1729 if (frame)
1730 {
1731 ExecutionContext exe_ctx;
1732 frame->CalculateExecutionContext (exe_ctx);
1733 ExecutionResults result = RunThreadPlan (exe_ctx,
1734 call_plan_sp,
1735 stop_other_threads,
1736 try_all_threads,
1737 discard_on_error,
1738 single_thread_timeout_usec,
1739 error_strm);
1740 if (result == eExecutionCompleted)
1741 {
1742 m_addr_to_mmap_size.erase (pos);
1743 }
1744 }
1745 }
1746 }
1747 }
1748 }
1749 }
1750 }
1751 break;
1752 }
1753
Chris Lattner24943d22010-06-08 16:52:24 +00001754 return error;
1755}
1756
1757
1758//------------------------------------------------------------------
1759// Process STDIO
1760//------------------------------------------------------------------
1761
1762size_t
1763ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1764{
1765 Mutex::Locker locker(m_stdio_mutex);
1766 size_t bytes_available = m_stdout_data.size();
1767 if (bytes_available > 0)
1768 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001769 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1770 if (log)
1771 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001772 if (bytes_available > buf_size)
1773 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001774 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001775 m_stdout_data.erase(0, buf_size);
1776 bytes_available = buf_size;
1777 }
1778 else
1779 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001780 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001781 m_stdout_data.clear();
1782
1783 //ResetEventBits(eBroadcastBitSTDOUT);
1784 }
1785 }
1786 return bytes_available;
1787}
1788
1789size_t
1790ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1791{
1792 // Can we get STDERR through the remote protocol?
1793 return 0;
1794}
1795
1796size_t
1797ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1798{
1799 if (m_stdio_communication.IsConnected())
1800 {
1801 ConnectionStatus status;
1802 m_stdio_communication.Write(src, src_len, status, NULL);
1803 }
1804 return 0;
1805}
1806
1807Error
1808ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1809{
1810 Error error;
1811 assert (bp_site != NULL);
1812
Greg Claytone005f2c2010-11-06 01:53:30 +00001813 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001814 user_id_t site_id = bp_site->GetID();
1815 const addr_t addr = bp_site->GetLoadAddress();
1816 if (log)
1817 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1818
1819 if (bp_site->IsEnabled())
1820 {
1821 if (log)
1822 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1823 return error;
1824 }
1825 else
1826 {
1827 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1828
1829 if (bp_site->HardwarePreferred())
1830 {
1831 // Try and set hardware breakpoint, and if that fails, fall through
1832 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001833 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001834 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001835 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001836 {
1837 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001838 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001839 return error;
1840 }
Chris Lattner24943d22010-06-08 16:52:24 +00001841 }
1842 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001843
1844 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001845 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001846 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1847 {
1848 bp_site->SetEnabled(true);
1849 bp_site->SetType (BreakpointSite::eExternal);
1850 return error;
1851 }
Chris Lattner24943d22010-06-08 16:52:24 +00001852 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001853
1854 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001855 }
1856
1857 if (log)
1858 {
1859 const char *err_string = error.AsCString();
1860 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1861 bp_site->GetLoadAddress(),
1862 err_string ? err_string : "NULL");
1863 }
1864 // We shouldn't reach here on a successful breakpoint enable...
1865 if (error.Success())
1866 error.SetErrorToGenericError();
1867 return error;
1868}
1869
1870Error
1871ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1872{
1873 Error error;
1874 assert (bp_site != NULL);
1875 addr_t addr = bp_site->GetLoadAddress();
1876 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001877 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001878 if (log)
1879 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1880
1881 if (bp_site->IsEnabled())
1882 {
1883 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1884
Greg Claytonb72d0f02011-04-12 05:54:46 +00001885 BreakpointSite::Type bp_type = bp_site->GetType();
1886 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001887 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001888 case BreakpointSite::eSoftware:
1889 error = DisableSoftwareBreakpoint (bp_site);
1890 break;
1891
1892 case BreakpointSite::eHardware:
1893 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1894 error.SetErrorToGenericError();
1895 break;
1896
1897 case BreakpointSite::eExternal:
1898 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1899 error.SetErrorToGenericError();
1900 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001901 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001902 if (error.Success())
1903 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001904 }
1905 else
1906 {
1907 if (log)
1908 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1909 return error;
1910 }
1911
1912 if (error.Success())
1913 error.SetErrorToGenericError();
1914 return error;
1915}
1916
1917Error
1918ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1919{
1920 Error error;
1921 if (wp)
1922 {
1923 user_id_t watchID = wp->GetID();
1924 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001925 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001926 if (log)
1927 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1928 if (wp->IsEnabled())
1929 {
1930 if (log)
1931 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1932 return error;
1933 }
1934 else
1935 {
1936 // Pass down an appropriate z/Z packet...
1937 error.SetErrorString("watchpoints not supported");
1938 }
1939 }
1940 else
1941 {
1942 error.SetErrorString("Watchpoint location argument was NULL.");
1943 }
1944 if (error.Success())
1945 error.SetErrorToGenericError();
1946 return error;
1947}
1948
1949Error
1950ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1951{
1952 Error error;
1953 if (wp)
1954 {
1955 user_id_t watchID = wp->GetID();
1956
Greg Claytone005f2c2010-11-06 01:53:30 +00001957 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001958
1959 addr_t addr = wp->GetLoadAddress();
1960 if (log)
1961 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1962
1963 if (wp->IsHardware())
1964 {
1965 // Pass down an appropriate z/Z packet...
1966 error.SetErrorString("watchpoints not supported");
1967 }
1968 // TODO: clear software watchpoints if we implement them
1969 }
1970 else
1971 {
1972 error.SetErrorString("Watchpoint location argument was NULL.");
1973 }
1974 if (error.Success())
1975 error.SetErrorToGenericError();
1976 return error;
1977}
1978
1979void
1980ProcessGDBRemote::Clear()
1981{
1982 m_flags = 0;
1983 m_thread_list.Clear();
1984 {
1985 Mutex::Locker locker(m_stdio_mutex);
1986 m_stdout_data.clear();
1987 }
Chris Lattner24943d22010-06-08 16:52:24 +00001988}
1989
1990Error
1991ProcessGDBRemote::DoSignal (int signo)
1992{
1993 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001994 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001995 if (log)
1996 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1997
1998 if (!m_gdb_comm.SendAsyncSignal (signo))
1999 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2000 return error;
2001}
2002
Chris Lattner24943d22010-06-08 16:52:24 +00002003Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002004ProcessGDBRemote::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 +00002005{
2006 Error error;
2007 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2008 {
2009 // If we locate debugserver, keep that located version around
2010 static FileSpec g_debugserver_file_spec;
2011
Greg Claytonb72d0f02011-04-12 05:54:46 +00002012 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002013 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002014 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002015
2016 // Always check to see if we have an environment override for the path
2017 // to the debugserver to use and use it if we do.
2018 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2019 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002020 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002021 else
2022 debugserver_file_spec = g_debugserver_file_spec;
2023 bool debugserver_exists = debugserver_file_spec.Exists();
2024 if (!debugserver_exists)
2025 {
2026 // The debugserver binary is in the LLDB.framework/Resources
2027 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002028 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002029 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002030 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002031 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002032 if (debugserver_exists)
2033 {
2034 g_debugserver_file_spec = debugserver_file_spec;
2035 }
2036 else
2037 {
2038 g_debugserver_file_spec.Clear();
2039 debugserver_file_spec.Clear();
2040 }
Chris Lattner24943d22010-06-08 16:52:24 +00002041 }
2042 }
2043
2044 if (debugserver_exists)
2045 {
2046 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2047
2048 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002049
Greg Claytone005f2c2010-11-06 01:53:30 +00002050 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002051
Greg Claytonb72d0f02011-04-12 05:54:46 +00002052 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002053 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002054
Chris Lattner24943d22010-06-08 16:52:24 +00002055 // Start args with "debugserver /file/path -r --"
2056 debugserver_args.AppendArgument(debugserver_path);
2057 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002058 // use native registers, not the GDB registers
2059 debugserver_args.AppendArgument("--native-regs");
2060 // make debugserver run in its own session so signals generated by
2061 // special terminal key sequences (^C) don't affect debugserver
2062 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002063
Chris Lattner24943d22010-06-08 16:52:24 +00002064 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2065 if (env_debugserver_log_file)
2066 {
2067 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2068 debugserver_args.AppendArgument(arg_cstr);
2069 }
2070
2071 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2072 if (env_debugserver_log_flags)
2073 {
2074 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2075 debugserver_args.AppendArgument(arg_cstr);
2076 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002077// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002078// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002079
Greg Claytonb72d0f02011-04-12 05:54:46 +00002080 // We currently send down all arguments, attach pids, or attach
2081 // process names in dedicated GDB server packets, so we don't need
2082 // to pass them as arguments. This is currently because of all the
2083 // things we need to setup prior to launching: the environment,
2084 // current working dir, file actions, etc.
2085#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002086 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002087 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002088 {
Greg Claytona2f74232011-02-24 22:24:29 +00002089 // Terminate the debugserver args so we can now append the inferior args
2090 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002091
Greg Claytona2f74232011-02-24 22:24:29 +00002092 for (int i = 0; inferior_argv[i] != NULL; ++i)
2093 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002094 }
2095 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2096 {
2097 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2098 debugserver_args.AppendArgument (arg_cstr);
2099 }
2100 else if (attach_name && attach_name[0])
2101 {
2102 if (wait_for_launch)
2103 debugserver_args.AppendArgument ("--waitfor");
2104 else
2105 debugserver_args.AppendArgument ("--attach");
2106 debugserver_args.AppendArgument (attach_name);
2107 }
Chris Lattner24943d22010-06-08 16:52:24 +00002108#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002109
2110 ProcessLaunchInfo::FileAction file_action;
2111
2112 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2113 // to "/dev/null" if we run into any problems.
2114 file_action.Close (STDIN_FILENO);
2115 launch_info.AppendFileAction (file_action);
2116 file_action.Close (STDOUT_FILENO);
2117 launch_info.AppendFileAction (file_action);
2118 file_action.Close (STDERR_FILENO);
2119 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002120
2121 if (log)
2122 {
2123 StreamString strm;
2124 debugserver_args.Dump (&strm);
2125 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2126 }
2127
Greg Claytonb72d0f02011-04-12 05:54:46 +00002128 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002129
Greg Claytonb72d0f02011-04-12 05:54:46 +00002130 if (error.Success ())
2131 m_debugserver_pid = launch_info.GetProcessID();
2132 else
Chris Lattner24943d22010-06-08 16:52:24 +00002133 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2134
2135 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002136 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002137 }
2138 else
2139 {
2140 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2141 }
2142
2143 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2144 StartAsyncThread ();
2145 }
2146 return error;
2147}
2148
2149bool
2150ProcessGDBRemote::MonitorDebugserverProcess
2151(
2152 void *callback_baton,
2153 lldb::pid_t debugserver_pid,
2154 int signo, // Zero for no signal
2155 int exit_status // Exit value of process if signal is zero
2156)
2157{
2158 // We pass in the ProcessGDBRemote inferior process it and name it
2159 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2160 // pointer value itself, thus we need the double cast...
2161
2162 // "debugserver_pid" argument passed in is the process ID for
2163 // debugserver that we are tracking...
2164
Greg Clayton75ccf502010-08-21 02:22:51 +00002165 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002166
2167 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2168 if (log)
2169 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2170
Greg Clayton75ccf502010-08-21 02:22:51 +00002171 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002172 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002173 // Sleep for a half a second to make sure our inferior process has
2174 // time to set its exit status before we set it incorrectly when
2175 // both the debugserver and the inferior process shut down.
2176 usleep (500000);
2177 // If our process hasn't yet exited, debugserver might have died.
2178 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002179 const StateType state = process->GetState();
2180
2181 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2182 state != eStateInvalid &&
2183 state != eStateUnloaded &&
2184 state != eStateExited &&
2185 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002186 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002187 char error_str[1024];
2188 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002189 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002190 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2191 if (signal_cstr)
2192 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002193 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002194 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002195 }
2196 else
2197 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002198 ::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 +00002199 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002200
2201 process->SetExitStatus (-1, error_str);
2202 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002203 // Debugserver has exited we need to let our ProcessGDBRemote
2204 // know that it no longer has a debugserver instance
2205 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2206 // We are returning true to this function below, so we can
2207 // forget about the monitor handle.
2208 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002209 }
2210 return true;
2211}
2212
2213void
2214ProcessGDBRemote::KillDebugserverProcess ()
2215{
2216 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2217 {
2218 ::kill (m_debugserver_pid, SIGINT);
2219 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2220 }
2221}
2222
2223void
2224ProcessGDBRemote::Initialize()
2225{
2226 static bool g_initialized = false;
2227
2228 if (g_initialized == false)
2229 {
2230 g_initialized = true;
2231 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2232 GetPluginDescriptionStatic(),
2233 CreateInstance);
2234
2235 Log::Callbacks log_callbacks = {
2236 ProcessGDBRemoteLog::DisableLog,
2237 ProcessGDBRemoteLog::EnableLog,
2238 ProcessGDBRemoteLog::ListLogCategories
2239 };
2240
2241 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2242 }
2243}
2244
2245bool
Chris Lattner24943d22010-06-08 16:52:24 +00002246ProcessGDBRemote::StartAsyncThread ()
2247{
Greg Claytone005f2c2010-11-06 01:53:30 +00002248 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002249
2250 if (log)
2251 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2252
2253 // Create a thread that watches our internal state and controls which
2254 // events make it to clients (into the DCProcess event queue).
2255 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002256 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002257}
2258
2259void
2260ProcessGDBRemote::StopAsyncThread ()
2261{
Greg Claytone005f2c2010-11-06 01:53:30 +00002262 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002263
2264 if (log)
2265 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2266
2267 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2268
2269 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002270 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002271 {
2272 Host::ThreadJoin (m_async_thread, NULL, NULL);
2273 }
2274}
2275
2276
2277void *
2278ProcessGDBRemote::AsyncThread (void *arg)
2279{
2280 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2281
Greg Claytone005f2c2010-11-06 01:53:30 +00002282 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002283 if (log)
2284 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2285
2286 Listener listener ("ProcessGDBRemote::AsyncThread");
2287 EventSP event_sp;
2288 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2289 eBroadcastBitAsyncThreadShouldExit;
2290
2291 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2292 {
Greg Claytona2f74232011-02-24 22:24:29 +00002293 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2294
Chris Lattner24943d22010-06-08 16:52:24 +00002295 bool done = false;
2296 while (!done)
2297 {
2298 if (log)
2299 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2300 if (listener.WaitForEvent (NULL, event_sp))
2301 {
2302 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002303 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002304 {
Greg Claytona2f74232011-02-24 22:24:29 +00002305 if (log)
2306 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 +00002307
Greg Claytona2f74232011-02-24 22:24:29 +00002308 switch (event_type)
2309 {
2310 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002311 {
Greg Claytona2f74232011-02-24 22:24:29 +00002312 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002313
Greg Claytona2f74232011-02-24 22:24:29 +00002314 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002315 {
Greg Claytona2f74232011-02-24 22:24:29 +00002316 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2317 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2318 if (log)
2319 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002320
Greg Claytona2f74232011-02-24 22:24:29 +00002321 if (::strstr (continue_cstr, "vAttach") == NULL)
2322 process->SetPrivateState(eStateRunning);
2323 StringExtractorGDBRemote response;
2324 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002325
Greg Claytona2f74232011-02-24 22:24:29 +00002326 switch (stop_state)
2327 {
2328 case eStateStopped:
2329 case eStateCrashed:
2330 case eStateSuspended:
2331 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002332 process->SetPrivateState (stop_state);
2333 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002334
Greg Claytona2f74232011-02-24 22:24:29 +00002335 case eStateExited:
2336 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002337 response.SetFilePos(1);
2338 process->SetExitStatus(response.GetHexU8(), NULL);
2339 done = true;
2340 break;
2341
2342 case eStateInvalid:
2343 process->SetExitStatus(-1, "lost connection");
2344 break;
2345
2346 default:
2347 process->SetPrivateState (stop_state);
2348 break;
2349 }
Chris Lattner24943d22010-06-08 16:52:24 +00002350 }
2351 }
Greg Claytona2f74232011-02-24 22:24:29 +00002352 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002353
Greg Claytona2f74232011-02-24 22:24:29 +00002354 case eBroadcastBitAsyncThreadShouldExit:
2355 if (log)
2356 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2357 done = true;
2358 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002359
Greg Claytona2f74232011-02-24 22:24:29 +00002360 default:
2361 if (log)
2362 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2363 done = true;
2364 break;
2365 }
2366 }
2367 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2368 {
2369 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2370 {
2371 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002372 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002373 }
Chris Lattner24943d22010-06-08 16:52:24 +00002374 }
2375 }
2376 else
2377 {
2378 if (log)
2379 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2380 done = true;
2381 }
2382 }
2383 }
2384
2385 if (log)
2386 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2387
2388 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2389 return NULL;
2390}
2391
Chris Lattner24943d22010-06-08 16:52:24 +00002392const char *
2393ProcessGDBRemote::GetDispatchQueueNameForThread
2394(
2395 addr_t thread_dispatch_qaddr,
2396 std::string &dispatch_queue_name
2397)
2398{
2399 dispatch_queue_name.clear();
2400 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2401 {
2402 // Cache the dispatch_queue_offsets_addr value so we don't always have
2403 // to look it up
2404 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2405 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002406 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2407 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002408 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002409 if (module_sp)
2410 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2411
2412 if (dispatch_queue_offsets_symbol == NULL)
2413 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002414 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002415 if (module_sp)
2416 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2417 }
Chris Lattner24943d22010-06-08 16:52:24 +00002418 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002419 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002420
2421 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2422 return NULL;
2423 }
2424
2425 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002426 DataExtractor data (memory_buffer,
2427 sizeof(memory_buffer),
2428 m_target.GetArchitecture().GetByteOrder(),
2429 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002430
2431 // Excerpt from src/queue_private.h
2432 struct dispatch_queue_offsets_s
2433 {
2434 uint16_t dqo_version;
2435 uint16_t dqo_label;
2436 uint16_t dqo_label_size;
2437 } dispatch_queue_offsets;
2438
2439
2440 Error error;
2441 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2442 {
2443 uint32_t data_offset = 0;
2444 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2445 {
2446 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2447 {
2448 data_offset = 0;
2449 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2450 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2451 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2452 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2453 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2454 dispatch_queue_name.erase (bytes_read);
2455 }
2456 }
2457 }
2458 }
2459 if (dispatch_queue_name.empty())
2460 return NULL;
2461 return dispatch_queue_name.c_str();
2462}
2463
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002464//uint32_t
2465//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2466//{
2467// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2468// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2469// if (m_local_debugserver)
2470// {
2471// return Host::ListProcessesMatchingName (name, matches, pids);
2472// }
2473// else
2474// {
2475// // FIXME: Implement talking to the remote debugserver.
2476// return 0;
2477// }
2478//
2479//}
2480//
Jim Ingham55e01d82011-01-22 01:33:44 +00002481bool
2482ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2483 lldb_private::StoppointCallbackContext *context,
2484 lldb::user_id_t break_id,
2485 lldb::user_id_t break_loc_id)
2486{
2487 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2488 // run so I can stop it if that's what I want to do.
2489 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2490 if (log)
2491 log->Printf("Hit New Thread Notification breakpoint.");
2492 return false;
2493}
2494
2495
2496bool
2497ProcessGDBRemote::StartNoticingNewThreads()
2498{
2499 static const char *bp_names[] =
2500 {
2501 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002502 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002503 "_pthread_start",
2504 NULL
2505 };
2506
2507 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2508 size_t num_bps = m_thread_observation_bps.size();
2509 if (num_bps != 0)
2510 {
2511 for (int i = 0; i < num_bps; i++)
2512 {
2513 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2514 if (break_sp)
2515 {
2516 if (log)
2517 log->Printf("Enabled noticing new thread breakpoint.");
2518 break_sp->SetEnabled(true);
2519 }
2520 }
2521 }
2522 else
2523 {
2524 for (int i = 0; bp_names[i] != NULL; i++)
2525 {
2526 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2527 if (breakpoint)
2528 {
2529 if (log)
2530 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2531 m_thread_observation_bps.push_back(breakpoint->GetID());
2532 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2533 }
2534 else
2535 {
2536 if (log)
2537 log->Printf("Failed to create new thread notification breakpoint.");
2538 return false;
2539 }
2540 }
2541 }
2542
2543 return true;
2544}
2545
2546bool
2547ProcessGDBRemote::StopNoticingNewThreads()
2548{
Jim Inghamff276fe2011-02-08 05:19:01 +00002549 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2550 if (log)
2551 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002552 size_t num_bps = m_thread_observation_bps.size();
2553 if (num_bps != 0)
2554 {
2555 for (int i = 0; i < num_bps; i++)
2556 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002557
2558 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2559 if (break_sp)
2560 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002561 break_sp->SetEnabled(false);
2562 }
2563 }
2564 }
2565 return true;
2566}
2567
2568