blob: 6b810bbe37aa2b05d52f6a93af2df4a99d492329 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Greg Clayton989816b2011-05-14 01:50:35 +000014#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000016#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000017#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000018
19// C++ Includes
20#include <algorithm>
21#include <map>
22
23// Other libraries and framework includes
24
25#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000026#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Core/ArchSpec.h"
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000030#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Core/InputReader.h"
32#include "lldb/Core/Module.h"
33#include "lldb/Core/PluginManager.h"
34#include "lldb/Core/State.h"
35#include "lldb/Core/StreamString.h"
36#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000037#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Host/TimeValue.h"
39#include "lldb/Symbol/ObjectFile.h"
40#include "lldb/Target/DynamicLoader.h"
41#include "lldb/Target/Target.h"
42#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000043#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000044#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045
46// Project includes
47#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000048#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000049#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000050#include "GDBRemoteRegisterContext.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000054#include "StopInfoMachException.h"
55
Chris Lattner24943d22010-06-08 16:52:24 +000056
Chris Lattner24943d22010-06-08 16:52:24 +000057
58#define DEBUGSERVER_BASENAME "debugserver"
59using namespace lldb;
60using namespace lldb_private;
61
Jim Inghamf9600482011-03-29 21:45:47 +000062static bool rand_initialized = false;
63
Chris Lattner24943d22010-06-08 16:52:24 +000064static inline uint16_t
65get_random_port ()
66{
Jim Inghamf9600482011-03-29 21:45:47 +000067 if (!rand_initialized)
68 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000069 time_t seed = time(NULL);
70
Jim Inghamf9600482011-03-29 21:45:47 +000071 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000072 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000073 }
Stephen Wilson50daf772011-03-25 18:16:28 +000074 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000075}
76
77
78const char *
79ProcessGDBRemote::GetPluginNameStatic()
80{
Greg Claytonb1888f22011-03-19 01:12:21 +000081 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000082}
83
84const char *
85ProcessGDBRemote::GetPluginDescriptionStatic()
86{
87 return "GDB Remote protocol based debugging plug-in.";
88}
89
90void
91ProcessGDBRemote::Terminate()
92{
93 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
94}
95
96
97Process*
98ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
99{
100 return new ProcessGDBRemote (target, listener);
101}
102
103bool
104ProcessGDBRemote::CanDebug(Target &target)
105{
106 // For now we are just making sure the file exists for a given module
107 ModuleSP exe_module_sp(target.GetExecutableModule());
108 if (exe_module_sp.get())
109 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000110 // However, if there is no executable module, we return true since we might be preparing to attach.
111 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000112}
113
114//----------------------------------------------------------------------
115// ProcessGDBRemote constructor
116//----------------------------------------------------------------------
117ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
118 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000119 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000120 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000121 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000123 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000124 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000125 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000126 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
127 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000128 m_continue_c_tids (),
129 m_continue_C_tids (),
130 m_continue_s_tids (),
131 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000132 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000133 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000134 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000135 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000136{
Greg Claytonff39f742011-04-01 00:29:43 +0000137 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
138 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000139}
140
141//----------------------------------------------------------------------
142// Destructor
143//----------------------------------------------------------------------
144ProcessGDBRemote::~ProcessGDBRemote()
145{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000146 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000147 {
148 Host::ThreadCancel (m_debugserver_thread, NULL);
149 thread_result_t thread_result;
150 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
151 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
152 }
Chris Lattner24943d22010-06-08 16:52:24 +0000153 // m_mach_process.UnregisterNotificationCallbacks (this);
154 Clear();
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.
Greg Claytonb4747822011-06-24 22:32:10 +0000466 PlatformSP platform_sp (m_target.GetPlatform());
467 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000468 {
469 const char *slave_name = NULL;
470 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000471 {
Greg Claytona2f74232011-02-24 22:24:29 +0000472 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
473 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000474 }
Greg Claytona2f74232011-02-24 22:24:29 +0000475 if (stdin_path == NULL)
476 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000477
Greg Claytona2f74232011-02-24 22:24:29 +0000478 if (stdout_path == NULL)
479 stdout_path = slave_name;
480
481 if (stderr_path == NULL)
482 stderr_path = slave_name;
483 }
484
Greg Claytonafb81862011-03-02 21:34:46 +0000485 // Set STDIN to /dev/null if we want STDIO disabled or if either
486 // STDOUT or STDERR have been set to something and STDIN hasn't
487 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000488 stdin_path = "/dev/null";
489
Greg Claytonafb81862011-03-02 21:34:46 +0000490 // Set STDOUT to /dev/null if we want STDIO disabled or if either
491 // STDIN or STDERR have been set to something and STDOUT hasn't
492 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000493 stdout_path = "/dev/null";
494
Greg Claytonafb81862011-03-02 21:34:46 +0000495 // Set STDERR to /dev/null if we want STDIO disabled or if either
496 // STDIN or STDOUT have been set to something and STDERR hasn't
497 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000498 stderr_path = "/dev/null";
499
500 if (stdin_path)
501 m_gdb_comm.SetSTDIN (stdin_path);
502 if (stdout_path)
503 m_gdb_comm.SetSTDOUT (stdout_path);
504 if (stderr_path)
505 m_gdb_comm.SetSTDERR (stderr_path);
506
507 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
508
Greg Claytona4582402011-05-08 04:53:50 +0000509 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000510
511 if (working_dir && working_dir[0])
512 {
513 m_gdb_comm.SetWorkingDir (working_dir);
514 }
515
516 // Send the environment and the program + arguments after we connect
517 if (envp)
518 {
519 const char *env_entry;
520 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000521 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000522 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000523 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000524 }
Greg Claytona2f74232011-02-24 22:24:29 +0000525 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000526
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000527 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
528 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
529 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Greg Claytona2f74232011-02-24 22:24:29 +0000530 if (arg_packet_err == 0)
531 {
532 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000533 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000534 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000535 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000536 }
537 else
538 {
Greg Claytona2f74232011-02-24 22:24:29 +0000539 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000540 }
Greg Claytona2f74232011-02-24 22:24:29 +0000541 }
542 else
543 {
544 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
545 }
Chris Lattner24943d22010-06-08 16:52:24 +0000546
Greg Claytona2f74232011-02-24 22:24:29 +0000547 if (GetID() == LLDB_INVALID_PROCESS_ID)
548 {
549 KillDebugserverProcess ();
550 return error;
551 }
552
Greg Clayton261a18b2011-06-02 22:22:38 +0000553 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000554 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000555 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000556
557 if (!disable_stdio)
558 {
559 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
560 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
561 }
Chris Lattner24943d22010-06-08 16:52:24 +0000562 }
563 }
Chris Lattner24943d22010-06-08 16:52:24 +0000564 }
565 else
566 {
567 // Set our user ID to an invalid process ID.
568 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000569 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
570 module->GetFileSpec().GetFilename().AsCString(),
571 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000572 }
Chris Lattner24943d22010-06-08 16:52:24 +0000573 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000574
Chris Lattner24943d22010-06-08 16:52:24 +0000575}
576
577
578Error
Greg Claytone71e2582011-02-04 01:58:07 +0000579ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000580{
581 Error error;
582 // Sleep and wait a bit for debugserver to start to listen...
583 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
584 if (conn_ap.get())
585 {
Chris Lattner24943d22010-06-08 16:52:24 +0000586 const uint32_t max_retry_count = 50;
587 uint32_t retry_count = 0;
588 while (!m_gdb_comm.IsConnected())
589 {
Greg Claytone71e2582011-02-04 01:58:07 +0000590 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000591 {
592 m_gdb_comm.SetConnection (conn_ap.release());
593 break;
594 }
595 retry_count++;
596
597 if (retry_count >= max_retry_count)
598 break;
599
600 usleep (100000);
601 }
602 }
603
604 if (!m_gdb_comm.IsConnected())
605 {
606 if (error.Success())
607 error.SetErrorString("not connected to remote gdb server");
608 return error;
609 }
610
Greg Clayton24bc5d92011-03-30 18:16:51 +0000611 // We always seem to be able to open a connection to a local port
612 // so we need to make sure we can then send data to it. If we can't
613 // then we aren't actually connected to anything, so try and do the
614 // handshake with the remote GDB server and make sure that goes
615 // alright.
616 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000617 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000618 m_gdb_comm.Disconnect();
619 if (error.Success())
620 error.SetErrorString("not connected to remote gdb server");
621 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000622 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000623 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
624 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
625 this,
626 m_debugserver_pid,
627 false);
628 m_gdb_comm.ResetDiscoverableSettings();
629 m_gdb_comm.QueryNoAckModeSupported ();
630 m_gdb_comm.GetThreadSuffixSupported ();
631 m_gdb_comm.GetHostInfo ();
632 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000633 return error;
634}
635
636void
637ProcessGDBRemote::DidLaunchOrAttach ()
638{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000639 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
640 if (log)
641 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000642 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000643 {
644 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
645
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000646 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000647
Chris Lattner24943d22010-06-08 16:52:24 +0000648 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000649
Greg Claytoncb8977d2011-03-23 00:09:55 +0000650 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
651 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000652 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000653 ArchSpec &target_arch = GetTarget().GetArchitecture();
654
655 if (target_arch.IsValid())
656 {
657 // If the remote host is ARM and we have apple as the vendor, then
658 // ARM executables and shared libraries can have mixed ARM architectures.
659 // You can have an armv6 executable, and if the host is armv7, then the
660 // system will load the best possible architecture for all shared libraries
661 // it has, so we really need to take the remote host architecture as our
662 // defacto architecture in this case.
663
664 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
665 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
666 {
667 target_arch = gdb_remote_arch;
668 }
669 else
670 {
671 // Fill in what is missing in the triple
672 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
673 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000674 if (target_triple.getVendorName().size() == 0)
675 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000676 target_triple.setVendor (remote_triple.getVendor());
677
Greg Clayton2f085c62011-05-15 01:25:55 +0000678 if (target_triple.getOSName().size() == 0)
679 {
680 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000681
Greg Clayton2f085c62011-05-15 01:25:55 +0000682 if (target_triple.getEnvironmentName().size() == 0)
683 target_triple.setEnvironment (remote_triple.getEnvironment());
684 }
685 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000686 }
687 }
688 else
689 {
690 // The target doesn't have a valid architecture yet, set it from
691 // the architecture we got from the remote GDB server
692 target_arch = gdb_remote_arch;
693 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000694 }
Chris Lattner24943d22010-06-08 16:52:24 +0000695 }
696}
697
698void
699ProcessGDBRemote::DidLaunch ()
700{
701 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000702}
703
704Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000705ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000706{
707 Error error;
708 // Clear out and clean up from any current state
709 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000710 if (attach_pid != LLDB_INVALID_PROCESS_ID)
711 {
Greg Claytona2f74232011-02-24 22:24:29 +0000712 // Make sure we aren't already connected?
713 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000714 {
Greg Claytona2f74232011-02-24 22:24:29 +0000715 char host_port[128];
716 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
717 char connect_url[128];
718 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000719
Greg Claytonb72d0f02011-04-12 05:54:46 +0000720 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000721
722 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000723 {
Greg Claytona2f74232011-02-24 22:24:29 +0000724 const char *error_string = error.AsCString();
725 if (error_string == NULL)
726 error_string = "unable to launch " DEBUGSERVER_BASENAME;
727
728 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000729 }
Greg Claytona2f74232011-02-24 22:24:29 +0000730 else
731 {
732 error = ConnectToDebugserver (connect_url);
733 }
734 }
735
736 if (error.Success())
737 {
738 char packet[64];
739 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
740
741 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000742 }
743 }
Chris Lattner24943d22010-06-08 16:52:24 +0000744 return error;
745}
746
747size_t
748ProcessGDBRemote::AttachInputReaderCallback
749(
750 void *baton,
751 InputReader *reader,
752 lldb::InputReaderAction notification,
753 const char *bytes,
754 size_t bytes_len
755)
756{
757 if (notification == eInputReaderGotToken)
758 {
759 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
760 if (gdb_process->m_waiting_for_attach)
761 gdb_process->m_waiting_for_attach = false;
762 reader->SetIsDone(true);
763 return 1;
764 }
765 return 0;
766}
767
768Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000769ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000770{
771 Error error;
772 // Clear out and clean up from any current state
773 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000774
Chris Lattner24943d22010-06-08 16:52:24 +0000775 if (process_name && process_name[0])
776 {
Greg Claytona2f74232011-02-24 22:24:29 +0000777 // Make sure we aren't already connected?
778 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000779 {
Greg Claytona2f74232011-02-24 22:24:29 +0000780 char host_port[128];
781 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
782 char connect_url[128];
783 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
784
Greg Claytonb72d0f02011-04-12 05:54:46 +0000785 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000786 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000787 {
Greg Claytona2f74232011-02-24 22:24:29 +0000788 const char *error_string = error.AsCString();
789 if (error_string == NULL)
790 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000791
Greg Claytona2f74232011-02-24 22:24:29 +0000792 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000793 }
Greg Claytona2f74232011-02-24 22:24:29 +0000794 else
795 {
796 error = ConnectToDebugserver (connect_url);
797 }
798 }
799
800 if (error.Success())
801 {
802 StreamString packet;
803
804 if (wait_for_launch)
805 packet.PutCString("vAttachWait");
806 else
807 packet.PutCString("vAttachName");
808 packet.PutChar(';');
809 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
810
811 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
812
Chris Lattner24943d22010-06-08 16:52:24 +0000813 }
814 }
Chris Lattner24943d22010-06-08 16:52:24 +0000815 return error;
816}
817
Chris Lattner24943d22010-06-08 16:52:24 +0000818
819void
820ProcessGDBRemote::DidAttach ()
821{
Greg Claytone71e2582011-02-04 01:58:07 +0000822 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000823}
824
825Error
826ProcessGDBRemote::WillResume ()
827{
Greg Claytonc1f45872011-02-12 06:28:37 +0000828 m_continue_c_tids.clear();
829 m_continue_C_tids.clear();
830 m_continue_s_tids.clear();
831 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000832 return Error();
833}
834
835Error
836ProcessGDBRemote::DoResume ()
837{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000838 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000839 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
840 if (log)
841 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000842
843 Listener listener ("gdb-remote.resume-packet-sent");
844 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
845 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000846 StreamString continue_packet;
847 bool continue_packet_error = false;
848 if (m_gdb_comm.HasAnyVContSupport ())
849 {
850 continue_packet.PutCString ("vCont");
851
852 if (!m_continue_c_tids.empty())
853 {
854 if (m_gdb_comm.GetVContSupported ('c'))
855 {
856 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)
857 continue_packet.Printf(";c:%4.4x", *t_pos);
858 }
859 else
860 continue_packet_error = true;
861 }
862
863 if (!continue_packet_error && !m_continue_C_tids.empty())
864 {
865 if (m_gdb_comm.GetVContSupported ('C'))
866 {
867 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)
868 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
869 }
870 else
871 continue_packet_error = true;
872 }
Greg Claytonb749a262010-12-03 06:02:24 +0000873
Greg Claytonc1f45872011-02-12 06:28:37 +0000874 if (!continue_packet_error && !m_continue_s_tids.empty())
875 {
876 if (m_gdb_comm.GetVContSupported ('s'))
877 {
878 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)
879 continue_packet.Printf(";s:%4.4x", *t_pos);
880 }
881 else
882 continue_packet_error = true;
883 }
884
885 if (!continue_packet_error && !m_continue_S_tids.empty())
886 {
887 if (m_gdb_comm.GetVContSupported ('S'))
888 {
889 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)
890 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
891 }
892 else
893 continue_packet_error = true;
894 }
895
896 if (continue_packet_error)
897 continue_packet.GetString().clear();
898 }
899 else
900 continue_packet_error = true;
901
902 if (continue_packet_error)
903 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000904 // 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 Claytonde1dd812011-06-24 03:21:43 +0000918 continue_packet.PutChar ('c');
919 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000920 }
921 else if (num_continue_c_tids == 1 &&
922 num_continue_C_tids == 0 &&
923 num_continue_s_tids == 0 &&
924 num_continue_S_tids == 0 )
925 {
926 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000927 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000928 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000929 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000930 }
931 }
932
Greg Claytonde1dd812011-06-24 03:21:43 +0000933 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000934 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000935 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
936 num_continue_C_tids > 0 &&
937 num_continue_s_tids == 0 &&
938 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000939 {
940 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000941 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +0000942 if (num_continue_C_tids > 1)
943 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000944 // More that one thread with a signal, yet we don't have
945 // vCont support and we are being asked to resume each
946 // thread with a signal, we need to make sure they are
947 // all the same signal, or we can't issue the continue
948 // accurately with the current support...
949 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +0000950 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000951 continue_packet_error = false;
952 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
953 {
954 if (m_continue_C_tids[i].second != continue_signo)
955 continue_packet_error = true;
956 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000957 }
Greg Claytonde1dd812011-06-24 03:21:43 +0000958 if (!continue_packet_error)
959 m_gdb_comm.SetCurrentThreadForRun (-1);
960 }
961 else
962 {
963 // Set the continue thread ID
964 continue_packet_error = false;
965 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000966 }
967 if (!continue_packet_error)
968 {
969 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +0000970 continue_packet.Printf("C%2.2x", continue_signo);
971 }
972 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000973 }
974
Greg Claytonde1dd812011-06-24 03:21:43 +0000975 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000976 {
977 if (num_continue_s_tids == num_threads)
978 {
979 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000980 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000981 continue_packet.PutChar ('s');
982 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000983 }
984 else if (num_continue_c_tids == 0 &&
985 num_continue_C_tids == 0 &&
986 num_continue_s_tids == 1 &&
987 num_continue_S_tids == 0 )
988 {
989 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +0000990 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000991 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +0000992 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000993 }
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?
Greg Claytonde1dd812011-06-24 03:21:43 +00001002 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001003 if (num_continue_S_tids > 1)
1004 {
1005 for (size_t i=1; i<num_threads; ++i)
1006 {
1007 if (m_continue_S_tids[i].second != step_signo)
1008 continue_packet_error = true;
1009 }
1010 }
1011 if (!continue_packet_error)
1012 {
1013 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001014 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001015 continue_packet.Printf("S%2.2x", step_signo);
1016 }
1017 }
1018 else if (num_continue_c_tids == 0 &&
1019 num_continue_C_tids == 0 &&
1020 num_continue_s_tids == 0 &&
1021 num_continue_S_tids == 1 )
1022 {
1023 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001024 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001025 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001026 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001027 }
1028 }
1029 }
1030
1031 if (continue_packet_error)
1032 {
1033 error.SetErrorString ("can't make continue packet for this resume");
1034 }
1035 else
1036 {
1037 EventSP event_sp;
1038 TimeValue timeout;
1039 timeout = TimeValue::Now();
1040 timeout.OffsetWithSeconds (5);
1041 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1042
1043 if (listener.WaitForEvent (&timeout, event_sp) == false)
1044 error.SetErrorString("Resume timed out.");
1045 }
Greg Claytonb749a262010-12-03 06:02:24 +00001046 }
1047
Jim Ingham3ae449a2010-11-17 02:32:00 +00001048 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001049}
1050
Chris Lattner24943d22010-06-08 16:52:24 +00001051uint32_t
1052ProcessGDBRemote::UpdateThreadListIfNeeded ()
1053{
1054 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001055 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001056 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001057 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1058
Greg Clayton5205f0b2010-09-03 17:10:42 +00001059 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001060 const uint32_t stop_id = GetStopID();
1061 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1062 {
1063 // Update the thread list's stop id immediately so we don't recurse into this function.
1064 ThreadList curr_thread_list (this);
1065 curr_thread_list.SetStopID(stop_id);
1066
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001067 std::vector<lldb::tid_t> thread_ids;
1068 bool sequence_mutex_unavailable = false;
1069 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1070 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001071 {
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001072 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001073 {
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001074 tid_t tid = thread_ids[i];
1075 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
1076 if (!thread_sp)
1077 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1078 curr_thread_list.AddThread(thread_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001079 }
1080 }
1081
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001082 if (sequence_mutex_unavailable == false)
1083 {
1084 m_thread_list = curr_thread_list;
1085 SetThreadStopInfo (m_last_stop_packet);
1086 }
Chris Lattner24943d22010-06-08 16:52:24 +00001087 }
1088 return GetThreadList().GetSize(false);
1089}
1090
1091
1092StateType
1093ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1094{
Greg Clayton261a18b2011-06-02 22:22:38 +00001095 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001096 const char stop_type = stop_packet.GetChar();
1097 switch (stop_type)
1098 {
1099 case 'T':
1100 case 'S':
1101 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001102 if (GetStopID() == 0)
1103 {
1104 // Our first stop, make sure we have a process ID, and also make
1105 // sure we know about our registers
1106 if (GetID() == LLDB_INVALID_PROCESS_ID)
1107 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001108 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001109 if (pid != LLDB_INVALID_PROCESS_ID)
1110 SetID (pid);
1111 }
1112 BuildDynamicRegisterInfo (true);
1113 }
Chris Lattner24943d22010-06-08 16:52:24 +00001114 // Stop with signal and thread info
1115 const uint8_t signo = stop_packet.GetHexU8();
1116 std::string name;
1117 std::string value;
1118 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001119 std::string reason;
1120 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001121 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001122 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001123 uint32_t tid = LLDB_INVALID_THREAD_ID;
1124 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1125 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001126 ThreadSP thread_sp;
1127
Chris Lattner24943d22010-06-08 16:52:24 +00001128 while (stop_packet.GetNameColonValue(name, value))
1129 {
1130 if (name.compare("metype") == 0)
1131 {
1132 // exception type in big endian hex
1133 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1134 }
1135 else if (name.compare("mecount") == 0)
1136 {
1137 // exception count in big endian hex
1138 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1139 }
1140 else if (name.compare("medata") == 0)
1141 {
1142 // exception data in big endian hex
1143 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1144 }
1145 else if (name.compare("thread") == 0)
1146 {
1147 // thread in big endian hex
1148 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001149 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001150 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001151 if (!thread_sp)
1152 {
1153 // Create the thread if we need to
1154 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1155 m_thread_list.AddThread(thread_sp);
1156 }
Chris Lattner24943d22010-06-08 16:52:24 +00001157 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001158 else if (name.compare("hexname") == 0)
1159 {
1160 StringExtractor name_extractor;
1161 // Swap "value" over into "name_extractor"
1162 name_extractor.GetStringRef().swap(value);
1163 // Now convert the HEX bytes into a string value
1164 name_extractor.GetHexByteString (value);
1165 thread_name.swap (value);
1166 }
Chris Lattner24943d22010-06-08 16:52:24 +00001167 else if (name.compare("name") == 0)
1168 {
1169 thread_name.swap (value);
1170 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001171 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001172 {
1173 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1174 }
Greg Clayton65611552011-06-04 01:26:29 +00001175 else if (name.compare("reason") == 0)
1176 {
1177 reason.swap(value);
1178 }
1179 else if (name.compare("description") == 0)
1180 {
1181 StringExtractor desc_extractor;
1182 // Swap "value" over into "name_extractor"
1183 desc_extractor.GetStringRef().swap(value);
1184 // Now convert the HEX bytes into a string value
1185 desc_extractor.GetHexByteString (thread_name);
1186 }
Greg Claytona875b642011-01-09 21:07:35 +00001187 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1188 {
1189 // We have a register number that contains an expedited
1190 // register value. Lets supply this register to our thread
1191 // so it won't have to go and read it.
1192 if (thread_sp)
1193 {
1194 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1195
1196 if (reg != UINT32_MAX)
1197 {
1198 StringExtractor reg_value_extractor;
1199 // Swap "value" over into "reg_value_extractor"
1200 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001201 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1202 {
1203 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1204 name.c_str(),
1205 reg,
1206 reg,
1207 reg_value_extractor.GetStringRef().c_str(),
1208 stop_packet.GetStringRef().c_str());
1209 }
Greg Claytona875b642011-01-09 21:07:35 +00001210 }
1211 }
1212 }
Chris Lattner24943d22010-06-08 16:52:24 +00001213 }
Chris Lattner24943d22010-06-08 16:52:24 +00001214
1215 if (thread_sp)
1216 {
1217 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1218
1219 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001220 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001221 if (exc_type != 0)
1222 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001223 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001224
1225 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1226 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001227 exc_data_size,
1228 exc_data_size >= 1 ? exc_data[0] : 0,
1229 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001230 }
Greg Clayton65611552011-06-04 01:26:29 +00001231 else
Chris Lattner24943d22010-06-08 16:52:24 +00001232 {
Greg Clayton65611552011-06-04 01:26:29 +00001233 bool handled = false;
1234 if (!reason.empty())
1235 {
1236 if (reason.compare("trace") == 0)
1237 {
1238 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1239 handled = true;
1240 }
1241 else if (reason.compare("breakpoint") == 0)
1242 {
1243 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1244 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1245 if (bp_site_sp)
1246 {
1247 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1248 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1249 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1250 if (bp_site_sp->ValidForThisThread (gdb_thread))
1251 {
1252 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1253 handled = true;
1254 }
1255 }
1256
1257 if (!handled)
1258 {
1259 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1260 }
1261 }
1262 else if (reason.compare("trap") == 0)
1263 {
1264 // Let the trap just use the standard signal stop reason below...
1265 }
1266 else if (reason.compare("watchpoint") == 0)
1267 {
1268 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1269 // TODO: locate the watchpoint somehow...
1270 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1271 handled = true;
1272 }
1273 else if (reason.compare("exception") == 0)
1274 {
1275 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1276 handled = true;
1277 }
1278 }
1279
1280 if (signo)
1281 {
1282 if (signo == SIGTRAP)
1283 {
1284 // Currently we are going to assume SIGTRAP means we are either
1285 // hitting a breakpoint or hardware single stepping.
1286 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1287 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1288 if (bp_site_sp)
1289 {
1290 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1291 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1292 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1293 if (bp_site_sp->ValidForThisThread (gdb_thread))
1294 {
1295 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1296 handled = true;
1297 }
1298 }
1299 if (!handled)
1300 {
1301 // TODO: check for breakpoint or trap opcode in case there is a hard
1302 // coded software trap
1303 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1304 handled = true;
1305 }
1306 }
1307 if (!handled)
Greg Clayton643ee732010-08-04 01:40:35 +00001308 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001309 }
1310 else
1311 {
Greg Clayton643ee732010-08-04 01:40:35 +00001312 StopInfoSP invalid_stop_info_sp;
1313 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001314 }
Greg Clayton65611552011-06-04 01:26:29 +00001315
1316 if (!description.empty())
1317 {
1318 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1319 if (stop_info_sp)
1320 {
1321 stop_info_sp->SetDescription (description.c_str());
1322 }
1323 else
1324 {
1325 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1326 }
1327 }
1328 }
Chris Lattner24943d22010-06-08 16:52:24 +00001329 }
1330 return eStateStopped;
1331 }
1332 break;
1333
1334 case 'W':
1335 // process exited
1336 return eStateExited;
1337
1338 default:
1339 break;
1340 }
1341 return eStateInvalid;
1342}
1343
1344void
1345ProcessGDBRemote::RefreshStateAfterStop ()
1346{
Chris Lattner24943d22010-06-08 16:52:24 +00001347 // Let all threads recover from stopping and do any clean up based
1348 // on the previous thread state (if any).
1349 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001350 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001351}
1352
1353Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001354ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001355{
1356 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001357
Greg Claytona4881d02011-01-22 07:12:45 +00001358 bool timed_out = false;
1359 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001360
1361 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001362 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001363 // We are being asked to halt during an attach. We need to just close
1364 // our file handle and debugserver will go away, and we can be done...
1365 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001366 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001367 else
1368 {
1369 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1370 {
1371 if (timed_out)
1372 error.SetErrorString("timed out sending interrupt packet");
1373 else
1374 error.SetErrorString("unknown error sending interrupt packet");
1375 }
1376 }
Chris Lattner24943d22010-06-08 16:52:24 +00001377 return error;
1378}
1379
1380Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001381ProcessGDBRemote::InterruptIfRunning
1382(
1383 bool discard_thread_plans,
1384 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001385 EventSP &stop_event_sp
1386)
Chris Lattner24943d22010-06-08 16:52:24 +00001387{
1388 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001389
Greg Clayton2860ba92011-01-23 19:58:49 +00001390 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1391
Greg Clayton68ca8232011-01-25 02:58:48 +00001392 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001393 const bool is_running = m_gdb_comm.IsRunning();
1394 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001395 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001396 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001397 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001398 is_running);
1399
Greg Clayton2860ba92011-01-23 19:58:49 +00001400 if (discard_thread_plans)
1401 {
1402 if (log)
1403 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1404 m_thread_list.DiscardThreadPlans();
1405 }
1406 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001407 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001408 if (catch_stop_event)
1409 {
1410 if (log)
1411 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1412 PausePrivateStateThread();
1413 paused_private_state_thread = true;
1414 }
1415
Greg Clayton4fb400f2010-09-27 21:07:38 +00001416 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001417 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001418 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001419
Greg Clayton72e1c782011-01-22 23:43:18 +00001420 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001421 {
1422 if (timed_out)
1423 error.SetErrorString("timed out sending interrupt packet");
1424 else
1425 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001426 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001427 ResumePrivateStateThread();
1428 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001429 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001430
Greg Clayton72e1c782011-01-22 23:43:18 +00001431 if (catch_stop_event)
1432 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001433 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001434 TimeValue timeout_time;
1435 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001436 timeout_time.OffsetWithSeconds(5);
1437 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001438
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001439 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001440 if (log)
1441 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001442
Greg Clayton2860ba92011-01-23 19:58:49 +00001443 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001444 error.SetErrorString("unable to verify target stopped");
1445 }
1446
Greg Clayton68ca8232011-01-25 02:58:48 +00001447 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001448 {
1449 if (log)
1450 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001451 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001452 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001453 }
Chris Lattner24943d22010-06-08 16:52:24 +00001454 return error;
1455}
1456
Greg Clayton4fb400f2010-09-27 21:07:38 +00001457Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001458ProcessGDBRemote::WillDetach ()
1459{
Greg Clayton2860ba92011-01-23 19:58:49 +00001460 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1461 if (log)
1462 log->Printf ("ProcessGDBRemote::WillDetach()");
1463
Greg Clayton72e1c782011-01-22 23:43:18 +00001464 bool discard_thread_plans = true;
1465 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001466 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001467 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001468}
1469
1470Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001471ProcessGDBRemote::DoDetach()
1472{
1473 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001474 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001475 if (log)
1476 log->Printf ("ProcessGDBRemote::DoDetach()");
1477
1478 DisableAllBreakpointSites ();
1479
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001480 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001481
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001482 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1483 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001484 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001485 if (response_size)
1486 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1487 else
1488 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001489 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001490 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001491 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001492
Greg Clayton4fb400f2010-09-27 21:07:38 +00001493 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001494 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001495
1496 SetPrivateState (eStateDetached);
1497 ResumePrivateStateThread();
1498
1499 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001500 return error;
1501}
Chris Lattner24943d22010-06-08 16:52:24 +00001502
1503Error
1504ProcessGDBRemote::DoDestroy ()
1505{
1506 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001507 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001508 if (log)
1509 log->Printf ("ProcessGDBRemote::DoDestroy()");
1510
1511 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001512 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001513 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001514 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001515 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001516 // We are being asked to halt during an attach. We need to just close
1517 // our file handle and debugserver will go away, and we can be done...
1518 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001519 }
1520 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001521 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001522
1523 StringExtractorGDBRemote response;
1524 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001525 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001526 {
1527 char packet_cmd = response.GetChar(0);
1528
1529 if (packet_cmd == 'W' || packet_cmd == 'X')
1530 {
1531 m_last_stop_packet = response;
1532 SetExitStatus(response.GetHexU8(), NULL);
1533 }
1534 }
1535 else
1536 {
1537 SetExitStatus(SIGABRT, NULL);
1538 //error.SetErrorString("kill packet failed");
1539 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001540 }
1541 }
Chris Lattner24943d22010-06-08 16:52:24 +00001542 StopAsyncThread ();
1543 m_gdb_comm.StopReadThread();
1544 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001545 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001546 return error;
1547}
1548
Chris Lattner24943d22010-06-08 16:52:24 +00001549//------------------------------------------------------------------
1550// Process Queries
1551//------------------------------------------------------------------
1552
1553bool
1554ProcessGDBRemote::IsAlive ()
1555{
Greg Clayton58e844b2010-12-08 05:08:21 +00001556 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001557}
1558
1559addr_t
1560ProcessGDBRemote::GetImageInfoAddress()
1561{
1562 if (!m_gdb_comm.IsRunning())
1563 {
1564 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001565 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001566 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001567 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001568 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1569 }
1570 }
1571 return LLDB_INVALID_ADDRESS;
1572}
1573
Chris Lattner24943d22010-06-08 16:52:24 +00001574//------------------------------------------------------------------
1575// Process Memory
1576//------------------------------------------------------------------
1577size_t
1578ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1579{
1580 if (size > m_max_memory_size)
1581 {
1582 // Keep memory read sizes down to a sane limit. This function will be
1583 // called multiple times in order to complete the task by
1584 // lldb_private::Process so it is ok to do this.
1585 size = m_max_memory_size;
1586 }
1587
1588 char packet[64];
1589 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1590 assert (packet_len + 1 < sizeof(packet));
1591 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001592 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001593 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001594 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001595 {
1596 error.Clear();
1597 return response.GetHexBytes(buf, size, '\xdd');
1598 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001599 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001600 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001601 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001602 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1603 else
1604 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1605 }
1606 else
1607 {
1608 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1609 }
1610 return 0;
1611}
1612
1613size_t
1614ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1615{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001616 if (size > m_max_memory_size)
1617 {
1618 // Keep memory read sizes down to a sane limit. This function will be
1619 // called multiple times in order to complete the task by
1620 // lldb_private::Process so it is ok to do this.
1621 size = m_max_memory_size;
1622 }
1623
Chris Lattner24943d22010-06-08 16:52:24 +00001624 StreamString packet;
1625 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001626 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001627 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001628 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001629 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001630 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001631 {
1632 error.Clear();
1633 return size;
1634 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001635 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001636 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001637 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001638 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1639 else
1640 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1641 }
1642 else
1643 {
1644 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1645 }
1646 return 0;
1647}
1648
1649lldb::addr_t
1650ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1651{
Greg Clayton989816b2011-05-14 01:50:35 +00001652 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1653
Greg Clayton2f085c62011-05-15 01:25:55 +00001654 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001655 switch (supported)
1656 {
1657 case eLazyBoolCalculate:
1658 case eLazyBoolYes:
1659 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1660 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1661 return allocated_addr;
1662
1663 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001664 // Call mmap() to create memory in the inferior..
1665 unsigned prot = 0;
1666 if (permissions & lldb::ePermissionsReadable)
1667 prot |= eMmapProtRead;
1668 if (permissions & lldb::ePermissionsWritable)
1669 prot |= eMmapProtWrite;
1670 if (permissions & lldb::ePermissionsExecutable)
1671 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001672
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001673 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1674 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1675 m_addr_to_mmap_size[allocated_addr] = size;
1676 else
1677 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001678 break;
1679 }
1680
Chris Lattner24943d22010-06-08 16:52:24 +00001681 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001682 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001683 else
1684 error.Clear();
1685 return allocated_addr;
1686}
1687
1688Error
1689ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1690{
1691 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001692 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1693
1694 switch (supported)
1695 {
1696 case eLazyBoolCalculate:
1697 // We should never be deallocating memory without allocating memory
1698 // first so we should never get eLazyBoolCalculate
1699 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1700 break;
1701
1702 case eLazyBoolYes:
1703 if (!m_gdb_comm.DeallocateMemory (addr))
1704 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1705 break;
1706
1707 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001708 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001709 {
1710 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001711 if (pos != m_addr_to_mmap_size.end() &&
1712 InferiorCallMunmap(this, addr, pos->second))
1713 m_addr_to_mmap_size.erase (pos);
1714 else
1715 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001716 }
1717 break;
1718 }
1719
Chris Lattner24943d22010-06-08 16:52:24 +00001720 return error;
1721}
1722
1723
1724//------------------------------------------------------------------
1725// Process STDIO
1726//------------------------------------------------------------------
1727
1728size_t
1729ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1730{
1731 Mutex::Locker locker(m_stdio_mutex);
1732 size_t bytes_available = m_stdout_data.size();
1733 if (bytes_available > 0)
1734 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001735 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1736 if (log)
1737 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001738 if (bytes_available > buf_size)
1739 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001740 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001741 m_stdout_data.erase(0, buf_size);
1742 bytes_available = buf_size;
1743 }
1744 else
1745 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001746 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001747 m_stdout_data.clear();
1748
1749 //ResetEventBits(eBroadcastBitSTDOUT);
1750 }
1751 }
1752 return bytes_available;
1753}
1754
1755size_t
1756ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1757{
1758 // Can we get STDERR through the remote protocol?
1759 return 0;
1760}
1761
1762size_t
1763ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1764{
1765 if (m_stdio_communication.IsConnected())
1766 {
1767 ConnectionStatus status;
1768 m_stdio_communication.Write(src, src_len, status, NULL);
1769 }
1770 return 0;
1771}
1772
1773Error
1774ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1775{
1776 Error error;
1777 assert (bp_site != NULL);
1778
Greg Claytone005f2c2010-11-06 01:53:30 +00001779 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001780 user_id_t site_id = bp_site->GetID();
1781 const addr_t addr = bp_site->GetLoadAddress();
1782 if (log)
1783 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1784
1785 if (bp_site->IsEnabled())
1786 {
1787 if (log)
1788 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1789 return error;
1790 }
1791 else
1792 {
1793 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1794
1795 if (bp_site->HardwarePreferred())
1796 {
1797 // Try and set hardware breakpoint, and if that fails, fall through
1798 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001799 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001800 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001801 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001802 {
1803 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001804 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001805 return error;
1806 }
Chris Lattner24943d22010-06-08 16:52:24 +00001807 }
1808 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001809
1810 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001811 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001812 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1813 {
1814 bp_site->SetEnabled(true);
1815 bp_site->SetType (BreakpointSite::eExternal);
1816 return error;
1817 }
Chris Lattner24943d22010-06-08 16:52:24 +00001818 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001819
1820 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001821 }
1822
1823 if (log)
1824 {
1825 const char *err_string = error.AsCString();
1826 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1827 bp_site->GetLoadAddress(),
1828 err_string ? err_string : "NULL");
1829 }
1830 // We shouldn't reach here on a successful breakpoint enable...
1831 if (error.Success())
1832 error.SetErrorToGenericError();
1833 return error;
1834}
1835
1836Error
1837ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1838{
1839 Error error;
1840 assert (bp_site != NULL);
1841 addr_t addr = bp_site->GetLoadAddress();
1842 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001843 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001844 if (log)
1845 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1846
1847 if (bp_site->IsEnabled())
1848 {
1849 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1850
Greg Claytonb72d0f02011-04-12 05:54:46 +00001851 BreakpointSite::Type bp_type = bp_site->GetType();
1852 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001853 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001854 case BreakpointSite::eSoftware:
1855 error = DisableSoftwareBreakpoint (bp_site);
1856 break;
1857
1858 case BreakpointSite::eHardware:
1859 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1860 error.SetErrorToGenericError();
1861 break;
1862
1863 case BreakpointSite::eExternal:
1864 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1865 error.SetErrorToGenericError();
1866 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001867 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001868 if (error.Success())
1869 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001870 }
1871 else
1872 {
1873 if (log)
1874 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1875 return error;
1876 }
1877
1878 if (error.Success())
1879 error.SetErrorToGenericError();
1880 return error;
1881}
1882
1883Error
1884ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1885{
1886 Error error;
1887 if (wp)
1888 {
1889 user_id_t watchID = wp->GetID();
1890 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001891 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001892 if (log)
1893 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1894 if (wp->IsEnabled())
1895 {
1896 if (log)
1897 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1898 return error;
1899 }
1900 else
1901 {
1902 // Pass down an appropriate z/Z packet...
1903 error.SetErrorString("watchpoints not supported");
1904 }
1905 }
1906 else
1907 {
1908 error.SetErrorString("Watchpoint location argument was NULL.");
1909 }
1910 if (error.Success())
1911 error.SetErrorToGenericError();
1912 return error;
1913}
1914
1915Error
1916ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1917{
1918 Error error;
1919 if (wp)
1920 {
1921 user_id_t watchID = wp->GetID();
1922
Greg Claytone005f2c2010-11-06 01:53:30 +00001923 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001924
1925 addr_t addr = wp->GetLoadAddress();
1926 if (log)
1927 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1928
1929 if (wp->IsHardware())
1930 {
1931 // Pass down an appropriate z/Z packet...
1932 error.SetErrorString("watchpoints not supported");
1933 }
1934 // TODO: clear software watchpoints if we implement them
1935 }
1936 else
1937 {
1938 error.SetErrorString("Watchpoint location argument was NULL.");
1939 }
1940 if (error.Success())
1941 error.SetErrorToGenericError();
1942 return error;
1943}
1944
1945void
1946ProcessGDBRemote::Clear()
1947{
1948 m_flags = 0;
1949 m_thread_list.Clear();
1950 {
1951 Mutex::Locker locker(m_stdio_mutex);
1952 m_stdout_data.clear();
1953 }
Chris Lattner24943d22010-06-08 16:52:24 +00001954}
1955
1956Error
1957ProcessGDBRemote::DoSignal (int signo)
1958{
1959 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001960 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001961 if (log)
1962 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1963
1964 if (!m_gdb_comm.SendAsyncSignal (signo))
1965 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1966 return error;
1967}
1968
Chris Lattner24943d22010-06-08 16:52:24 +00001969Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00001970ProcessGDBRemote::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 +00001971{
1972 Error error;
1973 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1974 {
1975 // If we locate debugserver, keep that located version around
1976 static FileSpec g_debugserver_file_spec;
1977
Greg Claytonb72d0f02011-04-12 05:54:46 +00001978 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00001979 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00001980 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00001981
1982 // Always check to see if we have an environment override for the path
1983 // to the debugserver to use and use it if we do.
1984 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1985 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001986 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001987 else
1988 debugserver_file_spec = g_debugserver_file_spec;
1989 bool debugserver_exists = debugserver_file_spec.Exists();
1990 if (!debugserver_exists)
1991 {
1992 // The debugserver binary is in the LLDB.framework/Resources
1993 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001994 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001995 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001996 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001997 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001998 if (debugserver_exists)
1999 {
2000 g_debugserver_file_spec = debugserver_file_spec;
2001 }
2002 else
2003 {
2004 g_debugserver_file_spec.Clear();
2005 debugserver_file_spec.Clear();
2006 }
Chris Lattner24943d22010-06-08 16:52:24 +00002007 }
2008 }
2009
2010 if (debugserver_exists)
2011 {
2012 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2013
2014 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002015
Greg Claytone005f2c2010-11-06 01:53:30 +00002016 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002017
Greg Claytonb72d0f02011-04-12 05:54:46 +00002018 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002019 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002020
Chris Lattner24943d22010-06-08 16:52:24 +00002021 // Start args with "debugserver /file/path -r --"
2022 debugserver_args.AppendArgument(debugserver_path);
2023 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002024 // use native registers, not the GDB registers
2025 debugserver_args.AppendArgument("--native-regs");
2026 // make debugserver run in its own session so signals generated by
2027 // special terminal key sequences (^C) don't affect debugserver
2028 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002029
Chris Lattner24943d22010-06-08 16:52:24 +00002030 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2031 if (env_debugserver_log_file)
2032 {
2033 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2034 debugserver_args.AppendArgument(arg_cstr);
2035 }
2036
2037 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2038 if (env_debugserver_log_flags)
2039 {
2040 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2041 debugserver_args.AppendArgument(arg_cstr);
2042 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002043// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002044// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002045
Greg Claytonb72d0f02011-04-12 05:54:46 +00002046 // We currently send down all arguments, attach pids, or attach
2047 // process names in dedicated GDB server packets, so we don't need
2048 // to pass them as arguments. This is currently because of all the
2049 // things we need to setup prior to launching: the environment,
2050 // current working dir, file actions, etc.
2051#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002052 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002053 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002054 {
Greg Claytona2f74232011-02-24 22:24:29 +00002055 // Terminate the debugserver args so we can now append the inferior args
2056 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002057
Greg Claytona2f74232011-02-24 22:24:29 +00002058 for (int i = 0; inferior_argv[i] != NULL; ++i)
2059 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002060 }
2061 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2062 {
2063 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2064 debugserver_args.AppendArgument (arg_cstr);
2065 }
2066 else if (attach_name && attach_name[0])
2067 {
2068 if (wait_for_launch)
2069 debugserver_args.AppendArgument ("--waitfor");
2070 else
2071 debugserver_args.AppendArgument ("--attach");
2072 debugserver_args.AppendArgument (attach_name);
2073 }
Chris Lattner24943d22010-06-08 16:52:24 +00002074#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002075
2076 ProcessLaunchInfo::FileAction file_action;
2077
2078 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2079 // to "/dev/null" if we run into any problems.
2080 file_action.Close (STDIN_FILENO);
2081 launch_info.AppendFileAction (file_action);
2082 file_action.Close (STDOUT_FILENO);
2083 launch_info.AppendFileAction (file_action);
2084 file_action.Close (STDERR_FILENO);
2085 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002086
2087 if (log)
2088 {
2089 StreamString strm;
2090 debugserver_args.Dump (&strm);
2091 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2092 }
2093
Greg Claytonb72d0f02011-04-12 05:54:46 +00002094 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002095
Greg Claytonb72d0f02011-04-12 05:54:46 +00002096 if (error.Success ())
2097 m_debugserver_pid = launch_info.GetProcessID();
2098 else
Chris Lattner24943d22010-06-08 16:52:24 +00002099 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2100
2101 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002102 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002103 }
2104 else
2105 {
2106 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2107 }
2108
2109 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2110 StartAsyncThread ();
2111 }
2112 return error;
2113}
2114
2115bool
2116ProcessGDBRemote::MonitorDebugserverProcess
2117(
2118 void *callback_baton,
2119 lldb::pid_t debugserver_pid,
2120 int signo, // Zero for no signal
2121 int exit_status // Exit value of process if signal is zero
2122)
2123{
2124 // We pass in the ProcessGDBRemote inferior process it and name it
2125 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2126 // pointer value itself, thus we need the double cast...
2127
2128 // "debugserver_pid" argument passed in is the process ID for
2129 // debugserver that we are tracking...
2130
Greg Clayton75ccf502010-08-21 02:22:51 +00002131 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002132
2133 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2134 if (log)
2135 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2136
Greg Clayton75ccf502010-08-21 02:22:51 +00002137 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002138 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002139 // Sleep for a half a second to make sure our inferior process has
2140 // time to set its exit status before we set it incorrectly when
2141 // both the debugserver and the inferior process shut down.
2142 usleep (500000);
2143 // If our process hasn't yet exited, debugserver might have died.
2144 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002145 const StateType state = process->GetState();
2146
2147 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2148 state != eStateInvalid &&
2149 state != eStateUnloaded &&
2150 state != eStateExited &&
2151 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002152 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002153 char error_str[1024];
2154 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002155 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002156 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2157 if (signal_cstr)
2158 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002159 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002160 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002161 }
2162 else
2163 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002164 ::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 +00002165 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002166
2167 process->SetExitStatus (-1, error_str);
2168 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002169 // Debugserver has exited we need to let our ProcessGDBRemote
2170 // know that it no longer has a debugserver instance
2171 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2172 // We are returning true to this function below, so we can
2173 // forget about the monitor handle.
2174 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002175 }
2176 return true;
2177}
2178
2179void
2180ProcessGDBRemote::KillDebugserverProcess ()
2181{
2182 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2183 {
2184 ::kill (m_debugserver_pid, SIGINT);
2185 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2186 }
2187}
2188
2189void
2190ProcessGDBRemote::Initialize()
2191{
2192 static bool g_initialized = false;
2193
2194 if (g_initialized == false)
2195 {
2196 g_initialized = true;
2197 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2198 GetPluginDescriptionStatic(),
2199 CreateInstance);
2200
2201 Log::Callbacks log_callbacks = {
2202 ProcessGDBRemoteLog::DisableLog,
2203 ProcessGDBRemoteLog::EnableLog,
2204 ProcessGDBRemoteLog::ListLogCategories
2205 };
2206
2207 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2208 }
2209}
2210
2211bool
Chris Lattner24943d22010-06-08 16:52:24 +00002212ProcessGDBRemote::StartAsyncThread ()
2213{
Greg Claytone005f2c2010-11-06 01:53:30 +00002214 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002215
2216 if (log)
2217 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2218
2219 // Create a thread that watches our internal state and controls which
2220 // events make it to clients (into the DCProcess event queue).
2221 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002222 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002223}
2224
2225void
2226ProcessGDBRemote::StopAsyncThread ()
2227{
Greg Claytone005f2c2010-11-06 01:53:30 +00002228 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002229
2230 if (log)
2231 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2232
2233 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2234
2235 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002236 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002237 {
2238 Host::ThreadJoin (m_async_thread, NULL, NULL);
2239 }
2240}
2241
2242
2243void *
2244ProcessGDBRemote::AsyncThread (void *arg)
2245{
2246 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2247
Greg Claytone005f2c2010-11-06 01:53:30 +00002248 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002249 if (log)
2250 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2251
2252 Listener listener ("ProcessGDBRemote::AsyncThread");
2253 EventSP event_sp;
2254 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2255 eBroadcastBitAsyncThreadShouldExit;
2256
2257 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2258 {
Greg Claytona2f74232011-02-24 22:24:29 +00002259 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2260
Chris Lattner24943d22010-06-08 16:52:24 +00002261 bool done = false;
2262 while (!done)
2263 {
2264 if (log)
2265 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2266 if (listener.WaitForEvent (NULL, event_sp))
2267 {
2268 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002269 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002270 {
Greg Claytona2f74232011-02-24 22:24:29 +00002271 if (log)
2272 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 +00002273
Greg Claytona2f74232011-02-24 22:24:29 +00002274 switch (event_type)
2275 {
2276 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002277 {
Greg Claytona2f74232011-02-24 22:24:29 +00002278 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002279
Greg Claytona2f74232011-02-24 22:24:29 +00002280 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002281 {
Greg Claytona2f74232011-02-24 22:24:29 +00002282 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2283 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2284 if (log)
2285 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002286
Greg Claytona2f74232011-02-24 22:24:29 +00002287 if (::strstr (continue_cstr, "vAttach") == NULL)
2288 process->SetPrivateState(eStateRunning);
2289 StringExtractorGDBRemote response;
2290 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002291
Greg Claytona2f74232011-02-24 22:24:29 +00002292 switch (stop_state)
2293 {
2294 case eStateStopped:
2295 case eStateCrashed:
2296 case eStateSuspended:
2297 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002298 process->SetPrivateState (stop_state);
2299 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002300
Greg Claytona2f74232011-02-24 22:24:29 +00002301 case eStateExited:
2302 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002303 response.SetFilePos(1);
2304 process->SetExitStatus(response.GetHexU8(), NULL);
2305 done = true;
2306 break;
2307
2308 case eStateInvalid:
2309 process->SetExitStatus(-1, "lost connection");
2310 break;
2311
2312 default:
2313 process->SetPrivateState (stop_state);
2314 break;
2315 }
Chris Lattner24943d22010-06-08 16:52:24 +00002316 }
2317 }
Greg Claytona2f74232011-02-24 22:24:29 +00002318 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002319
Greg Claytona2f74232011-02-24 22:24:29 +00002320 case eBroadcastBitAsyncThreadShouldExit:
2321 if (log)
2322 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2323 done = true;
2324 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002325
Greg Claytona2f74232011-02-24 22:24:29 +00002326 default:
2327 if (log)
2328 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2329 done = true;
2330 break;
2331 }
2332 }
2333 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2334 {
2335 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2336 {
2337 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002338 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002339 }
Chris Lattner24943d22010-06-08 16:52:24 +00002340 }
2341 }
2342 else
2343 {
2344 if (log)
2345 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2346 done = true;
2347 }
2348 }
2349 }
2350
2351 if (log)
2352 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2353
2354 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2355 return NULL;
2356}
2357
Chris Lattner24943d22010-06-08 16:52:24 +00002358const char *
2359ProcessGDBRemote::GetDispatchQueueNameForThread
2360(
2361 addr_t thread_dispatch_qaddr,
2362 std::string &dispatch_queue_name
2363)
2364{
2365 dispatch_queue_name.clear();
2366 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2367 {
2368 // Cache the dispatch_queue_offsets_addr value so we don't always have
2369 // to look it up
2370 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2371 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002372 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2373 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002374 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002375 if (module_sp)
2376 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2377
2378 if (dispatch_queue_offsets_symbol == NULL)
2379 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002380 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002381 if (module_sp)
2382 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2383 }
Chris Lattner24943d22010-06-08 16:52:24 +00002384 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002385 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002386
2387 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2388 return NULL;
2389 }
2390
2391 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002392 DataExtractor data (memory_buffer,
2393 sizeof(memory_buffer),
2394 m_target.GetArchitecture().GetByteOrder(),
2395 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002396
2397 // Excerpt from src/queue_private.h
2398 struct dispatch_queue_offsets_s
2399 {
2400 uint16_t dqo_version;
2401 uint16_t dqo_label;
2402 uint16_t dqo_label_size;
2403 } dispatch_queue_offsets;
2404
2405
2406 Error error;
2407 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2408 {
2409 uint32_t data_offset = 0;
2410 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2411 {
2412 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2413 {
2414 data_offset = 0;
2415 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2416 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2417 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2418 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2419 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2420 dispatch_queue_name.erase (bytes_read);
2421 }
2422 }
2423 }
2424 }
2425 if (dispatch_queue_name.empty())
2426 return NULL;
2427 return dispatch_queue_name.c_str();
2428}
2429
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002430//uint32_t
2431//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2432//{
2433// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2434// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2435// if (m_local_debugserver)
2436// {
2437// return Host::ListProcessesMatchingName (name, matches, pids);
2438// }
2439// else
2440// {
2441// // FIXME: Implement talking to the remote debugserver.
2442// return 0;
2443// }
2444//
2445//}
2446//
Jim Ingham55e01d82011-01-22 01:33:44 +00002447bool
2448ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2449 lldb_private::StoppointCallbackContext *context,
2450 lldb::user_id_t break_id,
2451 lldb::user_id_t break_loc_id)
2452{
2453 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2454 // run so I can stop it if that's what I want to do.
2455 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2456 if (log)
2457 log->Printf("Hit New Thread Notification breakpoint.");
2458 return false;
2459}
2460
2461
2462bool
2463ProcessGDBRemote::StartNoticingNewThreads()
2464{
2465 static const char *bp_names[] =
2466 {
2467 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002468 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002469 "_pthread_start",
2470 NULL
2471 };
2472
2473 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2474 size_t num_bps = m_thread_observation_bps.size();
2475 if (num_bps != 0)
2476 {
2477 for (int i = 0; i < num_bps; i++)
2478 {
2479 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2480 if (break_sp)
2481 {
2482 if (log)
2483 log->Printf("Enabled noticing new thread breakpoint.");
2484 break_sp->SetEnabled(true);
2485 }
2486 }
2487 }
2488 else
2489 {
2490 for (int i = 0; bp_names[i] != NULL; i++)
2491 {
2492 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2493 if (breakpoint)
2494 {
2495 if (log)
2496 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2497 m_thread_observation_bps.push_back(breakpoint->GetID());
2498 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2499 }
2500 else
2501 {
2502 if (log)
2503 log->Printf("Failed to create new thread notification breakpoint.");
2504 return false;
2505 }
2506 }
2507 }
2508
2509 return true;
2510}
2511
2512bool
2513ProcessGDBRemote::StopNoticingNewThreads()
2514{
Jim Inghamff276fe2011-02-08 05:19:01 +00002515 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2516 if (log)
2517 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002518 size_t num_bps = m_thread_observation_bps.size();
2519 if (num_bps != 0)
2520 {
2521 for (int i = 0; i < num_bps; i++)
2522 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002523
2524 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2525 if (break_sp)
2526 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002527 break_sp->SetEnabled(false);
2528 }
2529 }
2530 }
2531 return true;
2532}
2533
2534