blob: 2fd77223740c9fa02bf98eee31473b2fca683e39 [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>
Chris Lattner24943d22010-06-08 16:52:24 +000013#include <sys/types.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <sys/stat.h>
Chris Lattner24943d22010-06-08 16:52:24 +000015
16// C++ Includes
17#include <algorithm>
18#include <map>
19
20// Other libraries and framework includes
21
22#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000023#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/ArchSpec.h"
25#include "lldb/Core/Debugger.h"
26#include "lldb/Core/ConnectionFileDescriptor.h"
27#include "lldb/Core/FileSpec.h"
28#include "lldb/Core/InputReader.h"
29#include "lldb/Core/Module.h"
30#include "lldb/Core/PluginManager.h"
31#include "lldb/Core/State.h"
32#include "lldb/Core/StreamString.h"
33#include "lldb/Core/Timer.h"
34#include "lldb/Host/TimeValue.h"
35#include "lldb/Symbol/ObjectFile.h"
36#include "lldb/Target/DynamicLoader.h"
37#include "lldb/Target/Target.h"
38#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000039#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
41// Project includes
42#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000043#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "GDBRemoteRegisterContext.h"
45#include "ProcessGDBRemote.h"
46#include "ProcessGDBRemoteLog.h"
47#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000048#include "StopInfoMachException.h"
49
Chris Lattner24943d22010-06-08 16:52:24 +000050
Chris Lattner24943d22010-06-08 16:52:24 +000051
52#define DEBUGSERVER_BASENAME "debugserver"
53using namespace lldb;
54using namespace lldb_private;
55
56static inline uint16_t
57get_random_port ()
58{
59 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u;
60}
61
62
63const char *
64ProcessGDBRemote::GetPluginNameStatic()
65{
66 return "process.gdb-remote";
67}
68
69const char *
70ProcessGDBRemote::GetPluginDescriptionStatic()
71{
72 return "GDB Remote protocol based debugging plug-in.";
73}
74
75void
76ProcessGDBRemote::Terminate()
77{
78 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
79}
80
81
82Process*
83ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
84{
85 return new ProcessGDBRemote (target, listener);
86}
87
88bool
89ProcessGDBRemote::CanDebug(Target &target)
90{
91 // For now we are just making sure the file exists for a given module
92 ModuleSP exe_module_sp(target.GetExecutableModule());
93 if (exe_module_sp.get())
94 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +000095 // However, if there is no executable module, we return true since we might be preparing to attach.
96 return true;
Chris Lattner24943d22010-06-08 16:52:24 +000097}
98
99//----------------------------------------------------------------------
100// ProcessGDBRemote constructor
101//----------------------------------------------------------------------
102ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
103 Process (target, listener),
104 m_dynamic_loader_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000105 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000106 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000107 m_gdb_comm(),
108 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000109 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000110 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000111 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000112 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
113 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000114 m_curr_tid (LLDB_INVALID_THREAD_ID),
115 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000116 m_z0_supported (1),
117 m_continue_packet(),
118 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000119 m_packet_timeout (1),
120 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000121 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000122 m_local_debugserver (true),
123 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000124{
125}
126
127//----------------------------------------------------------------------
128// Destructor
129//----------------------------------------------------------------------
130ProcessGDBRemote::~ProcessGDBRemote()
131{
Greg Claytonff5cac22010-12-13 18:11:18 +0000132 m_dynamic_loader_ap.reset();
133
Greg Clayton75ccf502010-08-21 02:22:51 +0000134 if (m_debugserver_thread != LLDB_INVALID_HOST_THREAD)
135 {
136 Host::ThreadCancel (m_debugserver_thread, NULL);
137 thread_result_t thread_result;
138 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
139 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
140 }
Chris Lattner24943d22010-06-08 16:52:24 +0000141 // m_mach_process.UnregisterNotificationCallbacks (this);
142 Clear();
143}
144
145//----------------------------------------------------------------------
146// PluginInterface
147//----------------------------------------------------------------------
148const char *
149ProcessGDBRemote::GetPluginName()
150{
151 return "Process debugging plug-in that uses the GDB remote protocol";
152}
153
154const char *
155ProcessGDBRemote::GetShortPluginName()
156{
157 return GetPluginNameStatic();
158}
159
160uint32_t
161ProcessGDBRemote::GetPluginVersion()
162{
163 return 1;
164}
165
166void
167ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
168{
169 strm->Printf("TODO: fill this in\n");
170}
171
172Error
173ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
174{
175 Error error;
176 error.SetErrorString("No plug-in commands are currently supported.");
177 return error;
178}
179
180Log *
181ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
182{
183 return NULL;
184}
185
186void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000187ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000188{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000189 if (!force && m_register_info.GetNumRegisters() > 0)
190 return;
191
192 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000193 m_register_info.Clear();
194 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
195 uint32_t reg_offset = 0;
196 uint32_t reg_num = 0;
197 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
198 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000199 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
200 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000201 StringExtractorGDBRemote response;
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000202 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000203 {
204 packet_type = response.GetType();
205 if (packet_type == StringExtractorGDBRemote::eResponse)
206 {
207 std::string name;
208 std::string value;
209 ConstString reg_name;
210 ConstString alt_name;
211 ConstString set_name;
212 RegisterInfo reg_info = { NULL, // Name
213 NULL, // Alt name
214 0, // byte size
215 reg_offset, // offset
216 eEncodingUint, // encoding
217 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000218 {
219 LLDB_INVALID_REGNUM, // GCC reg num
220 LLDB_INVALID_REGNUM, // DWARF reg num
221 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000222 reg_num, // GDB reg num
223 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000224 }
225 };
226
227 while (response.GetNameColonValue(name, value))
228 {
229 if (name.compare("name") == 0)
230 {
231 reg_name.SetCString(value.c_str());
232 }
233 else if (name.compare("alt-name") == 0)
234 {
235 alt_name.SetCString(value.c_str());
236 }
237 else if (name.compare("bitsize") == 0)
238 {
239 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
240 }
241 else if (name.compare("offset") == 0)
242 {
243 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000244 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000245 {
246 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000247 }
248 }
249 else if (name.compare("encoding") == 0)
250 {
251 if (value.compare("uint") == 0)
252 reg_info.encoding = eEncodingUint;
253 else if (value.compare("sint") == 0)
254 reg_info.encoding = eEncodingSint;
255 else if (value.compare("ieee754") == 0)
256 reg_info.encoding = eEncodingIEEE754;
257 else if (value.compare("vector") == 0)
258 reg_info.encoding = eEncodingVector;
259 }
260 else if (name.compare("format") == 0)
261 {
262 if (value.compare("binary") == 0)
263 reg_info.format = eFormatBinary;
264 else if (value.compare("decimal") == 0)
265 reg_info.format = eFormatDecimal;
266 else if (value.compare("hex") == 0)
267 reg_info.format = eFormatHex;
268 else if (value.compare("float") == 0)
269 reg_info.format = eFormatFloat;
270 else if (value.compare("vector-sint8") == 0)
271 reg_info.format = eFormatVectorOfSInt8;
272 else if (value.compare("vector-uint8") == 0)
273 reg_info.format = eFormatVectorOfUInt8;
274 else if (value.compare("vector-sint16") == 0)
275 reg_info.format = eFormatVectorOfSInt16;
276 else if (value.compare("vector-uint16") == 0)
277 reg_info.format = eFormatVectorOfUInt16;
278 else if (value.compare("vector-sint32") == 0)
279 reg_info.format = eFormatVectorOfSInt32;
280 else if (value.compare("vector-uint32") == 0)
281 reg_info.format = eFormatVectorOfUInt32;
282 else if (value.compare("vector-float32") == 0)
283 reg_info.format = eFormatVectorOfFloat32;
284 else if (value.compare("vector-uint128") == 0)
285 reg_info.format = eFormatVectorOfUInt128;
286 }
287 else if (name.compare("set") == 0)
288 {
289 set_name.SetCString(value.c_str());
290 }
291 else if (name.compare("gcc") == 0)
292 {
293 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
294 }
295 else if (name.compare("dwarf") == 0)
296 {
297 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
298 }
299 else if (name.compare("generic") == 0)
300 {
301 if (value.compare("pc") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
303 else if (value.compare("sp") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
305 else if (value.compare("fp") == 0)
306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
307 else if (value.compare("ra") == 0)
308 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
309 else if (value.compare("flags") == 0)
310 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
311 }
312 }
313
Jason Molenda53d96862010-06-11 23:44:18 +0000314 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000315 assert (reg_info.byte_size != 0);
316 reg_offset += reg_info.byte_size;
317 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
318 }
319 }
320 else
321 {
322 packet_type = StringExtractorGDBRemote::eError;
323 }
324 }
325
326 if (reg_num == 0)
327 {
328 // We didn't get anything. See if we are debugging ARM and fill with
329 // a hard coded register set until we can get an updated debugserver
330 // down on the devices.
331 ArchSpec arm_arch ("arm");
332 if (GetTarget().GetArchitecture() == arm_arch)
333 m_register_info.HardcodeARMRegisters();
334 }
335 m_register_info.Finalize ();
336}
337
338Error
339ProcessGDBRemote::WillLaunch (Module* module)
340{
341 return WillLaunchOrAttach ();
342}
343
344Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000345ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000346{
347 return WillLaunchOrAttach ();
348}
349
350Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000351ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000352{
353 return WillLaunchOrAttach ();
354}
355
356Error
357ProcessGDBRemote::WillLaunchOrAttach ()
358{
359 Error error;
360 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
361 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
362
363 if (m_dynamic_loader_ap.get() == NULL)
364 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
365 m_stdio_communication.Clear ();
366
367 return error;
368}
369
370//----------------------------------------------------------------------
371// Process Control
372//----------------------------------------------------------------------
373Error
374ProcessGDBRemote::DoLaunch
375(
376 Module* module,
377 char const *argv[],
378 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000379 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000380 const char *stdin_path,
381 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000382 const char *stderr_path,
383 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000384)
385{
Greg Clayton4b407112010-09-30 21:49:03 +0000386 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000387 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
388 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
389 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000390
391 ObjectFile * object_file = module->GetObjectFile();
392 if (object_file)
393 {
394 ArchSpec inferior_arch(module->GetArchitecture());
395 char host_port[128];
396 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
397
Greg Clayton23cf0c72010-11-08 04:29:11 +0000398 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000399 bool start_debugserver_with_inferior_args = false;
400 if (start_debugserver_with_inferior_args)
401 {
402 // We want to launch debugserver with the inferior program and its
403 // arguments on the command line. We should only do this if we
404 // the GDB server we are talking to doesn't support the 'A' packet.
405 error = StartDebugserverProcess (host_port,
406 argv,
407 envp,
Greg Claytonde915be2011-01-23 05:56:20 +0000408 stdin_path,
409 stdout_path,
410 stderr_path,
411 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000412 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000413 LLDB_INVALID_PROCESS_ID,
414 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000415 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000416 inferior_arch);
417 if (error.Fail())
418 return error;
419
420 error = ConnectToDebugserver (host_port);
421 if (error.Success())
422 {
423 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
424 }
425 }
426 else
427 {
428 error = StartDebugserverProcess (host_port,
429 NULL,
430 NULL,
Greg Claytonde915be2011-01-23 05:56:20 +0000431 stdin_path,
432 stdout_path,
433 stderr_path,
434 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000435 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000436 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000437 NULL,
438 false,
Caroline Ticebd666012010-12-03 18:46:09 +0000439 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000440 inferior_arch);
441 if (error.Fail())
442 return error;
443
444 error = ConnectToDebugserver (host_port);
445 if (error.Success())
446 {
447 // Send the environment and the program + arguments after we connect
448 if (envp)
449 {
450 const char *env_entry;
451 for (int i=0; (env_entry = envp[i]); ++i)
452 {
453 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
454 break;
455 }
456 }
457
Greg Clayton960d6a42010-08-03 00:35:52 +0000458 // FIXME: convert this to use the new set/show variables when they are available
459#if 0
460 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
461 {
462 const uint32_t attach_debugserver_secs = 10;
463 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
464 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
465 {
466 printf ("%i\n", attach_debugserver_secs - i);
467 sleep (1);
468 }
469 }
470#endif
471
Chris Lattner24943d22010-06-08 16:52:24 +0000472 const uint32_t arg_timeout_seconds = 10;
473 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
474 if (arg_packet_err == 0)
475 {
476 std::string error_str;
477 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
478 {
479 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
480 }
481 else
482 {
483 error.SetErrorString (error_str.c_str());
484 }
485 }
486 else
487 {
488 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
489 }
490
491 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
492 }
493 }
494
495 if (GetID() == LLDB_INVALID_PROCESS_ID)
496 {
497 KillDebugserverProcess ();
498 return error;
499 }
500
501 StringExtractorGDBRemote response;
502 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
503 SetPrivateState (SetThreadStopInfo (response));
504
505 }
506 else
507 {
508 // Set our user ID to an invalid process ID.
509 SetID(LLDB_INVALID_PROCESS_ID);
510 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
511 }
Chris Lattner24943d22010-06-08 16:52:24 +0000512 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000513
Chris Lattner24943d22010-06-08 16:52:24 +0000514}
515
516
517Error
518ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
519{
520 Error error;
521 // Sleep and wait a bit for debugserver to start to listen...
522 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
523 if (conn_ap.get())
524 {
525 std::string connect_url("connect://");
526 connect_url.append (host_port);
527 const uint32_t max_retry_count = 50;
528 uint32_t retry_count = 0;
529 while (!m_gdb_comm.IsConnected())
530 {
531 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
532 {
533 m_gdb_comm.SetConnection (conn_ap.release());
534 break;
535 }
536 retry_count++;
537
538 if (retry_count >= max_retry_count)
539 break;
540
541 usleep (100000);
542 }
543 }
544
545 if (!m_gdb_comm.IsConnected())
546 {
547 if (error.Success())
548 error.SetErrorString("not connected to remote gdb server");
549 return error;
550 }
551
552 m_gdb_comm.SetAckMode (true);
553 if (m_gdb_comm.StartReadThread(&error))
554 {
555 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000556 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000557
558 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000559 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
560 this,
561 m_debugserver_pid,
562 false);
563
Chris Lattner24943d22010-06-08 16:52:24 +0000564 StringExtractorGDBRemote response;
565 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
566 {
567 if (response.IsOKPacket())
568 m_gdb_comm.SetAckMode (false);
569 }
Greg Claytonc71899e2011-01-18 19:36:39 +0000570
571 if (m_gdb_comm.SendPacketAndWaitForResponse("QThreadSuffixSupported", response, 1, false))
572 {
573 if (response.IsOKPacket())
574 m_gdb_comm.SetThreadSuffixSupported (true);
575 }
576
Chris Lattner24943d22010-06-08 16:52:24 +0000577 }
578 return error;
579}
580
581void
582ProcessGDBRemote::DidLaunchOrAttach ()
583{
584 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
585 if (GetID() == LLDB_INVALID_PROCESS_ID)
586 {
587 m_dynamic_loader_ap.reset();
588 }
589 else
590 {
591 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
592
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000593 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000594
595 m_byte_order = m_gdb_comm.GetByteOrder();
596
Chris Lattner24943d22010-06-08 16:52:24 +0000597 StreamString strm;
598
599 ArchSpec inferior_arch;
600 // See if the GDB server supports the qHostInfo information
601 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
602 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Clayton20d338f2010-11-18 05:57:03 +0000603 ArchSpec arch_spec (GetTarget().GetArchitecture());
Chris Lattner24943d22010-06-08 16:52:24 +0000604
Jim Ingham7508e732010-08-09 23:31:02 +0000605 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000606 {
607 // For ARM we can't trust the arch of the process as it could
608 // have an armv6 object file, but be running on armv7 kernel.
609 inferior_arch = m_gdb_comm.GetHostArchitecture();
610 }
611
612 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000613 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000614
615 if (vendor == NULL)
616 vendor = Host::GetVendorString().AsCString("apple");
617
618 if (os_type == NULL)
619 os_type = Host::GetOSString().AsCString("darwin");
620
621 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
622
623 std::transform (strm.GetString().begin(),
624 strm.GetString().end(),
625 strm.GetString().begin(),
626 ::tolower);
627
628 m_target_triple.SetCString(strm.GetString().c_str());
629 }
630}
631
632void
633ProcessGDBRemote::DidLaunch ()
634{
635 DidLaunchOrAttach ();
636 if (m_dynamic_loader_ap.get())
637 m_dynamic_loader_ap->DidLaunch();
638}
639
640Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000641ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000642{
643 Error error;
644 // Clear out and clean up from any current state
645 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000646 ArchSpec arch_spec = GetTarget().GetArchitecture();
647
Greg Claytone005f2c2010-11-06 01:53:30 +0000648 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000649
650
Chris Lattner24943d22010-06-08 16:52:24 +0000651 if (attach_pid != LLDB_INVALID_PROCESS_ID)
652 {
Chris Lattner24943d22010-06-08 16:52:24 +0000653 char host_port[128];
654 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000655 error = StartDebugserverProcess (host_port, // debugserver_url
656 NULL, // inferior_argv
657 NULL, // inferior_envp
658 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000659 NULL, // stdout_path
660 NULL, // stderr_path
661 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000662 false, // launch_process == false (we are attaching)
663 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
664 NULL, // Don't send any attach by process name option to debugserver
665 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000666 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000667 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000668
669 if (error.Fail())
670 {
671 const char *error_string = error.AsCString();
672 if (error_string == NULL)
673 error_string = "unable to launch " DEBUGSERVER_BASENAME;
674
675 SetExitStatus (-1, error_string);
676 }
677 else
678 {
679 error = ConnectToDebugserver (host_port);
680 if (error.Success())
681 {
682 char packet[64];
683 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000684
685 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000686 }
687 }
688 }
Chris Lattner24943d22010-06-08 16:52:24 +0000689 return error;
690}
691
692size_t
693ProcessGDBRemote::AttachInputReaderCallback
694(
695 void *baton,
696 InputReader *reader,
697 lldb::InputReaderAction notification,
698 const char *bytes,
699 size_t bytes_len
700)
701{
702 if (notification == eInputReaderGotToken)
703 {
704 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
705 if (gdb_process->m_waiting_for_attach)
706 gdb_process->m_waiting_for_attach = false;
707 reader->SetIsDone(true);
708 return 1;
709 }
710 return 0;
711}
712
713Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000714ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000715{
716 Error error;
717 // Clear out and clean up from any current state
718 Clear();
719 // HACK: require arch be set correctly at the target level until we can
720 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000721
Greg Claytone005f2c2010-11-06 01:53:30 +0000722 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000723 if (process_name && process_name[0])
724 {
Chris Lattner24943d22010-06-08 16:52:24 +0000725 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000726 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000727 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000728 error = StartDebugserverProcess (host_port, // debugserver_url
729 NULL, // inferior_argv
730 NULL, // inferior_envp
731 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000732 NULL, // stdout_path
733 NULL, // stderr_path
734 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000735 false, // launch_process == false (we are attaching)
736 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
737 NULL, // Don't send any attach by process name option to debugserver
738 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000739 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000740 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000741 if (error.Fail())
742 {
743 const char *error_string = error.AsCString();
744 if (error_string == NULL)
745 error_string = "unable to launch " DEBUGSERVER_BASENAME;
746
747 SetExitStatus (-1, error_string);
748 }
749 else
750 {
751 error = ConnectToDebugserver (host_port);
752 if (error.Success())
753 {
754 StreamString packet;
755
Chris Lattner24943d22010-06-08 16:52:24 +0000756 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000757 packet.PutCString("vAttachWait");
758 else
759 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000760 packet.PutChar(';');
Greg Claytoncd548032011-02-01 01:31:41 +0000761 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000762
763 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
Chris Lattner24943d22010-06-08 16:52:24 +0000764
Chris Lattner24943d22010-06-08 16:52:24 +0000765 }
766 }
767 }
Chris Lattner24943d22010-06-08 16:52:24 +0000768 return error;
769}
770
Chris Lattner24943d22010-06-08 16:52:24 +0000771
772void
773ProcessGDBRemote::DidAttach ()
774{
Chris Lattner24943d22010-06-08 16:52:24 +0000775 if (m_dynamic_loader_ap.get())
776 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000777 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000778}
779
780Error
781ProcessGDBRemote::WillResume ()
782{
783 m_continue_packet.Clear();
784 // Start the continue packet we will use to run the target. Each thread
785 // will append what it is supposed to be doing to this packet when the
786 // ThreadList::WillResume() is called. If a thread it supposed
787 // to stay stopped, then don't append anything to this string.
788 m_continue_packet.Printf("vCont");
789 return Error();
790}
791
792Error
793ProcessGDBRemote::DoResume ()
794{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000795 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000796 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000797
798 Listener listener ("gdb-remote.resume-packet-sent");
799 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
800 {
801 EventSP event_sp;
802 TimeValue timeout;
803 timeout = TimeValue::Now();
804 timeout.OffsetWithSeconds (5);
805 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
806
807 if (listener.WaitForEvent (&timeout, event_sp) == false)
808 error.SetErrorString("Resume timed out.");
809 }
810
Jim Ingham3ae449a2010-11-17 02:32:00 +0000811 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000812}
813
814size_t
815ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
816{
817 const uint8_t *trap_opcode = NULL;
818 uint32_t trap_opcode_size = 0;
819
820 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
821 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
822 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
823 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
824
Jim Ingham7508e732010-08-09 23:31:02 +0000825 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000826 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000827 {
Greg Claytoncf015052010-06-11 03:25:34 +0000828 case ArchSpec::eCPU_i386:
829 case ArchSpec::eCPU_x86_64:
830 trap_opcode = g_i386_breakpoint_opcode;
831 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
832 break;
833
834 case ArchSpec::eCPU_arm:
835 // TODO: fill this in for ARM. We need to dig up the symbol for
836 // the address in the breakpoint locaiton and figure out if it is
837 // an ARM or Thumb breakpoint.
838 trap_opcode = g_arm_breakpoint_opcode;
839 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
840 break;
841
842 case ArchSpec::eCPU_ppc:
843 case ArchSpec::eCPU_ppc64:
844 trap_opcode = g_ppc_breakpoint_opcode;
845 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
846 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000847
Greg Claytoncf015052010-06-11 03:25:34 +0000848 default:
849 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
850 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000851 }
852
853 if (trap_opcode && trap_opcode_size)
854 {
855 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
856 return trap_opcode_size;
857 }
858 return 0;
859}
860
861uint32_t
862ProcessGDBRemote::UpdateThreadListIfNeeded ()
863{
864 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000865 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000866 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000867 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
868
Greg Clayton5205f0b2010-09-03 17:10:42 +0000869 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000870 const uint32_t stop_id = GetStopID();
871 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
872 {
873 // Update the thread list's stop id immediately so we don't recurse into this function.
874 ThreadList curr_thread_list (this);
875 curr_thread_list.SetStopID(stop_id);
876
877 Error err;
878 StringExtractorGDBRemote response;
879 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
880 response.IsNormalPacket();
881 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
882 {
883 char ch = response.GetChar();
884 if (ch == 'l')
885 break;
886 if (ch == 'm')
887 {
888 do
889 {
890 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
891
892 if (tid != LLDB_INVALID_THREAD_ID)
893 {
894 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +0000895 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000896 thread_sp.reset (new ThreadGDBRemote (*this, tid));
897 curr_thread_list.AddThread(thread_sp);
898 }
899
900 ch = response.GetChar();
901 } while (ch == ',');
902 }
903 }
904
905 m_thread_list = curr_thread_list;
906
907 SetThreadStopInfo (m_last_stop_packet);
908 }
909 return GetThreadList().GetSize(false);
910}
911
912
913StateType
914ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
915{
916 const char stop_type = stop_packet.GetChar();
917 switch (stop_type)
918 {
919 case 'T':
920 case 'S':
921 {
922 // Stop with signal and thread info
923 const uint8_t signo = stop_packet.GetHexU8();
924 std::string name;
925 std::string value;
926 std::string thread_name;
927 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +0000928 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +0000929 uint32_t tid = LLDB_INVALID_THREAD_ID;
930 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
931 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +0000932 ThreadSP thread_sp;
933
Chris Lattner24943d22010-06-08 16:52:24 +0000934 while (stop_packet.GetNameColonValue(name, value))
935 {
936 if (name.compare("metype") == 0)
937 {
938 // exception type in big endian hex
939 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
940 }
941 else if (name.compare("mecount") == 0)
942 {
943 // exception count in big endian hex
944 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
945 }
946 else if (name.compare("medata") == 0)
947 {
948 // exception data in big endian hex
949 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
950 }
951 else if (name.compare("thread") == 0)
952 {
953 // thread in big endian hex
954 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytona875b642011-01-09 21:07:35 +0000955 thread_sp = m_thread_list.FindThreadByID(tid, false);
Chris Lattner24943d22010-06-08 16:52:24 +0000956 }
Greg Clayton4862fa22011-01-08 03:17:57 +0000957 else if (name.compare("hexname") == 0)
958 {
959 StringExtractor name_extractor;
960 // Swap "value" over into "name_extractor"
961 name_extractor.GetStringRef().swap(value);
962 // Now convert the HEX bytes into a string value
963 name_extractor.GetHexByteString (value);
964 thread_name.swap (value);
965 }
Chris Lattner24943d22010-06-08 16:52:24 +0000966 else if (name.compare("name") == 0)
967 {
968 thread_name.swap (value);
969 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +0000970 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000971 {
972 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
973 }
Greg Claytona875b642011-01-09 21:07:35 +0000974 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
975 {
976 // We have a register number that contains an expedited
977 // register value. Lets supply this register to our thread
978 // so it won't have to go and read it.
979 if (thread_sp)
980 {
981 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
982
983 if (reg != UINT32_MAX)
984 {
985 StringExtractor reg_value_extractor;
986 // Swap "value" over into "reg_value_extractor"
987 reg_value_extractor.GetStringRef().swap(value);
988 static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor);
989 }
990 }
991 }
Chris Lattner24943d22010-06-08 16:52:24 +0000992 }
Chris Lattner24943d22010-06-08 16:52:24 +0000993
994 if (thread_sp)
995 {
996 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
997
998 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +0000999 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001000 if (exc_type != 0)
1001 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001002 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001003
1004 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1005 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001006 exc_data_size,
1007 exc_data_size >= 1 ? exc_data[0] : 0,
1008 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001009 }
1010 else if (signo)
1011 {
Greg Clayton643ee732010-08-04 01:40:35 +00001012 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001013 }
1014 else
1015 {
Greg Clayton643ee732010-08-04 01:40:35 +00001016 StopInfoSP invalid_stop_info_sp;
1017 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001018 }
1019 }
1020 return eStateStopped;
1021 }
1022 break;
1023
1024 case 'W':
1025 // process exited
1026 return eStateExited;
1027
1028 default:
1029 break;
1030 }
1031 return eStateInvalid;
1032}
1033
1034void
1035ProcessGDBRemote::RefreshStateAfterStop ()
1036{
Jim Ingham7508e732010-08-09 23:31:02 +00001037 // FIXME - add a variable to tell that we're in the middle of attaching if we
1038 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001039 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001040// if (!GetTarget().GetArchitecture().IsValid())
1041// {
1042// Module *exe_module = GetTarget().GetExecutableModule().get();
1043// if (exe_module)
1044// m_arch_spec = exe_module->GetArchitecture();
1045// }
1046
Chris Lattner24943d22010-06-08 16:52:24 +00001047 // Let all threads recover from stopping and do any clean up based
1048 // on the previous thread state (if any).
1049 m_thread_list.RefreshStateAfterStop();
1050
1051 // Discover new threads:
1052 UpdateThreadListIfNeeded ();
1053}
1054
1055Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001056ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001057{
1058 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001059
Greg Claytona4881d02011-01-22 07:12:45 +00001060 bool timed_out = false;
1061 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001062
1063 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001064 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001065 // We are being asked to halt during an attach. We need to just close
1066 // our file handle and debugserver will go away, and we can be done...
1067 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001068 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001069 else
1070 {
1071 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1072 {
1073 if (timed_out)
1074 error.SetErrorString("timed out sending interrupt packet");
1075 else
1076 error.SetErrorString("unknown error sending interrupt packet");
1077 }
1078 }
Chris Lattner24943d22010-06-08 16:52:24 +00001079 return error;
1080}
1081
1082Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001083ProcessGDBRemote::InterruptIfRunning
1084(
1085 bool discard_thread_plans,
1086 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001087 EventSP &stop_event_sp
1088)
Chris Lattner24943d22010-06-08 16:52:24 +00001089{
1090 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001091
Greg Clayton2860ba92011-01-23 19:58:49 +00001092 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1093
Greg Clayton68ca8232011-01-25 02:58:48 +00001094 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001095 const bool is_running = m_gdb_comm.IsRunning();
1096 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001097 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001098 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001099 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001100 is_running);
1101
Greg Clayton2860ba92011-01-23 19:58:49 +00001102 if (discard_thread_plans)
1103 {
1104 if (log)
1105 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1106 m_thread_list.DiscardThreadPlans();
1107 }
1108 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001109 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001110 if (catch_stop_event)
1111 {
1112 if (log)
1113 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1114 PausePrivateStateThread();
1115 paused_private_state_thread = true;
1116 }
1117
Greg Clayton4fb400f2010-09-27 21:07:38 +00001118 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001119 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001120 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001121
Greg Clayton72e1c782011-01-22 23:43:18 +00001122 //m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1123 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001124 {
1125 if (timed_out)
1126 error.SetErrorString("timed out sending interrupt packet");
1127 else
1128 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001129 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001130 ResumePrivateStateThread();
1131 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001132 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001133
Greg Clayton72e1c782011-01-22 23:43:18 +00001134 if (catch_stop_event)
1135 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001136 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001137 TimeValue timeout_time;
1138 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001139 timeout_time.OffsetWithSeconds(5);
1140 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001141
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001142 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001143 if (log)
1144 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001145
Greg Clayton2860ba92011-01-23 19:58:49 +00001146 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001147 error.SetErrorString("unable to verify target stopped");
1148 }
1149
Greg Clayton68ca8232011-01-25 02:58:48 +00001150 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001151 {
1152 if (log)
1153 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001154 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001155 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001156 }
Chris Lattner24943d22010-06-08 16:52:24 +00001157 return error;
1158}
1159
Greg Clayton4fb400f2010-09-27 21:07:38 +00001160Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001161ProcessGDBRemote::WillDetach ()
1162{
Greg Clayton2860ba92011-01-23 19:58:49 +00001163 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1164 if (log)
1165 log->Printf ("ProcessGDBRemote::WillDetach()");
1166
Greg Clayton72e1c782011-01-22 23:43:18 +00001167 bool discard_thread_plans = true;
1168 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001169 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001170 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001171}
1172
1173Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001174ProcessGDBRemote::DoDetach()
1175{
1176 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001177 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001178 if (log)
1179 log->Printf ("ProcessGDBRemote::DoDetach()");
1180
1181 DisableAllBreakpointSites ();
1182
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001183 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001184
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001185 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1186 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001187 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001188 if (response_size)
1189 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1190 else
1191 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001192 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001193 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001194 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001195
Greg Clayton4fb400f2010-09-27 21:07:38 +00001196 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001197 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001198
1199 SetPrivateState (eStateDetached);
1200 ResumePrivateStateThread();
1201
1202 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001203 return error;
1204}
Chris Lattner24943d22010-06-08 16:52:24 +00001205
1206Error
1207ProcessGDBRemote::DoDestroy ()
1208{
1209 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001210 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001211 if (log)
1212 log->Printf ("ProcessGDBRemote::DoDestroy()");
1213
1214 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001215 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001216 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001217 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001218 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001219 // We are being asked to halt during an attach. We need to just close
1220 // our file handle and debugserver will go away, and we can be done...
1221 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001222 }
1223 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001224 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001225
1226 StringExtractorGDBRemote response;
1227 bool send_async = true;
1228 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, 2, send_async))
1229 {
1230 char packet_cmd = response.GetChar(0);
1231
1232 if (packet_cmd == 'W' || packet_cmd == 'X')
1233 {
1234 m_last_stop_packet = response;
1235 SetExitStatus(response.GetHexU8(), NULL);
1236 }
1237 }
1238 else
1239 {
1240 SetExitStatus(SIGABRT, NULL);
1241 //error.SetErrorString("kill packet failed");
1242 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001243 }
1244 }
Chris Lattner24943d22010-06-08 16:52:24 +00001245 StopAsyncThread ();
1246 m_gdb_comm.StopReadThread();
1247 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001248 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001249 return error;
1250}
1251
Chris Lattner24943d22010-06-08 16:52:24 +00001252//------------------------------------------------------------------
1253// Process Queries
1254//------------------------------------------------------------------
1255
1256bool
1257ProcessGDBRemote::IsAlive ()
1258{
Greg Clayton58e844b2010-12-08 05:08:21 +00001259 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001260}
1261
1262addr_t
1263ProcessGDBRemote::GetImageInfoAddress()
1264{
1265 if (!m_gdb_comm.IsRunning())
1266 {
1267 StringExtractorGDBRemote response;
1268 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1269 {
1270 if (response.IsNormalPacket())
1271 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1272 }
1273 }
1274 return LLDB_INVALID_ADDRESS;
1275}
1276
1277DynamicLoader *
1278ProcessGDBRemote::GetDynamicLoader()
1279{
1280 return m_dynamic_loader_ap.get();
1281}
1282
1283//------------------------------------------------------------------
1284// Process Memory
1285//------------------------------------------------------------------
1286size_t
1287ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1288{
1289 if (size > m_max_memory_size)
1290 {
1291 // Keep memory read sizes down to a sane limit. This function will be
1292 // called multiple times in order to complete the task by
1293 // lldb_private::Process so it is ok to do this.
1294 size = m_max_memory_size;
1295 }
1296
1297 char packet[64];
1298 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1299 assert (packet_len + 1 < sizeof(packet));
1300 StringExtractorGDBRemote response;
1301 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1302 {
1303 if (response.IsNormalPacket())
1304 {
1305 error.Clear();
1306 return response.GetHexBytes(buf, size, '\xdd');
1307 }
1308 else if (response.IsErrorPacket())
1309 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1310 else if (response.IsUnsupportedPacket())
1311 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1312 else
1313 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1314 }
1315 else
1316 {
1317 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1318 }
1319 return 0;
1320}
1321
1322size_t
1323ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1324{
1325 StreamString packet;
1326 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001327 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001328 StringExtractorGDBRemote response;
1329 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1330 {
1331 if (response.IsOKPacket())
1332 {
1333 error.Clear();
1334 return size;
1335 }
1336 else if (response.IsErrorPacket())
1337 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1338 else if (response.IsUnsupportedPacket())
1339 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1340 else
1341 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1342 }
1343 else
1344 {
1345 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1346 }
1347 return 0;
1348}
1349
1350lldb::addr_t
1351ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1352{
1353 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1354 if (allocated_addr == LLDB_INVALID_ADDRESS)
1355 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1356 else
1357 error.Clear();
1358 return allocated_addr;
1359}
1360
1361Error
1362ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1363{
1364 Error error;
1365 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1366 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1367 return error;
1368}
1369
1370
1371//------------------------------------------------------------------
1372// Process STDIO
1373//------------------------------------------------------------------
1374
1375size_t
1376ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1377{
1378 Mutex::Locker locker(m_stdio_mutex);
1379 size_t bytes_available = m_stdout_data.size();
1380 if (bytes_available > 0)
1381 {
1382 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1383 if (bytes_available > buf_size)
1384 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001385 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001386 m_stdout_data.erase(0, buf_size);
1387 bytes_available = buf_size;
1388 }
1389 else
1390 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001391 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001392 m_stdout_data.clear();
1393
1394 //ResetEventBits(eBroadcastBitSTDOUT);
1395 }
1396 }
1397 return bytes_available;
1398}
1399
1400size_t
1401ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1402{
1403 // Can we get STDERR through the remote protocol?
1404 return 0;
1405}
1406
1407size_t
1408ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1409{
1410 if (m_stdio_communication.IsConnected())
1411 {
1412 ConnectionStatus status;
1413 m_stdio_communication.Write(src, src_len, status, NULL);
1414 }
1415 return 0;
1416}
1417
1418Error
1419ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1420{
1421 Error error;
1422 assert (bp_site != NULL);
1423
Greg Claytone005f2c2010-11-06 01:53:30 +00001424 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001425 user_id_t site_id = bp_site->GetID();
1426 const addr_t addr = bp_site->GetLoadAddress();
1427 if (log)
1428 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1429
1430 if (bp_site->IsEnabled())
1431 {
1432 if (log)
1433 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1434 return error;
1435 }
1436 else
1437 {
1438 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1439
1440 if (bp_site->HardwarePreferred())
1441 {
1442 // Try and set hardware breakpoint, and if that fails, fall through
1443 // and set a software breakpoint?
1444 }
1445
1446 if (m_z0_supported)
1447 {
1448 char packet[64];
1449 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1450 assert (packet_len + 1 < sizeof(packet));
1451 StringExtractorGDBRemote response;
1452 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1453 {
1454 if (response.IsUnsupportedPacket())
1455 {
1456 // Disable z packet support and try again
1457 m_z0_supported = 0;
1458 return EnableBreakpoint (bp_site);
1459 }
1460 else if (response.IsOKPacket())
1461 {
1462 bp_site->SetEnabled(true);
1463 bp_site->SetType (BreakpointSite::eExternal);
1464 return error;
1465 }
1466 else
1467 {
1468 uint8_t error_byte = response.GetError();
1469 if (error_byte)
1470 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1471 }
1472 }
1473 }
1474 else
1475 {
1476 return EnableSoftwareBreakpoint (bp_site);
1477 }
1478 }
1479
1480 if (log)
1481 {
1482 const char *err_string = error.AsCString();
1483 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1484 bp_site->GetLoadAddress(),
1485 err_string ? err_string : "NULL");
1486 }
1487 // We shouldn't reach here on a successful breakpoint enable...
1488 if (error.Success())
1489 error.SetErrorToGenericError();
1490 return error;
1491}
1492
1493Error
1494ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1495{
1496 Error error;
1497 assert (bp_site != NULL);
1498 addr_t addr = bp_site->GetLoadAddress();
1499 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001500 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001501 if (log)
1502 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1503
1504 if (bp_site->IsEnabled())
1505 {
1506 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1507
1508 if (bp_site->IsHardware())
1509 {
1510 // TODO: disable hardware breakpoint...
1511 }
1512 else
1513 {
1514 if (m_z0_supported)
1515 {
1516 char packet[64];
1517 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1518 assert (packet_len + 1 < sizeof(packet));
1519 StringExtractorGDBRemote response;
1520 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1521 {
1522 if (response.IsUnsupportedPacket())
1523 {
1524 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1525 }
1526 else if (response.IsOKPacket())
1527 {
1528 if (log)
1529 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1530 bp_site->SetEnabled(false);
1531 return error;
1532 }
1533 else
1534 {
1535 uint8_t error_byte = response.GetError();
1536 if (error_byte)
1537 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1538 }
1539 }
1540 }
1541 else
1542 {
1543 return DisableSoftwareBreakpoint (bp_site);
1544 }
1545 }
1546 }
1547 else
1548 {
1549 if (log)
1550 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1551 return error;
1552 }
1553
1554 if (error.Success())
1555 error.SetErrorToGenericError();
1556 return error;
1557}
1558
1559Error
1560ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1561{
1562 Error error;
1563 if (wp)
1564 {
1565 user_id_t watchID = wp->GetID();
1566 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001567 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001568 if (log)
1569 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1570 if (wp->IsEnabled())
1571 {
1572 if (log)
1573 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1574 return error;
1575 }
1576 else
1577 {
1578 // Pass down an appropriate z/Z packet...
1579 error.SetErrorString("watchpoints not supported");
1580 }
1581 }
1582 else
1583 {
1584 error.SetErrorString("Watchpoint location argument was NULL.");
1585 }
1586 if (error.Success())
1587 error.SetErrorToGenericError();
1588 return error;
1589}
1590
1591Error
1592ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1593{
1594 Error error;
1595 if (wp)
1596 {
1597 user_id_t watchID = wp->GetID();
1598
Greg Claytone005f2c2010-11-06 01:53:30 +00001599 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001600
1601 addr_t addr = wp->GetLoadAddress();
1602 if (log)
1603 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1604
1605 if (wp->IsHardware())
1606 {
1607 // Pass down an appropriate z/Z packet...
1608 error.SetErrorString("watchpoints not supported");
1609 }
1610 // TODO: clear software watchpoints if we implement them
1611 }
1612 else
1613 {
1614 error.SetErrorString("Watchpoint location argument was NULL.");
1615 }
1616 if (error.Success())
1617 error.SetErrorToGenericError();
1618 return error;
1619}
1620
1621void
1622ProcessGDBRemote::Clear()
1623{
1624 m_flags = 0;
1625 m_thread_list.Clear();
1626 {
1627 Mutex::Locker locker(m_stdio_mutex);
1628 m_stdout_data.clear();
1629 }
Chris Lattner24943d22010-06-08 16:52:24 +00001630}
1631
1632Error
1633ProcessGDBRemote::DoSignal (int signo)
1634{
1635 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001636 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001637 if (log)
1638 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1639
1640 if (!m_gdb_comm.SendAsyncSignal (signo))
1641 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1642 return error;
1643}
1644
Caroline Tice861efb32010-11-16 05:07:41 +00001645//void
1646//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1647//{
1648// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1649// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1650//}
Chris Lattner24943d22010-06-08 16:52:24 +00001651
Caroline Tice861efb32010-11-16 05:07:41 +00001652//void
1653//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1654//{
1655// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1656// Mutex::Locker locker(m_stdio_mutex);
1657// m_stdout_data.append(s, len);
1658//
1659// // FIXME: Make a real data object for this and put it out.
1660// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1661//}
Chris Lattner24943d22010-06-08 16:52:24 +00001662
1663
1664Error
1665ProcessGDBRemote::StartDebugserverProcess
1666(
1667 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1668 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1669 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Claytonde915be2011-01-23 05:56:20 +00001670 const char *stdin_path,
1671 const char *stdout_path,
1672 const char *stderr_path,
1673 const char *working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001674 bool launch_process, // Set to true if we are going to be launching a the process
1675 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID send this pid as an argument to debugserver
Chris Lattner24943d22010-06-08 16:52:24 +00001676 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1677 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001678 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001679 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1680)
1681{
1682 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001683 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1684 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001685 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1686 {
1687 // If we locate debugserver, keep that located version around
1688 static FileSpec g_debugserver_file_spec;
1689
1690 FileSpec debugserver_file_spec;
1691 char debugserver_path[PATH_MAX];
1692
1693 // Always check to see if we have an environment override for the path
1694 // to the debugserver to use and use it if we do.
1695 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1696 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001697 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001698 else
1699 debugserver_file_spec = g_debugserver_file_spec;
1700 bool debugserver_exists = debugserver_file_spec.Exists();
1701 if (!debugserver_exists)
1702 {
1703 // The debugserver binary is in the LLDB.framework/Resources
1704 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001705 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001706 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001707 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001708 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001709 if (debugserver_exists)
1710 {
1711 g_debugserver_file_spec = debugserver_file_spec;
1712 }
1713 else
1714 {
1715 g_debugserver_file_spec.Clear();
1716 debugserver_file_spec.Clear();
1717 }
Chris Lattner24943d22010-06-08 16:52:24 +00001718 }
1719 }
1720
1721 if (debugserver_exists)
1722 {
1723 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1724
1725 m_stdio_communication.Clear();
1726 posix_spawnattr_t attr;
1727
Greg Claytone005f2c2010-11-06 01:53:30 +00001728 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001729
1730 Error local_err; // Errors that don't affect the spawning.
1731 if (log)
1732 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1733 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1734 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001735 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001736 if (error.Fail())
1737 return error;;
1738
1739#if !defined (__arm__)
1740
Greg Clayton24b48ff2010-10-17 22:03:32 +00001741 // We don't need to do this for ARM, and we really shouldn't now
1742 // that we have multiple CPU subtypes and no posix_spawnattr call
1743 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001744 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001745 {
Greg Claytoncf015052010-06-11 03:25:34 +00001746 cpu_type_t cpu = inferior_arch.GetCPUType();
1747 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1748 {
1749 size_t ocount = 0;
1750 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1751 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001752 error.PutToLog(log.get(), "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount);
Chris Lattner24943d22010-06-08 16:52:24 +00001753
Greg Claytoncf015052010-06-11 03:25:34 +00001754 if (error.Fail() != 0 || ocount != 1)
1755 return error;
1756 }
Chris Lattner24943d22010-06-08 16:52:24 +00001757 }
1758
1759#endif
1760
1761 Args debugserver_args;
1762 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001763
Chris Lattner24943d22010-06-08 16:52:24 +00001764 lldb_utility::PseudoTerminal pty;
Greg Claytonde915be2011-01-23 05:56:20 +00001765 const char *stdio_path = NULL;
1766 if (launch_process &&
Caroline Ticee4450f02011-01-28 00:19:58 +00001767 (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) &&
Greg Claytonde915be2011-01-23 05:56:20 +00001768 m_local_debugserver &&
1769 no_stdio == false)
Chris Lattner24943d22010-06-08 16:52:24 +00001770 {
Chris Lattner24943d22010-06-08 16:52:24 +00001771 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Caroline Ticee4450f02011-01-28 00:19:58 +00001772 {
1773 const char *slave_name = pty.GetSlaveName (NULL, 0);
1774 if (stdin_path == NULL
1775 && stdout_path == NULL
1776 && stderr_path == NULL)
1777 stdio_path = slave_name;
1778 else
1779 {
1780 if (stdin_path == NULL)
1781 stdin_path = slave_name;
1782 if (stdout_path == NULL)
1783 stdout_path = slave_name;
1784 if (stderr_path == NULL)
1785 stderr_path = slave_name;
1786 }
1787 }
Chris Lattner24943d22010-06-08 16:52:24 +00001788 }
1789
1790 // Start args with "debugserver /file/path -r --"
1791 debugserver_args.AppendArgument(debugserver_path);
1792 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001793 // use native registers, not the GDB registers
1794 debugserver_args.AppendArgument("--native-regs");
1795 // make debugserver run in its own session so signals generated by
1796 // special terminal key sequences (^C) don't affect debugserver
1797 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001798
Greg Clayton452bf612010-08-31 18:35:14 +00001799 if (disable_aslr)
1800 debugserver_args.AppendArguments("--disable-aslr");
1801
Chris Lattner24943d22010-06-08 16:52:24 +00001802 // Only set the inferior
Greg Claytonde915be2011-01-23 05:56:20 +00001803 if (launch_process)
Chris Lattner24943d22010-06-08 16:52:24 +00001804 {
Greg Claytonde915be2011-01-23 05:56:20 +00001805 if (no_stdio)
1806 debugserver_args.AppendArgument("--no-stdio");
1807 else
1808 {
1809 if (stdin_path && stdout_path && stderr_path &&
1810 strcmp(stdin_path, stdout_path) == 0 &&
1811 strcmp(stdin_path, stderr_path) == 0)
1812 {
1813 stdio_path = stdin_path;
1814 stdin_path = stdout_path = stderr_path = NULL;
1815 }
1816
1817 if (stdio_path)
1818 {
1819 // All file handles to stdin, stdout, stderr are the same...
1820 debugserver_args.AppendArgument("--stdio-path");
1821 debugserver_args.AppendArgument(stdio_path);
1822 }
1823 else
1824 {
1825 if (stdin_path == NULL && (stdout_path || stderr_path))
1826 stdin_path = "/dev/null";
1827
1828 if (stdout_path == NULL && (stdin_path || stderr_path))
1829 stdout_path = "/dev/null";
1830
1831 if (stderr_path == NULL && (stdin_path || stdout_path))
1832 stderr_path = "/dev/null";
1833
1834 if (stdin_path)
1835 {
1836 debugserver_args.AppendArgument("--stdin-path");
1837 debugserver_args.AppendArgument(stdin_path);
1838 }
1839 if (stdout_path)
1840 {
1841 debugserver_args.AppendArgument("--stdout-path");
1842 debugserver_args.AppendArgument(stdout_path);
1843 }
1844 if (stderr_path)
1845 {
1846 debugserver_args.AppendArgument("--stderr-path");
1847 debugserver_args.AppendArgument(stderr_path);
1848 }
1849 }
1850 }
Chris Lattner24943d22010-06-08 16:52:24 +00001851 }
Greg Claytonde915be2011-01-23 05:56:20 +00001852
1853 if (working_dir)
Caroline Ticebd666012010-12-03 18:46:09 +00001854 {
Greg Claytonde915be2011-01-23 05:56:20 +00001855 debugserver_args.AppendArgument("--working-dir");
1856 debugserver_args.AppendArgument(working_dir);
Caroline Ticebd666012010-12-03 18:46:09 +00001857 }
Chris Lattner24943d22010-06-08 16:52:24 +00001858
1859 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1860 if (env_debugserver_log_file)
1861 {
1862 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1863 debugserver_args.AppendArgument(arg_cstr);
1864 }
1865
1866 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1867 if (env_debugserver_log_flags)
1868 {
1869 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1870 debugserver_args.AppendArgument(arg_cstr);
1871 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001872// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001873// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001874
1875 // Now append the program arguments
1876 if (launch_process)
1877 {
1878 if (inferior_argv)
1879 {
1880 // Terminate the debugserver args so we can now append the inferior args
1881 debugserver_args.AppendArgument("--");
1882
1883 for (int i = 0; inferior_argv[i] != NULL; ++i)
1884 debugserver_args.AppendArgument (inferior_argv[i]);
1885 }
1886 else
1887 {
1888 // Will send environment entries with the 'QEnvironment:' packet
1889 // Will send arguments with the 'A' packet
1890 }
1891 }
1892 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1893 {
1894 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1895 debugserver_args.AppendArgument (arg_cstr);
1896 }
1897 else if (attach_name && attach_name[0])
1898 {
1899 if (wait_for_launch)
1900 debugserver_args.AppendArgument ("--waitfor");
1901 else
1902 debugserver_args.AppendArgument ("--attach");
1903 debugserver_args.AppendArgument (attach_name);
1904 }
1905
1906 Error file_actions_err;
1907 posix_spawn_file_actions_t file_actions;
1908#if DONT_CLOSE_DEBUGSERVER_STDIO
1909 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1910#else
1911 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1912 if (file_actions_err.Success())
1913 {
1914 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1915 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1916 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1917 }
1918#endif
1919
1920 if (log)
1921 {
1922 StreamString strm;
1923 debugserver_args.Dump (&strm);
1924 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1925 }
1926
Greg Clayton72e1c782011-01-22 23:43:18 +00001927 error.SetError (::posix_spawnp (&m_debugserver_pid,
1928 debugserver_path,
1929 file_actions_err.Success() ? &file_actions : NULL,
1930 &attr,
1931 debugserver_args.GetArgumentVector(),
1932 (char * const*)inferior_envp),
1933 eErrorTypePOSIX);
1934
Greg Claytone9d0df42010-07-02 01:29:13 +00001935
1936 ::posix_spawnattr_destroy (&attr);
1937
Chris Lattner24943d22010-06-08 16:52:24 +00001938 if (file_actions_err.Success())
1939 ::posix_spawn_file_actions_destroy (&file_actions);
1940
1941 // We have seen some cases where posix_spawnp was returning a valid
1942 // looking pid even when an error was returned, so clear it out
1943 if (error.Fail())
1944 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1945
1946 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001947 error.PutToLog(log.get(), "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", m_debugserver_pid, debugserver_path, NULL, &attr, inferior_argv, inferior_envp);
Chris Lattner24943d22010-06-08 16:52:24 +00001948
Caroline Ticebd666012010-12-03 18:46:09 +00001949 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00001950 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001951 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001952 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001953 }
Chris Lattner24943d22010-06-08 16:52:24 +00001954 }
1955 else
1956 {
1957 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1958 }
1959
1960 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1961 StartAsyncThread ();
1962 }
1963 return error;
1964}
1965
1966bool
1967ProcessGDBRemote::MonitorDebugserverProcess
1968(
1969 void *callback_baton,
1970 lldb::pid_t debugserver_pid,
1971 int signo, // Zero for no signal
1972 int exit_status // Exit value of process if signal is zero
1973)
1974{
1975 // We pass in the ProcessGDBRemote inferior process it and name it
1976 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1977 // pointer value itself, thus we need the double cast...
1978
1979 // "debugserver_pid" argument passed in is the process ID for
1980 // debugserver that we are tracking...
1981
Greg Clayton75ccf502010-08-21 02:22:51 +00001982 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00001983
1984 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1985 if (log)
1986 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
1987
Greg Clayton75ccf502010-08-21 02:22:51 +00001988 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001989 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001990 // Sleep for a half a second to make sure our inferior process has
1991 // time to set its exit status before we set it incorrectly when
1992 // both the debugserver and the inferior process shut down.
1993 usleep (500000);
1994 // If our process hasn't yet exited, debugserver might have died.
1995 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001996 const StateType state = process->GetState();
1997
1998 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1999 state != eStateInvalid &&
2000 state != eStateUnloaded &&
2001 state != eStateExited &&
2002 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002003 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002004 char error_str[1024];
2005 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002006 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002007 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2008 if (signal_cstr)
2009 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002010 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002011 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002012 }
2013 else
2014 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002015 ::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 +00002016 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002017
2018 process->SetExitStatus (-1, error_str);
2019 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002020 // Debugserver has exited we need to let our ProcessGDBRemote
2021 // know that it no longer has a debugserver instance
2022 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2023 // We are returning true to this function below, so we can
2024 // forget about the monitor handle.
2025 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002026 }
2027 return true;
2028}
2029
2030void
2031ProcessGDBRemote::KillDebugserverProcess ()
2032{
2033 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2034 {
2035 ::kill (m_debugserver_pid, SIGINT);
2036 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2037 }
2038}
2039
2040void
2041ProcessGDBRemote::Initialize()
2042{
2043 static bool g_initialized = false;
2044
2045 if (g_initialized == false)
2046 {
2047 g_initialized = true;
2048 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2049 GetPluginDescriptionStatic(),
2050 CreateInstance);
2051
2052 Log::Callbacks log_callbacks = {
2053 ProcessGDBRemoteLog::DisableLog,
2054 ProcessGDBRemoteLog::EnableLog,
2055 ProcessGDBRemoteLog::ListLogCategories
2056 };
2057
2058 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2059 }
2060}
2061
2062bool
2063ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2064{
2065 if (m_curr_tid == tid)
2066 return true;
2067
2068 char packet[32];
2069 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2070 assert (packet_len + 1 < sizeof(packet));
2071 StringExtractorGDBRemote response;
2072 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2073 {
2074 if (response.IsOKPacket())
2075 {
2076 m_curr_tid = tid;
2077 return true;
2078 }
2079 }
2080 return false;
2081}
2082
2083bool
2084ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2085{
2086 if (m_curr_tid_run == tid)
2087 return true;
2088
2089 char packet[32];
Greg Claytonc71899e2011-01-18 19:36:39 +00002090 const int packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002091 assert (packet_len + 1 < sizeof(packet));
2092 StringExtractorGDBRemote response;
2093 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2094 {
2095 if (response.IsOKPacket())
2096 {
2097 m_curr_tid_run = tid;
2098 return true;
2099 }
2100 }
2101 return false;
2102}
2103
2104void
2105ProcessGDBRemote::ResetGDBRemoteState ()
2106{
2107 // Reset and GDB remote state
2108 m_curr_tid = LLDB_INVALID_THREAD_ID;
2109 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2110 m_z0_supported = 1;
2111}
2112
2113
2114bool
2115ProcessGDBRemote::StartAsyncThread ()
2116{
2117 ResetGDBRemoteState ();
2118
Greg Claytone005f2c2010-11-06 01:53:30 +00002119 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002120
2121 if (log)
2122 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2123
2124 // Create a thread that watches our internal state and controls which
2125 // events make it to clients (into the DCProcess event queue).
2126 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2127 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2128}
2129
2130void
2131ProcessGDBRemote::StopAsyncThread ()
2132{
Greg Claytone005f2c2010-11-06 01:53:30 +00002133 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002134
2135 if (log)
2136 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2137
2138 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2139
2140 // Stop the stdio thread
2141 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2142 {
2143 Host::ThreadJoin (m_async_thread, NULL, NULL);
2144 }
2145}
2146
2147
2148void *
2149ProcessGDBRemote::AsyncThread (void *arg)
2150{
2151 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2152
Greg Claytone005f2c2010-11-06 01:53:30 +00002153 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002154 if (log)
2155 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2156
2157 Listener listener ("ProcessGDBRemote::AsyncThread");
2158 EventSP event_sp;
2159 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2160 eBroadcastBitAsyncThreadShouldExit;
2161
2162 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2163 {
2164 bool done = false;
2165 while (!done)
2166 {
Caroline Tice926060e2010-10-29 21:48:37 +00002167 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002168 if (log)
2169 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2170 if (listener.WaitForEvent (NULL, event_sp))
2171 {
2172 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002173 if (log)
2174 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2175
Chris Lattner24943d22010-06-08 16:52:24 +00002176 switch (event_type)
2177 {
2178 case eBroadcastBitAsyncContinue:
2179 {
2180 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2181
2182 if (continue_packet)
2183 {
2184 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2185 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002186 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002187 if (log)
2188 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2189
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002190 if (::strstr (continue_cstr, "vAttach") == NULL)
2191 process->SetPrivateState(eStateRunning);
Chris Lattner24943d22010-06-08 16:52:24 +00002192 StringExtractorGDBRemote response;
2193 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2194
2195 switch (stop_state)
2196 {
2197 case eStateStopped:
2198 case eStateCrashed:
2199 case eStateSuspended:
2200 process->m_last_stop_packet = response;
2201 process->m_last_stop_packet.SetFilePos (0);
2202 process->SetPrivateState (stop_state);
2203 break;
2204
2205 case eStateExited:
2206 process->m_last_stop_packet = response;
2207 process->m_last_stop_packet.SetFilePos (0);
2208 response.SetFilePos(1);
2209 process->SetExitStatus(response.GetHexU8(), NULL);
2210 done = true;
2211 break;
2212
2213 case eStateInvalid:
2214 break;
2215
2216 default:
2217 process->SetPrivateState (stop_state);
2218 break;
2219 }
2220 }
2221 }
2222 break;
2223
2224 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002225 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002226 if (log)
2227 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2228 done = true;
2229 break;
2230
2231 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002232 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002233 if (log)
2234 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2235 done = true;
2236 break;
2237 }
2238 }
2239 else
2240 {
Caroline Tice926060e2010-10-29 21:48:37 +00002241 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002242 if (log)
2243 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2244 done = true;
2245 }
2246 }
2247 }
2248
Caroline Tice926060e2010-10-29 21:48:37 +00002249 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002250 if (log)
2251 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2252
2253 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2254 return NULL;
2255}
2256
Chris Lattner24943d22010-06-08 16:52:24 +00002257const char *
2258ProcessGDBRemote::GetDispatchQueueNameForThread
2259(
2260 addr_t thread_dispatch_qaddr,
2261 std::string &dispatch_queue_name
2262)
2263{
2264 dispatch_queue_name.clear();
2265 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2266 {
2267 // Cache the dispatch_queue_offsets_addr value so we don't always have
2268 // to look it up
2269 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2270 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002271 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2272 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002273 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002274 if (module_sp)
2275 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2276
2277 if (dispatch_queue_offsets_symbol == NULL)
2278 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002279 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002280 if (module_sp)
2281 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2282 }
Chris Lattner24943d22010-06-08 16:52:24 +00002283 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002284 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002285
2286 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2287 return NULL;
2288 }
2289
2290 uint8_t memory_buffer[8];
2291 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2292
2293 // Excerpt from src/queue_private.h
2294 struct dispatch_queue_offsets_s
2295 {
2296 uint16_t dqo_version;
2297 uint16_t dqo_label;
2298 uint16_t dqo_label_size;
2299 } dispatch_queue_offsets;
2300
2301
2302 Error error;
2303 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2304 {
2305 uint32_t data_offset = 0;
2306 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2307 {
2308 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2309 {
2310 data_offset = 0;
2311 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2312 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2313 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2314 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2315 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2316 dispatch_queue_name.erase (bytes_read);
2317 }
2318 }
2319 }
2320 }
2321 if (dispatch_queue_name.empty())
2322 return NULL;
2323 return dispatch_queue_name.c_str();
2324}
2325
Jim Ingham7508e732010-08-09 23:31:02 +00002326uint32_t
2327ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2328{
2329 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2330 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2331 if (m_local_debugserver)
2332 {
2333 return Host::ListProcessesMatchingName (name, matches, pids);
2334 }
2335 else
2336 {
2337 // FIXME: Implement talking to the remote debugserver.
2338 return 0;
2339 }
2340
2341}
Jim Ingham55e01d82011-01-22 01:33:44 +00002342
2343bool
2344ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2345 lldb_private::StoppointCallbackContext *context,
2346 lldb::user_id_t break_id,
2347 lldb::user_id_t break_loc_id)
2348{
2349 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2350 // run so I can stop it if that's what I want to do.
2351 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2352 if (log)
2353 log->Printf("Hit New Thread Notification breakpoint.");
2354 return false;
2355}
2356
2357
2358bool
2359ProcessGDBRemote::StartNoticingNewThreads()
2360{
2361 static const char *bp_names[] =
2362 {
2363 "start_wqthread",
2364 "_pthread_start",
2365 NULL
2366 };
2367
2368 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2369 size_t num_bps = m_thread_observation_bps.size();
2370 if (num_bps != 0)
2371 {
2372 for (int i = 0; i < num_bps; i++)
2373 {
2374 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2375 if (break_sp)
2376 {
2377 if (log)
2378 log->Printf("Enabled noticing new thread breakpoint.");
2379 break_sp->SetEnabled(true);
2380 }
2381 }
2382 }
2383 else
2384 {
2385 for (int i = 0; bp_names[i] != NULL; i++)
2386 {
2387 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2388 if (breakpoint)
2389 {
2390 if (log)
2391 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2392 m_thread_observation_bps.push_back(breakpoint->GetID());
2393 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2394 }
2395 else
2396 {
2397 if (log)
2398 log->Printf("Failed to create new thread notification breakpoint.");
2399 return false;
2400 }
2401 }
2402 }
2403
2404 return true;
2405}
2406
2407bool
2408ProcessGDBRemote::StopNoticingNewThreads()
2409{
2410 size_t num_bps = m_thread_observation_bps.size();
2411 if (num_bps != 0)
2412 {
2413 for (int i = 0; i < num_bps; i++)
2414 {
2415 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2416
2417 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2418 if (break_sp)
2419 {
2420 if (log)
2421 log->Printf ("Disabling new thread notification breakpoint.");
2422 break_sp->SetEnabled(false);
2423 }
2424 }
2425 }
2426 return true;
2427}
2428
2429