blob: 26aa456428153f6cf76a7de74faa3d5f9ddcb97e [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),
122 m_local_debugserver (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000123{
124}
125
126//----------------------------------------------------------------------
127// Destructor
128//----------------------------------------------------------------------
129ProcessGDBRemote::~ProcessGDBRemote()
130{
Greg Claytonff5cac22010-12-13 18:11:18 +0000131 m_dynamic_loader_ap.reset();
132
Greg Clayton75ccf502010-08-21 02:22:51 +0000133 if (m_debugserver_thread != LLDB_INVALID_HOST_THREAD)
134 {
135 Host::ThreadCancel (m_debugserver_thread, NULL);
136 thread_result_t thread_result;
137 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
138 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
139 }
Chris Lattner24943d22010-06-08 16:52:24 +0000140 // m_mach_process.UnregisterNotificationCallbacks (this);
141 Clear();
142}
143
144//----------------------------------------------------------------------
145// PluginInterface
146//----------------------------------------------------------------------
147const char *
148ProcessGDBRemote::GetPluginName()
149{
150 return "Process debugging plug-in that uses the GDB remote protocol";
151}
152
153const char *
154ProcessGDBRemote::GetShortPluginName()
155{
156 return GetPluginNameStatic();
157}
158
159uint32_t
160ProcessGDBRemote::GetPluginVersion()
161{
162 return 1;
163}
164
165void
166ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
167{
168 strm->Printf("TODO: fill this in\n");
169}
170
171Error
172ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
173{
174 Error error;
175 error.SetErrorString("No plug-in commands are currently supported.");
176 return error;
177}
178
179Log *
180ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
181{
182 return NULL;
183}
184
185void
186ProcessGDBRemote::BuildDynamicRegisterInfo ()
187{
188 char register_info_command[64];
189 m_register_info.Clear();
190 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
191 uint32_t reg_offset = 0;
192 uint32_t reg_num = 0;
193 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
194 {
195 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
196 StringExtractorGDBRemote response;
197 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
198 {
199 packet_type = response.GetType();
200 if (packet_type == StringExtractorGDBRemote::eResponse)
201 {
202 std::string name;
203 std::string value;
204 ConstString reg_name;
205 ConstString alt_name;
206 ConstString set_name;
207 RegisterInfo reg_info = { NULL, // Name
208 NULL, // Alt name
209 0, // byte size
210 reg_offset, // offset
211 eEncodingUint, // encoding
212 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000213 {
214 LLDB_INVALID_REGNUM, // GCC reg num
215 LLDB_INVALID_REGNUM, // DWARF reg num
216 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000217 reg_num, // GDB reg num
218 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000219 }
220 };
221
222 while (response.GetNameColonValue(name, value))
223 {
224 if (name.compare("name") == 0)
225 {
226 reg_name.SetCString(value.c_str());
227 }
228 else if (name.compare("alt-name") == 0)
229 {
230 alt_name.SetCString(value.c_str());
231 }
232 else if (name.compare("bitsize") == 0)
233 {
234 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
235 }
236 else if (name.compare("offset") == 0)
237 {
238 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000239 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000240 {
241 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000242 }
243 }
244 else if (name.compare("encoding") == 0)
245 {
246 if (value.compare("uint") == 0)
247 reg_info.encoding = eEncodingUint;
248 else if (value.compare("sint") == 0)
249 reg_info.encoding = eEncodingSint;
250 else if (value.compare("ieee754") == 0)
251 reg_info.encoding = eEncodingIEEE754;
252 else if (value.compare("vector") == 0)
253 reg_info.encoding = eEncodingVector;
254 }
255 else if (name.compare("format") == 0)
256 {
257 if (value.compare("binary") == 0)
258 reg_info.format = eFormatBinary;
259 else if (value.compare("decimal") == 0)
260 reg_info.format = eFormatDecimal;
261 else if (value.compare("hex") == 0)
262 reg_info.format = eFormatHex;
263 else if (value.compare("float") == 0)
264 reg_info.format = eFormatFloat;
265 else if (value.compare("vector-sint8") == 0)
266 reg_info.format = eFormatVectorOfSInt8;
267 else if (value.compare("vector-uint8") == 0)
268 reg_info.format = eFormatVectorOfUInt8;
269 else if (value.compare("vector-sint16") == 0)
270 reg_info.format = eFormatVectorOfSInt16;
271 else if (value.compare("vector-uint16") == 0)
272 reg_info.format = eFormatVectorOfUInt16;
273 else if (value.compare("vector-sint32") == 0)
274 reg_info.format = eFormatVectorOfSInt32;
275 else if (value.compare("vector-uint32") == 0)
276 reg_info.format = eFormatVectorOfUInt32;
277 else if (value.compare("vector-float32") == 0)
278 reg_info.format = eFormatVectorOfFloat32;
279 else if (value.compare("vector-uint128") == 0)
280 reg_info.format = eFormatVectorOfUInt128;
281 }
282 else if (name.compare("set") == 0)
283 {
284 set_name.SetCString(value.c_str());
285 }
286 else if (name.compare("gcc") == 0)
287 {
288 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
289 }
290 else if (name.compare("dwarf") == 0)
291 {
292 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
293 }
294 else if (name.compare("generic") == 0)
295 {
296 if (value.compare("pc") == 0)
297 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
298 else if (value.compare("sp") == 0)
299 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
300 else if (value.compare("fp") == 0)
301 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
302 else if (value.compare("ra") == 0)
303 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
304 else if (value.compare("flags") == 0)
305 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
306 }
307 }
308
Jason Molenda53d96862010-06-11 23:44:18 +0000309 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000310 assert (reg_info.byte_size != 0);
311 reg_offset += reg_info.byte_size;
312 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
313 }
314 }
315 else
316 {
317 packet_type = StringExtractorGDBRemote::eError;
318 }
319 }
320
321 if (reg_num == 0)
322 {
323 // We didn't get anything. See if we are debugging ARM and fill with
324 // a hard coded register set until we can get an updated debugserver
325 // down on the devices.
326 ArchSpec arm_arch ("arm");
327 if (GetTarget().GetArchitecture() == arm_arch)
328 m_register_info.HardcodeARMRegisters();
329 }
330 m_register_info.Finalize ();
331}
332
333Error
334ProcessGDBRemote::WillLaunch (Module* module)
335{
336 return WillLaunchOrAttach ();
337}
338
339Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000340ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000341{
342 return WillLaunchOrAttach ();
343}
344
345Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000346ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000347{
348 return WillLaunchOrAttach ();
349}
350
351Error
352ProcessGDBRemote::WillLaunchOrAttach ()
353{
354 Error error;
355 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
356 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
357
358 if (m_dynamic_loader_ap.get() == NULL)
359 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
360 m_stdio_communication.Clear ();
361
362 return error;
363}
364
365//----------------------------------------------------------------------
366// Process Control
367//----------------------------------------------------------------------
368Error
369ProcessGDBRemote::DoLaunch
370(
371 Module* module,
372 char const *argv[],
373 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000374 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000375 const char *stdin_path,
376 const char *stdout_path,
377 const char *stderr_path
378)
379{
Greg Clayton4b407112010-09-30 21:49:03 +0000380 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000381 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
382 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
383 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000384
385 ObjectFile * object_file = module->GetObjectFile();
386 if (object_file)
387 {
388 ArchSpec inferior_arch(module->GetArchitecture());
389 char host_port[128];
390 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
391
Greg Clayton23cf0c72010-11-08 04:29:11 +0000392 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000393 bool start_debugserver_with_inferior_args = false;
394 if (start_debugserver_with_inferior_args)
395 {
396 // We want to launch debugserver with the inferior program and its
397 // arguments on the command line. We should only do this if we
398 // the GDB server we are talking to doesn't support the 'A' packet.
399 error = StartDebugserverProcess (host_port,
400 argv,
401 envp,
402 NULL, //stdin_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000403 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000404 LLDB_INVALID_PROCESS_ID,
405 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000406 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000407 inferior_arch);
408 if (error.Fail())
409 return error;
410
411 error = ConnectToDebugserver (host_port);
412 if (error.Success())
413 {
414 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
415 }
416 }
417 else
418 {
419 error = StartDebugserverProcess (host_port,
420 NULL,
421 NULL,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000422 NULL, //stdin_path
423 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000424 LLDB_INVALID_PROCESS_ID,
425 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000426 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000427 inferior_arch);
428 if (error.Fail())
429 return error;
430
431 error = ConnectToDebugserver (host_port);
432 if (error.Success())
433 {
434 // Send the environment and the program + arguments after we connect
435 if (envp)
436 {
437 const char *env_entry;
438 for (int i=0; (env_entry = envp[i]); ++i)
439 {
440 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
441 break;
442 }
443 }
444
Greg Clayton960d6a42010-08-03 00:35:52 +0000445 // FIXME: convert this to use the new set/show variables when they are available
446#if 0
447 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
448 {
449 const uint32_t attach_debugserver_secs = 10;
450 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
451 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
452 {
453 printf ("%i\n", attach_debugserver_secs - i);
454 sleep (1);
455 }
456 }
457#endif
458
Chris Lattner24943d22010-06-08 16:52:24 +0000459 const uint32_t arg_timeout_seconds = 10;
460 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
461 if (arg_packet_err == 0)
462 {
463 std::string error_str;
464 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
465 {
466 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
467 }
468 else
469 {
470 error.SetErrorString (error_str.c_str());
471 }
472 }
473 else
474 {
475 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
476 }
477
478 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
479 }
480 }
481
482 if (GetID() == LLDB_INVALID_PROCESS_ID)
483 {
484 KillDebugserverProcess ();
485 return error;
486 }
487
488 StringExtractorGDBRemote response;
489 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
490 SetPrivateState (SetThreadStopInfo (response));
491
492 }
493 else
494 {
495 // Set our user ID to an invalid process ID.
496 SetID(LLDB_INVALID_PROCESS_ID);
497 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
498 }
Chris Lattner24943d22010-06-08 16:52:24 +0000499 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000500
Chris Lattner24943d22010-06-08 16:52:24 +0000501}
502
503
504Error
505ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
506{
507 Error error;
508 // Sleep and wait a bit for debugserver to start to listen...
509 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
510 if (conn_ap.get())
511 {
512 std::string connect_url("connect://");
513 connect_url.append (host_port);
514 const uint32_t max_retry_count = 50;
515 uint32_t retry_count = 0;
516 while (!m_gdb_comm.IsConnected())
517 {
518 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
519 {
520 m_gdb_comm.SetConnection (conn_ap.release());
521 break;
522 }
523 retry_count++;
524
525 if (retry_count >= max_retry_count)
526 break;
527
528 usleep (100000);
529 }
530 }
531
532 if (!m_gdb_comm.IsConnected())
533 {
534 if (error.Success())
535 error.SetErrorString("not connected to remote gdb server");
536 return error;
537 }
538
539 m_gdb_comm.SetAckMode (true);
540 if (m_gdb_comm.StartReadThread(&error))
541 {
542 // Send an initial ack
543 m_gdb_comm.SendAck('+');
544
545 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000546 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
547 this,
548 m_debugserver_pid,
549 false);
550
Chris Lattner24943d22010-06-08 16:52:24 +0000551 StringExtractorGDBRemote response;
552 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
553 {
554 if (response.IsOKPacket())
555 m_gdb_comm.SetAckMode (false);
556 }
Greg Claytonc71899e2011-01-18 19:36:39 +0000557
558 if (m_gdb_comm.SendPacketAndWaitForResponse("QThreadSuffixSupported", response, 1, false))
559 {
560 if (response.IsOKPacket())
561 m_gdb_comm.SetThreadSuffixSupported (true);
562 }
563
Chris Lattner24943d22010-06-08 16:52:24 +0000564 }
565 return error;
566}
567
568void
569ProcessGDBRemote::DidLaunchOrAttach ()
570{
571 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
572 if (GetID() == LLDB_INVALID_PROCESS_ID)
573 {
574 m_dynamic_loader_ap.reset();
575 }
576 else
577 {
578 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
579
Greg Clayton20d338f2010-11-18 05:57:03 +0000580 BuildDynamicRegisterInfo ();
581
582 m_byte_order = m_gdb_comm.GetByteOrder();
583
Chris Lattner24943d22010-06-08 16:52:24 +0000584 StreamString strm;
585
586 ArchSpec inferior_arch;
587 // See if the GDB server supports the qHostInfo information
588 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
589 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Clayton20d338f2010-11-18 05:57:03 +0000590 ArchSpec arch_spec (GetTarget().GetArchitecture());
Chris Lattner24943d22010-06-08 16:52:24 +0000591
Jim Ingham7508e732010-08-09 23:31:02 +0000592 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000593 {
594 // For ARM we can't trust the arch of the process as it could
595 // have an armv6 object file, but be running on armv7 kernel.
596 inferior_arch = m_gdb_comm.GetHostArchitecture();
597 }
598
599 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000600 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000601
602 if (vendor == NULL)
603 vendor = Host::GetVendorString().AsCString("apple");
604
605 if (os_type == NULL)
606 os_type = Host::GetOSString().AsCString("darwin");
607
608 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
609
610 std::transform (strm.GetString().begin(),
611 strm.GetString().end(),
612 strm.GetString().begin(),
613 ::tolower);
614
615 m_target_triple.SetCString(strm.GetString().c_str());
616 }
617}
618
619void
620ProcessGDBRemote::DidLaunch ()
621{
622 DidLaunchOrAttach ();
623 if (m_dynamic_loader_ap.get())
624 m_dynamic_loader_ap->DidLaunch();
625}
626
627Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000628ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000629{
630 Error error;
631 // Clear out and clean up from any current state
632 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000633 ArchSpec arch_spec = GetTarget().GetArchitecture();
634
Greg Claytone005f2c2010-11-06 01:53:30 +0000635 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000636
637
Chris Lattner24943d22010-06-08 16:52:24 +0000638 if (attach_pid != LLDB_INVALID_PROCESS_ID)
639 {
Chris Lattner24943d22010-06-08 16:52:24 +0000640 char host_port[128];
641 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000642 error = StartDebugserverProcess (host_port, // debugserver_url
643 NULL, // inferior_argv
644 NULL, // inferior_envp
645 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000646 false, // launch_process == false (we are attaching)
647 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
648 NULL, // Don't send any attach by process name option to debugserver
649 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000650 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000651 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000652
653 if (error.Fail())
654 {
655 const char *error_string = error.AsCString();
656 if (error_string == NULL)
657 error_string = "unable to launch " DEBUGSERVER_BASENAME;
658
659 SetExitStatus (-1, error_string);
660 }
661 else
662 {
663 error = ConnectToDebugserver (host_port);
664 if (error.Success())
665 {
666 char packet[64];
667 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
668 StringExtractorGDBRemote response;
669 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
670 packet,
671 packet_len,
672 response);
673 switch (stop_state)
674 {
675 case eStateStopped:
676 case eStateCrashed:
677 case eStateSuspended:
678 SetID (attach_pid);
679 m_last_stop_packet = response;
680 m_last_stop_packet.SetFilePos (0);
681 SetPrivateState (stop_state);
682 break;
683
684 case eStateExited:
685 m_last_stop_packet = response;
686 m_last_stop_packet.SetFilePos (0);
687 response.SetFilePos(1);
688 SetExitStatus(response.GetHexU8(), NULL);
689 break;
690
691 default:
692 SetExitStatus(-1, "unable to attach to process");
693 break;
694 }
695
696 }
697 }
698 }
699
700 lldb::pid_t pid = GetID();
701 if (pid == LLDB_INVALID_PROCESS_ID)
702 {
703 KillDebugserverProcess();
704 }
705 return error;
706}
707
708size_t
709ProcessGDBRemote::AttachInputReaderCallback
710(
711 void *baton,
712 InputReader *reader,
713 lldb::InputReaderAction notification,
714 const char *bytes,
715 size_t bytes_len
716)
717{
718 if (notification == eInputReaderGotToken)
719 {
720 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
721 if (gdb_process->m_waiting_for_attach)
722 gdb_process->m_waiting_for_attach = false;
723 reader->SetIsDone(true);
724 return 1;
725 }
726 return 0;
727}
728
729Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000730ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000731{
732 Error error;
733 // Clear out and clean up from any current state
734 Clear();
735 // HACK: require arch be set correctly at the target level until we can
736 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000737
Greg Claytone005f2c2010-11-06 01:53:30 +0000738 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000739 if (process_name && process_name[0])
740 {
Chris Lattner24943d22010-06-08 16:52:24 +0000741 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000742 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000743 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000744 error = StartDebugserverProcess (host_port, // debugserver_url
745 NULL, // inferior_argv
746 NULL, // inferior_envp
747 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000748 false, // launch_process == false (we are attaching)
749 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
750 NULL, // Don't send any attach by process name option to debugserver
751 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000752 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000753 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000754 if (error.Fail())
755 {
756 const char *error_string = error.AsCString();
757 if (error_string == NULL)
758 error_string = "unable to launch " DEBUGSERVER_BASENAME;
759
760 SetExitStatus (-1, error_string);
761 }
762 else
763 {
764 error = ConnectToDebugserver (host_port);
765 if (error.Success())
766 {
767 StreamString packet;
768
Chris Lattner24943d22010-06-08 16:52:24 +0000769 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000770 packet.PutCString("vAttachWait");
771 else
772 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000773 packet.PutChar(';');
774 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
775 StringExtractorGDBRemote response;
776 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
777 packet.GetData(),
778 packet.GetSize(),
779 response);
780 switch (stop_state)
781 {
782 case eStateStopped:
783 case eStateCrashed:
784 case eStateSuspended:
785 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
786 m_last_stop_packet = response;
787 m_last_stop_packet.SetFilePos (0);
788 SetPrivateState (stop_state);
789 break;
790
791 case eStateExited:
792 m_last_stop_packet = response;
793 m_last_stop_packet.SetFilePos (0);
794 response.SetFilePos(1);
795 SetExitStatus(response.GetHexU8(), NULL);
796 break;
797
798 default:
799 SetExitStatus(-1, "unable to attach to process");
800 break;
801 }
802 }
803 }
804 }
805
806 lldb::pid_t pid = GetID();
807 if (pid == LLDB_INVALID_PROCESS_ID)
808 {
809 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000810
811 if (error.Success())
812 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000813 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000814
Chris Lattner24943d22010-06-08 16:52:24 +0000815 return error;
816}
817
818//
819// if (wait_for_launch)
820// {
821// InputReaderSP reader_sp (new InputReader());
822// StreamString instructions;
823// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
824// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
825// this, // baton
826// eInputReaderGranularityByte,
827// NULL, // End token
828// false);
829//
830// StringExtractorGDBRemote response;
831// m_waiting_for_attach = true;
832// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
833// while (m_waiting_for_attach)
834// {
835// // Wait for one second for the stop reply packet
836// if (m_gdb_comm.WaitForPacket(response, 1))
837// {
838// // Got some sort of packet, see if it is the stop reply packet?
839// char ch = response.GetChar(0);
840// if (ch == 'T')
841// {
842// m_waiting_for_attach = false;
843// }
844// }
845// else
846// {
847// // Put a period character every second
848// fputc('.', reader_out_fh);
849// }
850// }
851// }
852// }
853// return GetID();
854//}
855
856void
857ProcessGDBRemote::DidAttach ()
858{
Chris Lattner24943d22010-06-08 16:52:24 +0000859 if (m_dynamic_loader_ap.get())
860 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000861 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000862}
863
864Error
865ProcessGDBRemote::WillResume ()
866{
867 m_continue_packet.Clear();
868 // Start the continue packet we will use to run the target. Each thread
869 // will append what it is supposed to be doing to this packet when the
870 // ThreadList::WillResume() is called. If a thread it supposed
871 // to stay stopped, then don't append anything to this string.
872 m_continue_packet.Printf("vCont");
873 return Error();
874}
875
876Error
877ProcessGDBRemote::DoResume ()
878{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000879 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000880 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000881
882 Listener listener ("gdb-remote.resume-packet-sent");
883 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
884 {
885 EventSP event_sp;
886 TimeValue timeout;
887 timeout = TimeValue::Now();
888 timeout.OffsetWithSeconds (5);
889 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
890
891 if (listener.WaitForEvent (&timeout, event_sp) == false)
892 error.SetErrorString("Resume timed out.");
893 }
894
Jim Ingham3ae449a2010-11-17 02:32:00 +0000895 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000896}
897
898size_t
899ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
900{
901 const uint8_t *trap_opcode = NULL;
902 uint32_t trap_opcode_size = 0;
903
904 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
905 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
906 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
907 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
908
Jim Ingham7508e732010-08-09 23:31:02 +0000909 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000910 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000911 {
Greg Claytoncf015052010-06-11 03:25:34 +0000912 case ArchSpec::eCPU_i386:
913 case ArchSpec::eCPU_x86_64:
914 trap_opcode = g_i386_breakpoint_opcode;
915 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
916 break;
917
918 case ArchSpec::eCPU_arm:
919 // TODO: fill this in for ARM. We need to dig up the symbol for
920 // the address in the breakpoint locaiton and figure out if it is
921 // an ARM or Thumb breakpoint.
922 trap_opcode = g_arm_breakpoint_opcode;
923 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
924 break;
925
926 case ArchSpec::eCPU_ppc:
927 case ArchSpec::eCPU_ppc64:
928 trap_opcode = g_ppc_breakpoint_opcode;
929 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
930 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000931
Greg Claytoncf015052010-06-11 03:25:34 +0000932 default:
933 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
934 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000935 }
936
937 if (trap_opcode && trap_opcode_size)
938 {
939 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
940 return trap_opcode_size;
941 }
942 return 0;
943}
944
945uint32_t
946ProcessGDBRemote::UpdateThreadListIfNeeded ()
947{
948 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000949 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000950 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000951 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
952
Greg Clayton5205f0b2010-09-03 17:10:42 +0000953 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000954 const uint32_t stop_id = GetStopID();
955 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
956 {
957 // Update the thread list's stop id immediately so we don't recurse into this function.
958 ThreadList curr_thread_list (this);
959 curr_thread_list.SetStopID(stop_id);
960
961 Error err;
962 StringExtractorGDBRemote response;
963 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
964 response.IsNormalPacket();
965 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
966 {
967 char ch = response.GetChar();
968 if (ch == 'l')
969 break;
970 if (ch == 'm')
971 {
972 do
973 {
974 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
975
976 if (tid != LLDB_INVALID_THREAD_ID)
977 {
978 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +0000979 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000980 thread_sp.reset (new ThreadGDBRemote (*this, tid));
981 curr_thread_list.AddThread(thread_sp);
982 }
983
984 ch = response.GetChar();
985 } while (ch == ',');
986 }
987 }
988
989 m_thread_list = curr_thread_list;
990
991 SetThreadStopInfo (m_last_stop_packet);
992 }
993 return GetThreadList().GetSize(false);
994}
995
996
997StateType
998ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
999{
1000 const char stop_type = stop_packet.GetChar();
1001 switch (stop_type)
1002 {
1003 case 'T':
1004 case 'S':
1005 {
1006 // Stop with signal and thread info
1007 const uint8_t signo = stop_packet.GetHexU8();
1008 std::string name;
1009 std::string value;
1010 std::string thread_name;
1011 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001012 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001013 uint32_t tid = LLDB_INVALID_THREAD_ID;
1014 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1015 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001016 ThreadSP thread_sp;
1017
Chris Lattner24943d22010-06-08 16:52:24 +00001018 while (stop_packet.GetNameColonValue(name, value))
1019 {
1020 if (name.compare("metype") == 0)
1021 {
1022 // exception type in big endian hex
1023 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1024 }
1025 else if (name.compare("mecount") == 0)
1026 {
1027 // exception count in big endian hex
1028 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1029 }
1030 else if (name.compare("medata") == 0)
1031 {
1032 // exception data in big endian hex
1033 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1034 }
1035 else if (name.compare("thread") == 0)
1036 {
1037 // thread in big endian hex
1038 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytona875b642011-01-09 21:07:35 +00001039 thread_sp = m_thread_list.FindThreadByID(tid, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001040 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001041 else if (name.compare("hexname") == 0)
1042 {
1043 StringExtractor name_extractor;
1044 // Swap "value" over into "name_extractor"
1045 name_extractor.GetStringRef().swap(value);
1046 // Now convert the HEX bytes into a string value
1047 name_extractor.GetHexByteString (value);
1048 thread_name.swap (value);
1049 }
Chris Lattner24943d22010-06-08 16:52:24 +00001050 else if (name.compare("name") == 0)
1051 {
1052 thread_name.swap (value);
1053 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001054 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001055 {
1056 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1057 }
Greg Claytona875b642011-01-09 21:07:35 +00001058 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1059 {
1060 // We have a register number that contains an expedited
1061 // register value. Lets supply this register to our thread
1062 // so it won't have to go and read it.
1063 if (thread_sp)
1064 {
1065 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1066
1067 if (reg != UINT32_MAX)
1068 {
1069 StringExtractor reg_value_extractor;
1070 // Swap "value" over into "reg_value_extractor"
1071 reg_value_extractor.GetStringRef().swap(value);
1072 static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor);
1073 }
1074 }
1075 }
Chris Lattner24943d22010-06-08 16:52:24 +00001076 }
Chris Lattner24943d22010-06-08 16:52:24 +00001077
1078 if (thread_sp)
1079 {
1080 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1081
1082 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1083 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001084 if (exc_type != 0)
1085 {
Greg Clayton643ee732010-08-04 01:40:35 +00001086 const size_t exc_data_count = exc_data.size();
1087
1088 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1089 exc_type,
1090 exc_data_count,
1091 exc_data_count >= 1 ? exc_data[0] : 0,
1092 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001093 }
1094 else if (signo)
1095 {
Greg Clayton643ee732010-08-04 01:40:35 +00001096 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001097 }
1098 else
1099 {
Greg Clayton643ee732010-08-04 01:40:35 +00001100 StopInfoSP invalid_stop_info_sp;
1101 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001102 }
1103 }
1104 return eStateStopped;
1105 }
1106 break;
1107
1108 case 'W':
1109 // process exited
1110 return eStateExited;
1111
1112 default:
1113 break;
1114 }
1115 return eStateInvalid;
1116}
1117
1118void
1119ProcessGDBRemote::RefreshStateAfterStop ()
1120{
Jim Ingham7508e732010-08-09 23:31:02 +00001121 // FIXME - add a variable to tell that we're in the middle of attaching if we
1122 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001123 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001124// if (!GetTarget().GetArchitecture().IsValid())
1125// {
1126// Module *exe_module = GetTarget().GetExecutableModule().get();
1127// if (exe_module)
1128// m_arch_spec = exe_module->GetArchitecture();
1129// }
1130
Chris Lattner24943d22010-06-08 16:52:24 +00001131 // Let all threads recover from stopping and do any clean up based
1132 // on the previous thread state (if any).
1133 m_thread_list.RefreshStateAfterStop();
1134
1135 // Discover new threads:
1136 UpdateThreadListIfNeeded ();
1137}
1138
1139Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001140ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001141{
1142 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001143
Chris Lattner24943d22010-06-08 16:52:24 +00001144 if (m_gdb_comm.IsRunning())
1145 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001146 caused_stop = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001147 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001148 Mutex::Locker locker;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001149
Greg Clayton20d338f2010-11-18 05:57:03 +00001150 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001151 {
1152 if (timed_out)
1153 error.SetErrorString("timed out sending interrupt packet");
1154 else
1155 error.SetErrorString("unknown error sending interrupt packet");
1156 }
1157 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001158 else
1159 {
1160 caused_stop = false;
1161 }
1162
Chris Lattner24943d22010-06-08 16:52:24 +00001163 return error;
1164}
1165
1166Error
1167ProcessGDBRemote::WillDetach ()
1168{
1169 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001170
Greg Clayton4fb400f2010-09-27 21:07:38 +00001171 if (m_gdb_comm.IsRunning())
1172 {
1173 bool timed_out = false;
1174 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001175 PausePrivateStateThread();
1176 m_thread_list.DiscardThreadPlans();
1177 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001178 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1179 {
1180 if (timed_out)
1181 error.SetErrorString("timed out sending interrupt packet");
1182 else
1183 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001184 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001185 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001186 TimeValue timeout_time;
1187 timeout_time = TimeValue::Now();
1188 timeout_time.OffsetWithSeconds(2);
1189
1190 EventSP event_sp;
1191 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1192 if (state != eStateStopped)
1193 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001194 }
Chris Lattner24943d22010-06-08 16:52:24 +00001195 return error;
1196}
1197
Greg Clayton4fb400f2010-09-27 21:07:38 +00001198Error
1199ProcessGDBRemote::DoDetach()
1200{
1201 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001202 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001203 if (log)
1204 log->Printf ("ProcessGDBRemote::DoDetach()");
1205
1206 DisableAllBreakpointSites ();
1207
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001208 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001209
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001210 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1211 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001212 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001213 if (response_size)
1214 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1215 else
1216 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001217 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001218 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001219 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001220
Greg Clayton4fb400f2010-09-27 21:07:38 +00001221 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001222 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001223
1224 SetPrivateState (eStateDetached);
1225 ResumePrivateStateThread();
1226
1227 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001228 return error;
1229}
Chris Lattner24943d22010-06-08 16:52:24 +00001230
1231Error
1232ProcessGDBRemote::DoDestroy ()
1233{
1234 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001235 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001236 if (log)
1237 log->Printf ("ProcessGDBRemote::DoDestroy()");
1238
1239 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001240 Mutex::Locker locker;
1241 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001242 DisableAllBreakpointSites ();
1243 SetExitStatus(-1, "process killed");
1244
1245 StringExtractorGDBRemote response;
Greg Claytonb749a262010-12-03 06:02:24 +00001246 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 1, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001247 {
Caroline Tice926060e2010-10-29 21:48:37 +00001248 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001249 if (log)
1250 {
1251 if (response.IsOKPacket())
1252 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1253 else
1254 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1255 }
1256 }
1257
1258 StopAsyncThread ();
1259 m_gdb_comm.StopReadThread();
1260 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001261 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001262 return error;
1263}
1264
Chris Lattner24943d22010-06-08 16:52:24 +00001265//------------------------------------------------------------------
1266// Process Queries
1267//------------------------------------------------------------------
1268
1269bool
1270ProcessGDBRemote::IsAlive ()
1271{
Greg Clayton58e844b2010-12-08 05:08:21 +00001272 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001273}
1274
1275addr_t
1276ProcessGDBRemote::GetImageInfoAddress()
1277{
1278 if (!m_gdb_comm.IsRunning())
1279 {
1280 StringExtractorGDBRemote response;
1281 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1282 {
1283 if (response.IsNormalPacket())
1284 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1285 }
1286 }
1287 return LLDB_INVALID_ADDRESS;
1288}
1289
1290DynamicLoader *
1291ProcessGDBRemote::GetDynamicLoader()
1292{
1293 return m_dynamic_loader_ap.get();
1294}
1295
1296//------------------------------------------------------------------
1297// Process Memory
1298//------------------------------------------------------------------
1299size_t
1300ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1301{
1302 if (size > m_max_memory_size)
1303 {
1304 // Keep memory read sizes down to a sane limit. This function will be
1305 // called multiple times in order to complete the task by
1306 // lldb_private::Process so it is ok to do this.
1307 size = m_max_memory_size;
1308 }
1309
1310 char packet[64];
1311 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1312 assert (packet_len + 1 < sizeof(packet));
1313 StringExtractorGDBRemote response;
1314 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1315 {
1316 if (response.IsNormalPacket())
1317 {
1318 error.Clear();
1319 return response.GetHexBytes(buf, size, '\xdd');
1320 }
1321 else if (response.IsErrorPacket())
1322 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1323 else if (response.IsUnsupportedPacket())
1324 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1325 else
1326 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1327 }
1328 else
1329 {
1330 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1331 }
1332 return 0;
1333}
1334
1335size_t
1336ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1337{
1338 StreamString packet;
1339 packet.Printf("M%llx,%zx:", addr, size);
1340 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1341 StringExtractorGDBRemote response;
1342 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1343 {
1344 if (response.IsOKPacket())
1345 {
1346 error.Clear();
1347 return size;
1348 }
1349 else if (response.IsErrorPacket())
1350 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1351 else if (response.IsUnsupportedPacket())
1352 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1353 else
1354 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1355 }
1356 else
1357 {
1358 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1359 }
1360 return 0;
1361}
1362
1363lldb::addr_t
1364ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1365{
1366 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1367 if (allocated_addr == LLDB_INVALID_ADDRESS)
1368 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1369 else
1370 error.Clear();
1371 return allocated_addr;
1372}
1373
1374Error
1375ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1376{
1377 Error error;
1378 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1379 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1380 return error;
1381}
1382
1383
1384//------------------------------------------------------------------
1385// Process STDIO
1386//------------------------------------------------------------------
1387
1388size_t
1389ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1390{
1391 Mutex::Locker locker(m_stdio_mutex);
1392 size_t bytes_available = m_stdout_data.size();
1393 if (bytes_available > 0)
1394 {
1395 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1396 if (bytes_available > buf_size)
1397 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001398 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001399 m_stdout_data.erase(0, buf_size);
1400 bytes_available = buf_size;
1401 }
1402 else
1403 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001404 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001405 m_stdout_data.clear();
1406
1407 //ResetEventBits(eBroadcastBitSTDOUT);
1408 }
1409 }
1410 return bytes_available;
1411}
1412
1413size_t
1414ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1415{
1416 // Can we get STDERR through the remote protocol?
1417 return 0;
1418}
1419
1420size_t
1421ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1422{
1423 if (m_stdio_communication.IsConnected())
1424 {
1425 ConnectionStatus status;
1426 m_stdio_communication.Write(src, src_len, status, NULL);
1427 }
1428 return 0;
1429}
1430
1431Error
1432ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1433{
1434 Error error;
1435 assert (bp_site != NULL);
1436
Greg Claytone005f2c2010-11-06 01:53:30 +00001437 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001438 user_id_t site_id = bp_site->GetID();
1439 const addr_t addr = bp_site->GetLoadAddress();
1440 if (log)
1441 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1442
1443 if (bp_site->IsEnabled())
1444 {
1445 if (log)
1446 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1447 return error;
1448 }
1449 else
1450 {
1451 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1452
1453 if (bp_site->HardwarePreferred())
1454 {
1455 // Try and set hardware breakpoint, and if that fails, fall through
1456 // and set a software breakpoint?
1457 }
1458
1459 if (m_z0_supported)
1460 {
1461 char packet[64];
1462 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1463 assert (packet_len + 1 < sizeof(packet));
1464 StringExtractorGDBRemote response;
1465 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1466 {
1467 if (response.IsUnsupportedPacket())
1468 {
1469 // Disable z packet support and try again
1470 m_z0_supported = 0;
1471 return EnableBreakpoint (bp_site);
1472 }
1473 else if (response.IsOKPacket())
1474 {
1475 bp_site->SetEnabled(true);
1476 bp_site->SetType (BreakpointSite::eExternal);
1477 return error;
1478 }
1479 else
1480 {
1481 uint8_t error_byte = response.GetError();
1482 if (error_byte)
1483 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1484 }
1485 }
1486 }
1487 else
1488 {
1489 return EnableSoftwareBreakpoint (bp_site);
1490 }
1491 }
1492
1493 if (log)
1494 {
1495 const char *err_string = error.AsCString();
1496 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1497 bp_site->GetLoadAddress(),
1498 err_string ? err_string : "NULL");
1499 }
1500 // We shouldn't reach here on a successful breakpoint enable...
1501 if (error.Success())
1502 error.SetErrorToGenericError();
1503 return error;
1504}
1505
1506Error
1507ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1508{
1509 Error error;
1510 assert (bp_site != NULL);
1511 addr_t addr = bp_site->GetLoadAddress();
1512 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001513 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001514 if (log)
1515 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1516
1517 if (bp_site->IsEnabled())
1518 {
1519 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1520
1521 if (bp_site->IsHardware())
1522 {
1523 // TODO: disable hardware breakpoint...
1524 }
1525 else
1526 {
1527 if (m_z0_supported)
1528 {
1529 char packet[64];
1530 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1531 assert (packet_len + 1 < sizeof(packet));
1532 StringExtractorGDBRemote response;
1533 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1534 {
1535 if (response.IsUnsupportedPacket())
1536 {
1537 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1538 }
1539 else if (response.IsOKPacket())
1540 {
1541 if (log)
1542 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1543 bp_site->SetEnabled(false);
1544 return error;
1545 }
1546 else
1547 {
1548 uint8_t error_byte = response.GetError();
1549 if (error_byte)
1550 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1551 }
1552 }
1553 }
1554 else
1555 {
1556 return DisableSoftwareBreakpoint (bp_site);
1557 }
1558 }
1559 }
1560 else
1561 {
1562 if (log)
1563 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1564 return error;
1565 }
1566
1567 if (error.Success())
1568 error.SetErrorToGenericError();
1569 return error;
1570}
1571
1572Error
1573ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1574{
1575 Error error;
1576 if (wp)
1577 {
1578 user_id_t watchID = wp->GetID();
1579 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001580 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001581 if (log)
1582 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1583 if (wp->IsEnabled())
1584 {
1585 if (log)
1586 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1587 return error;
1588 }
1589 else
1590 {
1591 // Pass down an appropriate z/Z packet...
1592 error.SetErrorString("watchpoints not supported");
1593 }
1594 }
1595 else
1596 {
1597 error.SetErrorString("Watchpoint location argument was NULL.");
1598 }
1599 if (error.Success())
1600 error.SetErrorToGenericError();
1601 return error;
1602}
1603
1604Error
1605ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1606{
1607 Error error;
1608 if (wp)
1609 {
1610 user_id_t watchID = wp->GetID();
1611
Greg Claytone005f2c2010-11-06 01:53:30 +00001612 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001613
1614 addr_t addr = wp->GetLoadAddress();
1615 if (log)
1616 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1617
1618 if (wp->IsHardware())
1619 {
1620 // Pass down an appropriate z/Z packet...
1621 error.SetErrorString("watchpoints not supported");
1622 }
1623 // TODO: clear software watchpoints if we implement them
1624 }
1625 else
1626 {
1627 error.SetErrorString("Watchpoint location argument was NULL.");
1628 }
1629 if (error.Success())
1630 error.SetErrorToGenericError();
1631 return error;
1632}
1633
1634void
1635ProcessGDBRemote::Clear()
1636{
1637 m_flags = 0;
1638 m_thread_list.Clear();
1639 {
1640 Mutex::Locker locker(m_stdio_mutex);
1641 m_stdout_data.clear();
1642 }
Chris Lattner24943d22010-06-08 16:52:24 +00001643}
1644
1645Error
1646ProcessGDBRemote::DoSignal (int signo)
1647{
1648 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001649 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001650 if (log)
1651 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1652
1653 if (!m_gdb_comm.SendAsyncSignal (signo))
1654 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1655 return error;
1656}
1657
Caroline Tice861efb32010-11-16 05:07:41 +00001658//void
1659//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1660//{
1661// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1662// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1663//}
Chris Lattner24943d22010-06-08 16:52:24 +00001664
Caroline Tice861efb32010-11-16 05:07:41 +00001665//void
1666//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1667//{
1668// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1669// Mutex::Locker locker(m_stdio_mutex);
1670// m_stdout_data.append(s, len);
1671//
1672// // FIXME: Make a real data object for this and put it out.
1673// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1674//}
Chris Lattner24943d22010-06-08 16:52:24 +00001675
1676
1677Error
1678ProcessGDBRemote::StartDebugserverProcess
1679(
1680 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1681 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1682 char const *inferior_envp[], // Environment to pass along to the inferior program
1683 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001684 bool launch_process, // Set to true if we are going to be launching a the process
1685 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 +00001686 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1687 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001688 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001689 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1690)
1691{
1692 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001693 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1694 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001695 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1696 {
1697 // If we locate debugserver, keep that located version around
1698 static FileSpec g_debugserver_file_spec;
1699
1700 FileSpec debugserver_file_spec;
1701 char debugserver_path[PATH_MAX];
1702
1703 // Always check to see if we have an environment override for the path
1704 // to the debugserver to use and use it if we do.
1705 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1706 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001707 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001708 else
1709 debugserver_file_spec = g_debugserver_file_spec;
1710 bool debugserver_exists = debugserver_file_spec.Exists();
1711 if (!debugserver_exists)
1712 {
1713 // The debugserver binary is in the LLDB.framework/Resources
1714 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001715 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001716 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001717 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001718 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001719 if (debugserver_exists)
1720 {
1721 g_debugserver_file_spec = debugserver_file_spec;
1722 }
1723 else
1724 {
1725 g_debugserver_file_spec.Clear();
1726 debugserver_file_spec.Clear();
1727 }
Chris Lattner24943d22010-06-08 16:52:24 +00001728 }
1729 }
1730
1731 if (debugserver_exists)
1732 {
1733 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1734
1735 m_stdio_communication.Clear();
1736 posix_spawnattr_t attr;
1737
Greg Claytone005f2c2010-11-06 01:53:30 +00001738 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001739
1740 Error local_err; // Errors that don't affect the spawning.
1741 if (log)
1742 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1743 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1744 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001745 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001746 if (error.Fail())
1747 return error;;
1748
1749#if !defined (__arm__)
1750
Greg Clayton24b48ff2010-10-17 22:03:32 +00001751 // We don't need to do this for ARM, and we really shouldn't now
1752 // that we have multiple CPU subtypes and no posix_spawnattr call
1753 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001754 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001755 {
Greg Claytoncf015052010-06-11 03:25:34 +00001756 cpu_type_t cpu = inferior_arch.GetCPUType();
1757 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1758 {
1759 size_t ocount = 0;
1760 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1761 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001762 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 +00001763
Greg Claytoncf015052010-06-11 03:25:34 +00001764 if (error.Fail() != 0 || ocount != 1)
1765 return error;
1766 }
Chris Lattner24943d22010-06-08 16:52:24 +00001767 }
1768
1769#endif
1770
1771 Args debugserver_args;
1772 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001773
Chris Lattner24943d22010-06-08 16:52:24 +00001774 lldb_utility::PseudoTerminal pty;
Caroline Ticebd666012010-12-03 18:46:09 +00001775 if (launch_process && stdio_path == NULL && m_local_debugserver && !no_stdio)
Chris Lattner24943d22010-06-08 16:52:24 +00001776 {
Chris Lattner24943d22010-06-08 16:52:24 +00001777 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001778 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001779 }
1780
1781 // Start args with "debugserver /file/path -r --"
1782 debugserver_args.AppendArgument(debugserver_path);
1783 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001784 // use native registers, not the GDB registers
1785 debugserver_args.AppendArgument("--native-regs");
1786 // make debugserver run in its own session so signals generated by
1787 // special terminal key sequences (^C) don't affect debugserver
1788 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001789
Greg Clayton452bf612010-08-31 18:35:14 +00001790 if (disable_aslr)
1791 debugserver_args.AppendArguments("--disable-aslr");
1792
Chris Lattner24943d22010-06-08 16:52:24 +00001793 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001794 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001795 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001796 debugserver_args.AppendArgument("--stdio-path");
1797 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001798 }
Caroline Ticebd666012010-12-03 18:46:09 +00001799 else if (launch_process && no_stdio)
1800 {
1801 debugserver_args.AppendArgument("--no-stdio");
1802 }
Chris Lattner24943d22010-06-08 16:52:24 +00001803
1804 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1805 if (env_debugserver_log_file)
1806 {
1807 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1808 debugserver_args.AppendArgument(arg_cstr);
1809 }
1810
1811 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1812 if (env_debugserver_log_flags)
1813 {
1814 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1815 debugserver_args.AppendArgument(arg_cstr);
1816 }
1817// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1818// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1819
1820 // Now append the program arguments
1821 if (launch_process)
1822 {
1823 if (inferior_argv)
1824 {
1825 // Terminate the debugserver args so we can now append the inferior args
1826 debugserver_args.AppendArgument("--");
1827
1828 for (int i = 0; inferior_argv[i] != NULL; ++i)
1829 debugserver_args.AppendArgument (inferior_argv[i]);
1830 }
1831 else
1832 {
1833 // Will send environment entries with the 'QEnvironment:' packet
1834 // Will send arguments with the 'A' packet
1835 }
1836 }
1837 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1838 {
1839 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1840 debugserver_args.AppendArgument (arg_cstr);
1841 }
1842 else if (attach_name && attach_name[0])
1843 {
1844 if (wait_for_launch)
1845 debugserver_args.AppendArgument ("--waitfor");
1846 else
1847 debugserver_args.AppendArgument ("--attach");
1848 debugserver_args.AppendArgument (attach_name);
1849 }
1850
1851 Error file_actions_err;
1852 posix_spawn_file_actions_t file_actions;
1853#if DONT_CLOSE_DEBUGSERVER_STDIO
1854 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1855#else
1856 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1857 if (file_actions_err.Success())
1858 {
1859 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1860 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1861 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1862 }
1863#endif
1864
1865 if (log)
1866 {
1867 StreamString strm;
1868 debugserver_args.Dump (&strm);
1869 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1870 }
1871
1872 error.SetError(::posix_spawnp (&m_debugserver_pid,
1873 debugserver_path,
1874 file_actions_err.Success() ? &file_actions : NULL,
1875 &attr,
1876 debugserver_args.GetArgumentVector(),
1877 (char * const*)inferior_envp),
1878 eErrorTypePOSIX);
1879
Greg Claytone9d0df42010-07-02 01:29:13 +00001880
1881 ::posix_spawnattr_destroy (&attr);
1882
Chris Lattner24943d22010-06-08 16:52:24 +00001883 if (file_actions_err.Success())
1884 ::posix_spawn_file_actions_destroy (&file_actions);
1885
1886 // We have seen some cases where posix_spawnp was returning a valid
1887 // looking pid even when an error was returned, so clear it out
1888 if (error.Fail())
1889 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1890
1891 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001892 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 +00001893
Caroline Ticebd666012010-12-03 18:46:09 +00001894 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00001895 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001896 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001897 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001898 }
Chris Lattner24943d22010-06-08 16:52:24 +00001899 }
1900 else
1901 {
1902 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1903 }
1904
1905 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1906 StartAsyncThread ();
1907 }
1908 return error;
1909}
1910
1911bool
1912ProcessGDBRemote::MonitorDebugserverProcess
1913(
1914 void *callback_baton,
1915 lldb::pid_t debugserver_pid,
1916 int signo, // Zero for no signal
1917 int exit_status // Exit value of process if signal is zero
1918)
1919{
1920 // We pass in the ProcessGDBRemote inferior process it and name it
1921 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1922 // pointer value itself, thus we need the double cast...
1923
1924 // "debugserver_pid" argument passed in is the process ID for
1925 // debugserver that we are tracking...
1926
Greg Clayton75ccf502010-08-21 02:22:51 +00001927 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1928
1929 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001930 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001931 // Sleep for a half a second to make sure our inferior process has
1932 // time to set its exit status before we set it incorrectly when
1933 // both the debugserver and the inferior process shut down.
1934 usleep (500000);
1935 // If our process hasn't yet exited, debugserver might have died.
1936 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001937 const StateType state = process->GetState();
1938
1939 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1940 state != eStateInvalid &&
1941 state != eStateUnloaded &&
1942 state != eStateExited &&
1943 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001944 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001945 char error_str[1024];
1946 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001947 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001948 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1949 if (signal_cstr)
1950 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001951 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001952 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001953 }
1954 else
1955 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001956 ::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 +00001957 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001958
1959 process->SetExitStatus (-1, error_str);
1960 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001961 // Debugserver has exited we need to let our ProcessGDBRemote
1962 // know that it no longer has a debugserver instance
1963 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1964 // We are returning true to this function below, so we can
1965 // forget about the monitor handle.
1966 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001967 }
1968 return true;
1969}
1970
1971void
1972ProcessGDBRemote::KillDebugserverProcess ()
1973{
1974 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1975 {
1976 ::kill (m_debugserver_pid, SIGINT);
1977 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1978 }
1979}
1980
1981void
1982ProcessGDBRemote::Initialize()
1983{
1984 static bool g_initialized = false;
1985
1986 if (g_initialized == false)
1987 {
1988 g_initialized = true;
1989 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1990 GetPluginDescriptionStatic(),
1991 CreateInstance);
1992
1993 Log::Callbacks log_callbacks = {
1994 ProcessGDBRemoteLog::DisableLog,
1995 ProcessGDBRemoteLog::EnableLog,
1996 ProcessGDBRemoteLog::ListLogCategories
1997 };
1998
1999 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2000 }
2001}
2002
2003bool
2004ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2005{
2006 if (m_curr_tid == tid)
2007 return true;
2008
2009 char packet[32];
2010 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2011 assert (packet_len + 1 < sizeof(packet));
2012 StringExtractorGDBRemote response;
2013 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2014 {
2015 if (response.IsOKPacket())
2016 {
2017 m_curr_tid = tid;
2018 return true;
2019 }
2020 }
2021 return false;
2022}
2023
2024bool
2025ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2026{
2027 if (m_curr_tid_run == tid)
2028 return true;
2029
2030 char packet[32];
Greg Claytonc71899e2011-01-18 19:36:39 +00002031 const int packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002032 assert (packet_len + 1 < sizeof(packet));
2033 StringExtractorGDBRemote response;
2034 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2035 {
2036 if (response.IsOKPacket())
2037 {
2038 m_curr_tid_run = tid;
2039 return true;
2040 }
2041 }
2042 return false;
2043}
2044
2045void
2046ProcessGDBRemote::ResetGDBRemoteState ()
2047{
2048 // Reset and GDB remote state
2049 m_curr_tid = LLDB_INVALID_THREAD_ID;
2050 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2051 m_z0_supported = 1;
2052}
2053
2054
2055bool
2056ProcessGDBRemote::StartAsyncThread ()
2057{
2058 ResetGDBRemoteState ();
2059
Greg Claytone005f2c2010-11-06 01:53:30 +00002060 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002061
2062 if (log)
2063 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2064
2065 // Create a thread that watches our internal state and controls which
2066 // events make it to clients (into the DCProcess event queue).
2067 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2068 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2069}
2070
2071void
2072ProcessGDBRemote::StopAsyncThread ()
2073{
Greg Claytone005f2c2010-11-06 01:53:30 +00002074 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002075
2076 if (log)
2077 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2078
2079 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2080
2081 // Stop the stdio thread
2082 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2083 {
2084 Host::ThreadJoin (m_async_thread, NULL, NULL);
2085 }
2086}
2087
2088
2089void *
2090ProcessGDBRemote::AsyncThread (void *arg)
2091{
2092 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2093
Greg Claytone005f2c2010-11-06 01:53:30 +00002094 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002095 if (log)
2096 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2097
2098 Listener listener ("ProcessGDBRemote::AsyncThread");
2099 EventSP event_sp;
2100 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2101 eBroadcastBitAsyncThreadShouldExit;
2102
2103 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2104 {
2105 bool done = false;
2106 while (!done)
2107 {
Caroline Tice926060e2010-10-29 21:48:37 +00002108 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002109 if (log)
2110 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2111 if (listener.WaitForEvent (NULL, event_sp))
2112 {
2113 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002114 if (log)
2115 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2116
Chris Lattner24943d22010-06-08 16:52:24 +00002117 switch (event_type)
2118 {
2119 case eBroadcastBitAsyncContinue:
2120 {
2121 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2122
2123 if (continue_packet)
2124 {
2125 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2126 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002127 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002128 if (log)
2129 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2130
2131 process->SetPrivateState(eStateRunning);
2132 StringExtractorGDBRemote response;
2133 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2134
2135 switch (stop_state)
2136 {
2137 case eStateStopped:
2138 case eStateCrashed:
2139 case eStateSuspended:
2140 process->m_last_stop_packet = response;
2141 process->m_last_stop_packet.SetFilePos (0);
2142 process->SetPrivateState (stop_state);
2143 break;
2144
2145 case eStateExited:
2146 process->m_last_stop_packet = response;
2147 process->m_last_stop_packet.SetFilePos (0);
2148 response.SetFilePos(1);
2149 process->SetExitStatus(response.GetHexU8(), NULL);
2150 done = true;
2151 break;
2152
2153 case eStateInvalid:
2154 break;
2155
2156 default:
2157 process->SetPrivateState (stop_state);
2158 break;
2159 }
2160 }
2161 }
2162 break;
2163
2164 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002165 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002166 if (log)
2167 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2168 done = true;
2169 break;
2170
2171 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002172 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002173 if (log)
2174 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2175 done = true;
2176 break;
2177 }
2178 }
2179 else
2180 {
Caroline Tice926060e2010-10-29 21:48:37 +00002181 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002182 if (log)
2183 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2184 done = true;
2185 }
2186 }
2187 }
2188
Caroline Tice926060e2010-10-29 21:48:37 +00002189 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002190 if (log)
2191 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2192
2193 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2194 return NULL;
2195}
2196
Chris Lattner24943d22010-06-08 16:52:24 +00002197const char *
2198ProcessGDBRemote::GetDispatchQueueNameForThread
2199(
2200 addr_t thread_dispatch_qaddr,
2201 std::string &dispatch_queue_name
2202)
2203{
2204 dispatch_queue_name.clear();
2205 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2206 {
2207 // Cache the dispatch_queue_offsets_addr value so we don't always have
2208 // to look it up
2209 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2210 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002211 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2212 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002213 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002214 if (module_sp)
2215 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2216
2217 if (dispatch_queue_offsets_symbol == NULL)
2218 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002219 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002220 if (module_sp)
2221 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2222 }
Chris Lattner24943d22010-06-08 16:52:24 +00002223 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002224 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002225
2226 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2227 return NULL;
2228 }
2229
2230 uint8_t memory_buffer[8];
2231 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2232
2233 // Excerpt from src/queue_private.h
2234 struct dispatch_queue_offsets_s
2235 {
2236 uint16_t dqo_version;
2237 uint16_t dqo_label;
2238 uint16_t dqo_label_size;
2239 } dispatch_queue_offsets;
2240
2241
2242 Error error;
2243 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2244 {
2245 uint32_t data_offset = 0;
2246 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2247 {
2248 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2249 {
2250 data_offset = 0;
2251 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2252 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2253 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2254 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2255 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2256 dispatch_queue_name.erase (bytes_read);
2257 }
2258 }
2259 }
2260 }
2261 if (dispatch_queue_name.empty())
2262 return NULL;
2263 return dispatch_queue_name.c_str();
2264}
2265
Jim Ingham7508e732010-08-09 23:31:02 +00002266uint32_t
2267ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2268{
2269 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2270 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2271 if (m_local_debugserver)
2272 {
2273 return Host::ListProcessesMatchingName (name, matches, pids);
2274 }
2275 else
2276 {
2277 // FIXME: Implement talking to the remote debugserver.
2278 return 0;
2279 }
2280
2281}