blob: 80580f8dddc5ab1f38145e4ca30377b5537bb0d8 [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 }
Chris Lattner24943d22010-06-08 16:52:24 +0000557 }
558 return error;
559}
560
561void
562ProcessGDBRemote::DidLaunchOrAttach ()
563{
564 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
565 if (GetID() == LLDB_INVALID_PROCESS_ID)
566 {
567 m_dynamic_loader_ap.reset();
568 }
569 else
570 {
571 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
572
Greg Clayton20d338f2010-11-18 05:57:03 +0000573 BuildDynamicRegisterInfo ();
574
575 m_byte_order = m_gdb_comm.GetByteOrder();
576
Chris Lattner24943d22010-06-08 16:52:24 +0000577 StreamString strm;
578
579 ArchSpec inferior_arch;
580 // See if the GDB server supports the qHostInfo information
581 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
582 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Clayton20d338f2010-11-18 05:57:03 +0000583 ArchSpec arch_spec (GetTarget().GetArchitecture());
Chris Lattner24943d22010-06-08 16:52:24 +0000584
Jim Ingham7508e732010-08-09 23:31:02 +0000585 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000586 {
587 // For ARM we can't trust the arch of the process as it could
588 // have an armv6 object file, but be running on armv7 kernel.
589 inferior_arch = m_gdb_comm.GetHostArchitecture();
590 }
591
592 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000593 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000594
595 if (vendor == NULL)
596 vendor = Host::GetVendorString().AsCString("apple");
597
598 if (os_type == NULL)
599 os_type = Host::GetOSString().AsCString("darwin");
600
601 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
602
603 std::transform (strm.GetString().begin(),
604 strm.GetString().end(),
605 strm.GetString().begin(),
606 ::tolower);
607
608 m_target_triple.SetCString(strm.GetString().c_str());
609 }
610}
611
612void
613ProcessGDBRemote::DidLaunch ()
614{
615 DidLaunchOrAttach ();
616 if (m_dynamic_loader_ap.get())
617 m_dynamic_loader_ap->DidLaunch();
618}
619
620Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000621ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000622{
623 Error error;
624 // Clear out and clean up from any current state
625 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000626 ArchSpec arch_spec = GetTarget().GetArchitecture();
627
Greg Claytone005f2c2010-11-06 01:53:30 +0000628 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000629
630
Chris Lattner24943d22010-06-08 16:52:24 +0000631 if (attach_pid != LLDB_INVALID_PROCESS_ID)
632 {
Chris Lattner24943d22010-06-08 16:52:24 +0000633 char host_port[128];
634 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000635 error = StartDebugserverProcess (host_port, // debugserver_url
636 NULL, // inferior_argv
637 NULL, // inferior_envp
638 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000639 false, // launch_process == false (we are attaching)
640 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
641 NULL, // Don't send any attach by process name option to debugserver
642 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000643 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000644 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000645
646 if (error.Fail())
647 {
648 const char *error_string = error.AsCString();
649 if (error_string == NULL)
650 error_string = "unable to launch " DEBUGSERVER_BASENAME;
651
652 SetExitStatus (-1, error_string);
653 }
654 else
655 {
656 error = ConnectToDebugserver (host_port);
657 if (error.Success())
658 {
659 char packet[64];
660 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
661 StringExtractorGDBRemote response;
662 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
663 packet,
664 packet_len,
665 response);
666 switch (stop_state)
667 {
668 case eStateStopped:
669 case eStateCrashed:
670 case eStateSuspended:
671 SetID (attach_pid);
672 m_last_stop_packet = response;
673 m_last_stop_packet.SetFilePos (0);
674 SetPrivateState (stop_state);
675 break;
676
677 case eStateExited:
678 m_last_stop_packet = response;
679 m_last_stop_packet.SetFilePos (0);
680 response.SetFilePos(1);
681 SetExitStatus(response.GetHexU8(), NULL);
682 break;
683
684 default:
685 SetExitStatus(-1, "unable to attach to process");
686 break;
687 }
688
689 }
690 }
691 }
692
693 lldb::pid_t pid = GetID();
694 if (pid == LLDB_INVALID_PROCESS_ID)
695 {
696 KillDebugserverProcess();
697 }
698 return error;
699}
700
701size_t
702ProcessGDBRemote::AttachInputReaderCallback
703(
704 void *baton,
705 InputReader *reader,
706 lldb::InputReaderAction notification,
707 const char *bytes,
708 size_t bytes_len
709)
710{
711 if (notification == eInputReaderGotToken)
712 {
713 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
714 if (gdb_process->m_waiting_for_attach)
715 gdb_process->m_waiting_for_attach = false;
716 reader->SetIsDone(true);
717 return 1;
718 }
719 return 0;
720}
721
722Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000723ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000724{
725 Error error;
726 // Clear out and clean up from any current state
727 Clear();
728 // HACK: require arch be set correctly at the target level until we can
729 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000730
Greg Claytone005f2c2010-11-06 01:53:30 +0000731 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000732 if (process_name && process_name[0])
733 {
Chris Lattner24943d22010-06-08 16:52:24 +0000734 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000735 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000736 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000737 error = StartDebugserverProcess (host_port, // debugserver_url
738 NULL, // inferior_argv
739 NULL, // inferior_envp
740 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000741 false, // launch_process == false (we are attaching)
742 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
743 NULL, // Don't send any attach by process name option to debugserver
744 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000745 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000746 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000747 if (error.Fail())
748 {
749 const char *error_string = error.AsCString();
750 if (error_string == NULL)
751 error_string = "unable to launch " DEBUGSERVER_BASENAME;
752
753 SetExitStatus (-1, error_string);
754 }
755 else
756 {
757 error = ConnectToDebugserver (host_port);
758 if (error.Success())
759 {
760 StreamString packet;
761
Chris Lattner24943d22010-06-08 16:52:24 +0000762 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000763 packet.PutCString("vAttachWait");
764 else
765 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000766 packet.PutChar(';');
767 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
768 StringExtractorGDBRemote response;
769 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
770 packet.GetData(),
771 packet.GetSize(),
772 response);
773 switch (stop_state)
774 {
775 case eStateStopped:
776 case eStateCrashed:
777 case eStateSuspended:
778 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
779 m_last_stop_packet = response;
780 m_last_stop_packet.SetFilePos (0);
781 SetPrivateState (stop_state);
782 break;
783
784 case eStateExited:
785 m_last_stop_packet = response;
786 m_last_stop_packet.SetFilePos (0);
787 response.SetFilePos(1);
788 SetExitStatus(response.GetHexU8(), NULL);
789 break;
790
791 default:
792 SetExitStatus(-1, "unable to attach to process");
793 break;
794 }
795 }
796 }
797 }
798
799 lldb::pid_t pid = GetID();
800 if (pid == LLDB_INVALID_PROCESS_ID)
801 {
802 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000803
804 if (error.Success())
805 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000806 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000807
Chris Lattner24943d22010-06-08 16:52:24 +0000808 return error;
809}
810
811//
812// if (wait_for_launch)
813// {
814// InputReaderSP reader_sp (new InputReader());
815// StreamString instructions;
816// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
817// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
818// this, // baton
819// eInputReaderGranularityByte,
820// NULL, // End token
821// false);
822//
823// StringExtractorGDBRemote response;
824// m_waiting_for_attach = true;
825// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
826// while (m_waiting_for_attach)
827// {
828// // Wait for one second for the stop reply packet
829// if (m_gdb_comm.WaitForPacket(response, 1))
830// {
831// // Got some sort of packet, see if it is the stop reply packet?
832// char ch = response.GetChar(0);
833// if (ch == 'T')
834// {
835// m_waiting_for_attach = false;
836// }
837// }
838// else
839// {
840// // Put a period character every second
841// fputc('.', reader_out_fh);
842// }
843// }
844// }
845// }
846// return GetID();
847//}
848
849void
850ProcessGDBRemote::DidAttach ()
851{
Chris Lattner24943d22010-06-08 16:52:24 +0000852 if (m_dynamic_loader_ap.get())
853 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000854 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000855}
856
857Error
858ProcessGDBRemote::WillResume ()
859{
860 m_continue_packet.Clear();
861 // Start the continue packet we will use to run the target. Each thread
862 // will append what it is supposed to be doing to this packet when the
863 // ThreadList::WillResume() is called. If a thread it supposed
864 // to stay stopped, then don't append anything to this string.
865 m_continue_packet.Printf("vCont");
866 return Error();
867}
868
869Error
870ProcessGDBRemote::DoResume ()
871{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000872 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000873 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000874
875 Listener listener ("gdb-remote.resume-packet-sent");
876 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
877 {
878 EventSP event_sp;
879 TimeValue timeout;
880 timeout = TimeValue::Now();
881 timeout.OffsetWithSeconds (5);
882 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
883
884 if (listener.WaitForEvent (&timeout, event_sp) == false)
885 error.SetErrorString("Resume timed out.");
886 }
887
Jim Ingham3ae449a2010-11-17 02:32:00 +0000888 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000889}
890
891size_t
892ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
893{
894 const uint8_t *trap_opcode = NULL;
895 uint32_t trap_opcode_size = 0;
896
897 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
898 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
899 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
900 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
901
Jim Ingham7508e732010-08-09 23:31:02 +0000902 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000903 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000904 {
Greg Claytoncf015052010-06-11 03:25:34 +0000905 case ArchSpec::eCPU_i386:
906 case ArchSpec::eCPU_x86_64:
907 trap_opcode = g_i386_breakpoint_opcode;
908 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
909 break;
910
911 case ArchSpec::eCPU_arm:
912 // TODO: fill this in for ARM. We need to dig up the symbol for
913 // the address in the breakpoint locaiton and figure out if it is
914 // an ARM or Thumb breakpoint.
915 trap_opcode = g_arm_breakpoint_opcode;
916 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
917 break;
918
919 case ArchSpec::eCPU_ppc:
920 case ArchSpec::eCPU_ppc64:
921 trap_opcode = g_ppc_breakpoint_opcode;
922 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
923 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000924
Greg Claytoncf015052010-06-11 03:25:34 +0000925 default:
926 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
927 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000928 }
929
930 if (trap_opcode && trap_opcode_size)
931 {
932 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
933 return trap_opcode_size;
934 }
935 return 0;
936}
937
938uint32_t
939ProcessGDBRemote::UpdateThreadListIfNeeded ()
940{
941 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000942 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000943 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000944 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
945
Greg Clayton5205f0b2010-09-03 17:10:42 +0000946 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000947 const uint32_t stop_id = GetStopID();
948 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
949 {
950 // Update the thread list's stop id immediately so we don't recurse into this function.
951 ThreadList curr_thread_list (this);
952 curr_thread_list.SetStopID(stop_id);
953
954 Error err;
955 StringExtractorGDBRemote response;
956 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
957 response.IsNormalPacket();
958 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
959 {
960 char ch = response.GetChar();
961 if (ch == 'l')
962 break;
963 if (ch == 'm')
964 {
965 do
966 {
967 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
968
969 if (tid != LLDB_INVALID_THREAD_ID)
970 {
971 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +0000972 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000973 thread_sp.reset (new ThreadGDBRemote (*this, tid));
974 curr_thread_list.AddThread(thread_sp);
975 }
976
977 ch = response.GetChar();
978 } while (ch == ',');
979 }
980 }
981
982 m_thread_list = curr_thread_list;
983
984 SetThreadStopInfo (m_last_stop_packet);
985 }
986 return GetThreadList().GetSize(false);
987}
988
989
990StateType
991ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
992{
993 const char stop_type = stop_packet.GetChar();
994 switch (stop_type)
995 {
996 case 'T':
997 case 'S':
998 {
999 // Stop with signal and thread info
1000 const uint8_t signo = stop_packet.GetHexU8();
1001 std::string name;
1002 std::string value;
1003 std::string thread_name;
1004 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001005 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001006 uint32_t tid = LLDB_INVALID_THREAD_ID;
1007 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1008 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001009 ThreadSP thread_sp;
1010
Chris Lattner24943d22010-06-08 16:52:24 +00001011 while (stop_packet.GetNameColonValue(name, value))
1012 {
1013 if (name.compare("metype") == 0)
1014 {
1015 // exception type in big endian hex
1016 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1017 }
1018 else if (name.compare("mecount") == 0)
1019 {
1020 // exception count in big endian hex
1021 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1022 }
1023 else if (name.compare("medata") == 0)
1024 {
1025 // exception data in big endian hex
1026 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1027 }
1028 else if (name.compare("thread") == 0)
1029 {
1030 // thread in big endian hex
1031 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytona875b642011-01-09 21:07:35 +00001032 thread_sp = m_thread_list.FindThreadByID(tid, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001033 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001034 else if (name.compare("hexname") == 0)
1035 {
1036 StringExtractor name_extractor;
1037 // Swap "value" over into "name_extractor"
1038 name_extractor.GetStringRef().swap(value);
1039 // Now convert the HEX bytes into a string value
1040 name_extractor.GetHexByteString (value);
1041 thread_name.swap (value);
1042 }
Chris Lattner24943d22010-06-08 16:52:24 +00001043 else if (name.compare("name") == 0)
1044 {
1045 thread_name.swap (value);
1046 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001047 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001048 {
1049 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1050 }
Greg Claytona875b642011-01-09 21:07:35 +00001051 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1052 {
1053 // We have a register number that contains an expedited
1054 // register value. Lets supply this register to our thread
1055 // so it won't have to go and read it.
1056 if (thread_sp)
1057 {
1058 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1059
1060 if (reg != UINT32_MAX)
1061 {
1062 StringExtractor reg_value_extractor;
1063 // Swap "value" over into "reg_value_extractor"
1064 reg_value_extractor.GetStringRef().swap(value);
1065 static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor);
1066 }
1067 }
1068 }
Chris Lattner24943d22010-06-08 16:52:24 +00001069 }
Chris Lattner24943d22010-06-08 16:52:24 +00001070
1071 if (thread_sp)
1072 {
1073 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1074
1075 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1076 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001077 if (exc_type != 0)
1078 {
Greg Clayton643ee732010-08-04 01:40:35 +00001079 const size_t exc_data_count = exc_data.size();
1080
1081 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1082 exc_type,
1083 exc_data_count,
1084 exc_data_count >= 1 ? exc_data[0] : 0,
1085 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001086 }
1087 else if (signo)
1088 {
Greg Clayton643ee732010-08-04 01:40:35 +00001089 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001090 }
1091 else
1092 {
Greg Clayton643ee732010-08-04 01:40:35 +00001093 StopInfoSP invalid_stop_info_sp;
1094 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001095 }
1096 }
1097 return eStateStopped;
1098 }
1099 break;
1100
1101 case 'W':
1102 // process exited
1103 return eStateExited;
1104
1105 default:
1106 break;
1107 }
1108 return eStateInvalid;
1109}
1110
1111void
1112ProcessGDBRemote::RefreshStateAfterStop ()
1113{
Jim Ingham7508e732010-08-09 23:31:02 +00001114 // FIXME - add a variable to tell that we're in the middle of attaching if we
1115 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001116 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001117// if (!GetTarget().GetArchitecture().IsValid())
1118// {
1119// Module *exe_module = GetTarget().GetExecutableModule().get();
1120// if (exe_module)
1121// m_arch_spec = exe_module->GetArchitecture();
1122// }
1123
Chris Lattner24943d22010-06-08 16:52:24 +00001124 // Let all threads recover from stopping and do any clean up based
1125 // on the previous thread state (if any).
1126 m_thread_list.RefreshStateAfterStop();
1127
1128 // Discover new threads:
1129 UpdateThreadListIfNeeded ();
1130}
1131
1132Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001133ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001134{
1135 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001136
Chris Lattner24943d22010-06-08 16:52:24 +00001137 if (m_gdb_comm.IsRunning())
1138 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001139 caused_stop = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001140 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001141 Mutex::Locker locker;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001142
Greg Clayton20d338f2010-11-18 05:57:03 +00001143 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001144 {
1145 if (timed_out)
1146 error.SetErrorString("timed out sending interrupt packet");
1147 else
1148 error.SetErrorString("unknown error sending interrupt packet");
1149 }
1150 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001151 else
1152 {
1153 caused_stop = false;
1154 }
1155
Chris Lattner24943d22010-06-08 16:52:24 +00001156 return error;
1157}
1158
1159Error
1160ProcessGDBRemote::WillDetach ()
1161{
1162 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001163
Greg Clayton4fb400f2010-09-27 21:07:38 +00001164 if (m_gdb_comm.IsRunning())
1165 {
1166 bool timed_out = false;
1167 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001168 PausePrivateStateThread();
1169 m_thread_list.DiscardThreadPlans();
1170 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001171 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1172 {
1173 if (timed_out)
1174 error.SetErrorString("timed out sending interrupt packet");
1175 else
1176 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001177 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001178 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001179 TimeValue timeout_time;
1180 timeout_time = TimeValue::Now();
1181 timeout_time.OffsetWithSeconds(2);
1182
1183 EventSP event_sp;
1184 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1185 if (state != eStateStopped)
1186 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001187 }
Chris Lattner24943d22010-06-08 16:52:24 +00001188 return error;
1189}
1190
Greg Clayton4fb400f2010-09-27 21:07:38 +00001191Error
1192ProcessGDBRemote::DoDetach()
1193{
1194 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001195 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001196 if (log)
1197 log->Printf ("ProcessGDBRemote::DoDetach()");
1198
1199 DisableAllBreakpointSites ();
1200
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001201 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001202
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001203 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1204 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001205 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001206 if (response_size)
1207 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1208 else
1209 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001210 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001211 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001212 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001213
Greg Clayton4fb400f2010-09-27 21:07:38 +00001214 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001215 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001216
1217 SetPrivateState (eStateDetached);
1218 ResumePrivateStateThread();
1219
1220 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001221 return error;
1222}
Chris Lattner24943d22010-06-08 16:52:24 +00001223
1224Error
1225ProcessGDBRemote::DoDestroy ()
1226{
1227 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001228 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001229 if (log)
1230 log->Printf ("ProcessGDBRemote::DoDestroy()");
1231
1232 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001233 Mutex::Locker locker;
1234 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001235 DisableAllBreakpointSites ();
1236 SetExitStatus(-1, "process killed");
1237
1238 StringExtractorGDBRemote response;
Greg Claytonb749a262010-12-03 06:02:24 +00001239 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 1, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001240 {
Caroline Tice926060e2010-10-29 21:48:37 +00001241 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001242 if (log)
1243 {
1244 if (response.IsOKPacket())
1245 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1246 else
1247 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1248 }
1249 }
1250
1251 StopAsyncThread ();
1252 m_gdb_comm.StopReadThread();
1253 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001254 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001255 return error;
1256}
1257
Chris Lattner24943d22010-06-08 16:52:24 +00001258//------------------------------------------------------------------
1259// Process Queries
1260//------------------------------------------------------------------
1261
1262bool
1263ProcessGDBRemote::IsAlive ()
1264{
Greg Clayton58e844b2010-12-08 05:08:21 +00001265 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001266}
1267
1268addr_t
1269ProcessGDBRemote::GetImageInfoAddress()
1270{
1271 if (!m_gdb_comm.IsRunning())
1272 {
1273 StringExtractorGDBRemote response;
1274 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1275 {
1276 if (response.IsNormalPacket())
1277 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1278 }
1279 }
1280 return LLDB_INVALID_ADDRESS;
1281}
1282
1283DynamicLoader *
1284ProcessGDBRemote::GetDynamicLoader()
1285{
1286 return m_dynamic_loader_ap.get();
1287}
1288
1289//------------------------------------------------------------------
1290// Process Memory
1291//------------------------------------------------------------------
1292size_t
1293ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1294{
1295 if (size > m_max_memory_size)
1296 {
1297 // Keep memory read sizes down to a sane limit. This function will be
1298 // called multiple times in order to complete the task by
1299 // lldb_private::Process so it is ok to do this.
1300 size = m_max_memory_size;
1301 }
1302
1303 char packet[64];
1304 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1305 assert (packet_len + 1 < sizeof(packet));
1306 StringExtractorGDBRemote response;
1307 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1308 {
1309 if (response.IsNormalPacket())
1310 {
1311 error.Clear();
1312 return response.GetHexBytes(buf, size, '\xdd');
1313 }
1314 else if (response.IsErrorPacket())
1315 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1316 else if (response.IsUnsupportedPacket())
1317 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1318 else
1319 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1320 }
1321 else
1322 {
1323 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1324 }
1325 return 0;
1326}
1327
1328size_t
1329ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1330{
1331 StreamString packet;
1332 packet.Printf("M%llx,%zx:", addr, size);
1333 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1334 StringExtractorGDBRemote response;
1335 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1336 {
1337 if (response.IsOKPacket())
1338 {
1339 error.Clear();
1340 return size;
1341 }
1342 else if (response.IsErrorPacket())
1343 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1344 else if (response.IsUnsupportedPacket())
1345 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1346 else
1347 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1348 }
1349 else
1350 {
1351 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1352 }
1353 return 0;
1354}
1355
1356lldb::addr_t
1357ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1358{
1359 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1360 if (allocated_addr == LLDB_INVALID_ADDRESS)
1361 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1362 else
1363 error.Clear();
1364 return allocated_addr;
1365}
1366
1367Error
1368ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1369{
1370 Error error;
1371 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1372 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1373 return error;
1374}
1375
1376
1377//------------------------------------------------------------------
1378// Process STDIO
1379//------------------------------------------------------------------
1380
1381size_t
1382ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1383{
1384 Mutex::Locker locker(m_stdio_mutex);
1385 size_t bytes_available = m_stdout_data.size();
1386 if (bytes_available > 0)
1387 {
1388 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1389 if (bytes_available > buf_size)
1390 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001391 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001392 m_stdout_data.erase(0, buf_size);
1393 bytes_available = buf_size;
1394 }
1395 else
1396 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001397 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001398 m_stdout_data.clear();
1399
1400 //ResetEventBits(eBroadcastBitSTDOUT);
1401 }
1402 }
1403 return bytes_available;
1404}
1405
1406size_t
1407ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1408{
1409 // Can we get STDERR through the remote protocol?
1410 return 0;
1411}
1412
1413size_t
1414ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1415{
1416 if (m_stdio_communication.IsConnected())
1417 {
1418 ConnectionStatus status;
1419 m_stdio_communication.Write(src, src_len, status, NULL);
1420 }
1421 return 0;
1422}
1423
1424Error
1425ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1426{
1427 Error error;
1428 assert (bp_site != NULL);
1429
Greg Claytone005f2c2010-11-06 01:53:30 +00001430 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001431 user_id_t site_id = bp_site->GetID();
1432 const addr_t addr = bp_site->GetLoadAddress();
1433 if (log)
1434 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1435
1436 if (bp_site->IsEnabled())
1437 {
1438 if (log)
1439 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1440 return error;
1441 }
1442 else
1443 {
1444 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1445
1446 if (bp_site->HardwarePreferred())
1447 {
1448 // Try and set hardware breakpoint, and if that fails, fall through
1449 // and set a software breakpoint?
1450 }
1451
1452 if (m_z0_supported)
1453 {
1454 char packet[64];
1455 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1456 assert (packet_len + 1 < sizeof(packet));
1457 StringExtractorGDBRemote response;
1458 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1459 {
1460 if (response.IsUnsupportedPacket())
1461 {
1462 // Disable z packet support and try again
1463 m_z0_supported = 0;
1464 return EnableBreakpoint (bp_site);
1465 }
1466 else if (response.IsOKPacket())
1467 {
1468 bp_site->SetEnabled(true);
1469 bp_site->SetType (BreakpointSite::eExternal);
1470 return error;
1471 }
1472 else
1473 {
1474 uint8_t error_byte = response.GetError();
1475 if (error_byte)
1476 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1477 }
1478 }
1479 }
1480 else
1481 {
1482 return EnableSoftwareBreakpoint (bp_site);
1483 }
1484 }
1485
1486 if (log)
1487 {
1488 const char *err_string = error.AsCString();
1489 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1490 bp_site->GetLoadAddress(),
1491 err_string ? err_string : "NULL");
1492 }
1493 // We shouldn't reach here on a successful breakpoint enable...
1494 if (error.Success())
1495 error.SetErrorToGenericError();
1496 return error;
1497}
1498
1499Error
1500ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1501{
1502 Error error;
1503 assert (bp_site != NULL);
1504 addr_t addr = bp_site->GetLoadAddress();
1505 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001506 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001507 if (log)
1508 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1509
1510 if (bp_site->IsEnabled())
1511 {
1512 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1513
1514 if (bp_site->IsHardware())
1515 {
1516 // TODO: disable hardware breakpoint...
1517 }
1518 else
1519 {
1520 if (m_z0_supported)
1521 {
1522 char packet[64];
1523 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1524 assert (packet_len + 1 < sizeof(packet));
1525 StringExtractorGDBRemote response;
1526 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1527 {
1528 if (response.IsUnsupportedPacket())
1529 {
1530 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1531 }
1532 else if (response.IsOKPacket())
1533 {
1534 if (log)
1535 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1536 bp_site->SetEnabled(false);
1537 return error;
1538 }
1539 else
1540 {
1541 uint8_t error_byte = response.GetError();
1542 if (error_byte)
1543 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1544 }
1545 }
1546 }
1547 else
1548 {
1549 return DisableSoftwareBreakpoint (bp_site);
1550 }
1551 }
1552 }
1553 else
1554 {
1555 if (log)
1556 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1557 return error;
1558 }
1559
1560 if (error.Success())
1561 error.SetErrorToGenericError();
1562 return error;
1563}
1564
1565Error
1566ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1567{
1568 Error error;
1569 if (wp)
1570 {
1571 user_id_t watchID = wp->GetID();
1572 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001573 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001574 if (log)
1575 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1576 if (wp->IsEnabled())
1577 {
1578 if (log)
1579 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1580 return error;
1581 }
1582 else
1583 {
1584 // Pass down an appropriate z/Z packet...
1585 error.SetErrorString("watchpoints not supported");
1586 }
1587 }
1588 else
1589 {
1590 error.SetErrorString("Watchpoint location argument was NULL.");
1591 }
1592 if (error.Success())
1593 error.SetErrorToGenericError();
1594 return error;
1595}
1596
1597Error
1598ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1599{
1600 Error error;
1601 if (wp)
1602 {
1603 user_id_t watchID = wp->GetID();
1604
Greg Claytone005f2c2010-11-06 01:53:30 +00001605 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001606
1607 addr_t addr = wp->GetLoadAddress();
1608 if (log)
1609 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1610
1611 if (wp->IsHardware())
1612 {
1613 // Pass down an appropriate z/Z packet...
1614 error.SetErrorString("watchpoints not supported");
1615 }
1616 // TODO: clear software watchpoints if we implement them
1617 }
1618 else
1619 {
1620 error.SetErrorString("Watchpoint location argument was NULL.");
1621 }
1622 if (error.Success())
1623 error.SetErrorToGenericError();
1624 return error;
1625}
1626
1627void
1628ProcessGDBRemote::Clear()
1629{
1630 m_flags = 0;
1631 m_thread_list.Clear();
1632 {
1633 Mutex::Locker locker(m_stdio_mutex);
1634 m_stdout_data.clear();
1635 }
Chris Lattner24943d22010-06-08 16:52:24 +00001636}
1637
1638Error
1639ProcessGDBRemote::DoSignal (int signo)
1640{
1641 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001642 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001643 if (log)
1644 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1645
1646 if (!m_gdb_comm.SendAsyncSignal (signo))
1647 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1648 return error;
1649}
1650
Caroline Tice861efb32010-11-16 05:07:41 +00001651//void
1652//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1653//{
1654// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1655// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1656//}
Chris Lattner24943d22010-06-08 16:52:24 +00001657
Caroline Tice861efb32010-11-16 05:07:41 +00001658//void
1659//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1660//{
1661// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1662// Mutex::Locker locker(m_stdio_mutex);
1663// m_stdout_data.append(s, len);
1664//
1665// // FIXME: Make a real data object for this and put it out.
1666// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1667//}
Chris Lattner24943d22010-06-08 16:52:24 +00001668
1669
1670Error
1671ProcessGDBRemote::StartDebugserverProcess
1672(
1673 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1674 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1675 char const *inferior_envp[], // Environment to pass along to the inferior program
1676 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001677 bool launch_process, // Set to true if we are going to be launching a the process
1678 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 +00001679 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1680 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001681 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001682 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1683)
1684{
1685 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001686 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1687 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001688 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1689 {
1690 // If we locate debugserver, keep that located version around
1691 static FileSpec g_debugserver_file_spec;
1692
1693 FileSpec debugserver_file_spec;
1694 char debugserver_path[PATH_MAX];
1695
1696 // Always check to see if we have an environment override for the path
1697 // to the debugserver to use and use it if we do.
1698 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1699 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001700 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001701 else
1702 debugserver_file_spec = g_debugserver_file_spec;
1703 bool debugserver_exists = debugserver_file_spec.Exists();
1704 if (!debugserver_exists)
1705 {
1706 // The debugserver binary is in the LLDB.framework/Resources
1707 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001708 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001709 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001710 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001711 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001712 if (debugserver_exists)
1713 {
1714 g_debugserver_file_spec = debugserver_file_spec;
1715 }
1716 else
1717 {
1718 g_debugserver_file_spec.Clear();
1719 debugserver_file_spec.Clear();
1720 }
Chris Lattner24943d22010-06-08 16:52:24 +00001721 }
1722 }
1723
1724 if (debugserver_exists)
1725 {
1726 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1727
1728 m_stdio_communication.Clear();
1729 posix_spawnattr_t attr;
1730
Greg Claytone005f2c2010-11-06 01:53:30 +00001731 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001732
1733 Error local_err; // Errors that don't affect the spawning.
1734 if (log)
1735 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1736 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1737 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001738 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001739 if (error.Fail())
1740 return error;;
1741
1742#if !defined (__arm__)
1743
Greg Clayton24b48ff2010-10-17 22:03:32 +00001744 // We don't need to do this for ARM, and we really shouldn't now
1745 // that we have multiple CPU subtypes and no posix_spawnattr call
1746 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001747 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001748 {
Greg Claytoncf015052010-06-11 03:25:34 +00001749 cpu_type_t cpu = inferior_arch.GetCPUType();
1750 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1751 {
1752 size_t ocount = 0;
1753 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1754 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001755 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 +00001756
Greg Claytoncf015052010-06-11 03:25:34 +00001757 if (error.Fail() != 0 || ocount != 1)
1758 return error;
1759 }
Chris Lattner24943d22010-06-08 16:52:24 +00001760 }
1761
1762#endif
1763
1764 Args debugserver_args;
1765 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001766
Chris Lattner24943d22010-06-08 16:52:24 +00001767 lldb_utility::PseudoTerminal pty;
Caroline Ticebd666012010-12-03 18:46:09 +00001768 if (launch_process && stdio_path == NULL && m_local_debugserver && !no_stdio)
Chris Lattner24943d22010-06-08 16:52:24 +00001769 {
Chris Lattner24943d22010-06-08 16:52:24 +00001770 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001771 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001772 }
1773
1774 // Start args with "debugserver /file/path -r --"
1775 debugserver_args.AppendArgument(debugserver_path);
1776 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001777 // use native registers, not the GDB registers
1778 debugserver_args.AppendArgument("--native-regs");
1779 // make debugserver run in its own session so signals generated by
1780 // special terminal key sequences (^C) don't affect debugserver
1781 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001782
Greg Clayton452bf612010-08-31 18:35:14 +00001783 if (disable_aslr)
1784 debugserver_args.AppendArguments("--disable-aslr");
1785
Chris Lattner24943d22010-06-08 16:52:24 +00001786 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001787 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001788 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001789 debugserver_args.AppendArgument("--stdio-path");
1790 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001791 }
Caroline Ticebd666012010-12-03 18:46:09 +00001792 else if (launch_process && no_stdio)
1793 {
1794 debugserver_args.AppendArgument("--no-stdio");
1795 }
Chris Lattner24943d22010-06-08 16:52:24 +00001796
1797 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1798 if (env_debugserver_log_file)
1799 {
1800 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1801 debugserver_args.AppendArgument(arg_cstr);
1802 }
1803
1804 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1805 if (env_debugserver_log_flags)
1806 {
1807 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1808 debugserver_args.AppendArgument(arg_cstr);
1809 }
1810// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1811// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1812
1813 // Now append the program arguments
1814 if (launch_process)
1815 {
1816 if (inferior_argv)
1817 {
1818 // Terminate the debugserver args so we can now append the inferior args
1819 debugserver_args.AppendArgument("--");
1820
1821 for (int i = 0; inferior_argv[i] != NULL; ++i)
1822 debugserver_args.AppendArgument (inferior_argv[i]);
1823 }
1824 else
1825 {
1826 // Will send environment entries with the 'QEnvironment:' packet
1827 // Will send arguments with the 'A' packet
1828 }
1829 }
1830 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1831 {
1832 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1833 debugserver_args.AppendArgument (arg_cstr);
1834 }
1835 else if (attach_name && attach_name[0])
1836 {
1837 if (wait_for_launch)
1838 debugserver_args.AppendArgument ("--waitfor");
1839 else
1840 debugserver_args.AppendArgument ("--attach");
1841 debugserver_args.AppendArgument (attach_name);
1842 }
1843
1844 Error file_actions_err;
1845 posix_spawn_file_actions_t file_actions;
1846#if DONT_CLOSE_DEBUGSERVER_STDIO
1847 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1848#else
1849 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1850 if (file_actions_err.Success())
1851 {
1852 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1853 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1854 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1855 }
1856#endif
1857
1858 if (log)
1859 {
1860 StreamString strm;
1861 debugserver_args.Dump (&strm);
1862 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1863 }
1864
1865 error.SetError(::posix_spawnp (&m_debugserver_pid,
1866 debugserver_path,
1867 file_actions_err.Success() ? &file_actions : NULL,
1868 &attr,
1869 debugserver_args.GetArgumentVector(),
1870 (char * const*)inferior_envp),
1871 eErrorTypePOSIX);
1872
Greg Claytone9d0df42010-07-02 01:29:13 +00001873
1874 ::posix_spawnattr_destroy (&attr);
1875
Chris Lattner24943d22010-06-08 16:52:24 +00001876 if (file_actions_err.Success())
1877 ::posix_spawn_file_actions_destroy (&file_actions);
1878
1879 // We have seen some cases where posix_spawnp was returning a valid
1880 // looking pid even when an error was returned, so clear it out
1881 if (error.Fail())
1882 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1883
1884 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001885 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 +00001886
Caroline Ticebd666012010-12-03 18:46:09 +00001887 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00001888 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001889 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001890 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001891 }
Chris Lattner24943d22010-06-08 16:52:24 +00001892 }
1893 else
1894 {
1895 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1896 }
1897
1898 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1899 StartAsyncThread ();
1900 }
1901 return error;
1902}
1903
1904bool
1905ProcessGDBRemote::MonitorDebugserverProcess
1906(
1907 void *callback_baton,
1908 lldb::pid_t debugserver_pid,
1909 int signo, // Zero for no signal
1910 int exit_status // Exit value of process if signal is zero
1911)
1912{
1913 // We pass in the ProcessGDBRemote inferior process it and name it
1914 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1915 // pointer value itself, thus we need the double cast...
1916
1917 // "debugserver_pid" argument passed in is the process ID for
1918 // debugserver that we are tracking...
1919
Greg Clayton75ccf502010-08-21 02:22:51 +00001920 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1921
1922 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001923 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001924 // Sleep for a half a second to make sure our inferior process has
1925 // time to set its exit status before we set it incorrectly when
1926 // both the debugserver and the inferior process shut down.
1927 usleep (500000);
1928 // If our process hasn't yet exited, debugserver might have died.
1929 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001930 const StateType state = process->GetState();
1931
1932 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1933 state != eStateInvalid &&
1934 state != eStateUnloaded &&
1935 state != eStateExited &&
1936 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001937 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001938 char error_str[1024];
1939 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001940 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001941 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1942 if (signal_cstr)
1943 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001944 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001945 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001946 }
1947 else
1948 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001949 ::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 +00001950 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001951
1952 process->SetExitStatus (-1, error_str);
1953 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001954 // Debugserver has exited we need to let our ProcessGDBRemote
1955 // know that it no longer has a debugserver instance
1956 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1957 // We are returning true to this function below, so we can
1958 // forget about the monitor handle.
1959 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001960 }
1961 return true;
1962}
1963
1964void
1965ProcessGDBRemote::KillDebugserverProcess ()
1966{
1967 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1968 {
1969 ::kill (m_debugserver_pid, SIGINT);
1970 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1971 }
1972}
1973
1974void
1975ProcessGDBRemote::Initialize()
1976{
1977 static bool g_initialized = false;
1978
1979 if (g_initialized == false)
1980 {
1981 g_initialized = true;
1982 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1983 GetPluginDescriptionStatic(),
1984 CreateInstance);
1985
1986 Log::Callbacks log_callbacks = {
1987 ProcessGDBRemoteLog::DisableLog,
1988 ProcessGDBRemoteLog::EnableLog,
1989 ProcessGDBRemoteLog::ListLogCategories
1990 };
1991
1992 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1993 }
1994}
1995
1996bool
1997ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1998{
1999 if (m_curr_tid == tid)
2000 return true;
2001
2002 char packet[32];
2003 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2004 assert (packet_len + 1 < sizeof(packet));
2005 StringExtractorGDBRemote response;
2006 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2007 {
2008 if (response.IsOKPacket())
2009 {
2010 m_curr_tid = tid;
2011 return true;
2012 }
2013 }
2014 return false;
2015}
2016
2017bool
2018ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2019{
2020 if (m_curr_tid_run == tid)
2021 return true;
2022
2023 char packet[32];
2024 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2025 assert (packet_len + 1 < sizeof(packet));
2026 StringExtractorGDBRemote response;
2027 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2028 {
2029 if (response.IsOKPacket())
2030 {
2031 m_curr_tid_run = tid;
2032 return true;
2033 }
2034 }
2035 return false;
2036}
2037
2038void
2039ProcessGDBRemote::ResetGDBRemoteState ()
2040{
2041 // Reset and GDB remote state
2042 m_curr_tid = LLDB_INVALID_THREAD_ID;
2043 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2044 m_z0_supported = 1;
2045}
2046
2047
2048bool
2049ProcessGDBRemote::StartAsyncThread ()
2050{
2051 ResetGDBRemoteState ();
2052
Greg Claytone005f2c2010-11-06 01:53:30 +00002053 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002054
2055 if (log)
2056 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2057
2058 // Create a thread that watches our internal state and controls which
2059 // events make it to clients (into the DCProcess event queue).
2060 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2061 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2062}
2063
2064void
2065ProcessGDBRemote::StopAsyncThread ()
2066{
Greg Claytone005f2c2010-11-06 01:53:30 +00002067 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002068
2069 if (log)
2070 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2071
2072 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2073
2074 // Stop the stdio thread
2075 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2076 {
2077 Host::ThreadJoin (m_async_thread, NULL, NULL);
2078 }
2079}
2080
2081
2082void *
2083ProcessGDBRemote::AsyncThread (void *arg)
2084{
2085 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2086
Greg Claytone005f2c2010-11-06 01:53:30 +00002087 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002088 if (log)
2089 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2090
2091 Listener listener ("ProcessGDBRemote::AsyncThread");
2092 EventSP event_sp;
2093 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2094 eBroadcastBitAsyncThreadShouldExit;
2095
2096 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2097 {
2098 bool done = false;
2099 while (!done)
2100 {
Caroline Tice926060e2010-10-29 21:48:37 +00002101 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002102 if (log)
2103 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2104 if (listener.WaitForEvent (NULL, event_sp))
2105 {
2106 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002107 if (log)
2108 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2109
Chris Lattner24943d22010-06-08 16:52:24 +00002110 switch (event_type)
2111 {
2112 case eBroadcastBitAsyncContinue:
2113 {
2114 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2115
2116 if (continue_packet)
2117 {
2118 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2119 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002120 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002121 if (log)
2122 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2123
2124 process->SetPrivateState(eStateRunning);
2125 StringExtractorGDBRemote response;
2126 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2127
2128 switch (stop_state)
2129 {
2130 case eStateStopped:
2131 case eStateCrashed:
2132 case eStateSuspended:
2133 process->m_last_stop_packet = response;
2134 process->m_last_stop_packet.SetFilePos (0);
2135 process->SetPrivateState (stop_state);
2136 break;
2137
2138 case eStateExited:
2139 process->m_last_stop_packet = response;
2140 process->m_last_stop_packet.SetFilePos (0);
2141 response.SetFilePos(1);
2142 process->SetExitStatus(response.GetHexU8(), NULL);
2143 done = true;
2144 break;
2145
2146 case eStateInvalid:
2147 break;
2148
2149 default:
2150 process->SetPrivateState (stop_state);
2151 break;
2152 }
2153 }
2154 }
2155 break;
2156
2157 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002158 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002159 if (log)
2160 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2161 done = true;
2162 break;
2163
2164 default:
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 unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2168 done = true;
2169 break;
2170 }
2171 }
2172 else
2173 {
Caroline Tice926060e2010-10-29 21:48:37 +00002174 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002175 if (log)
2176 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2177 done = true;
2178 }
2179 }
2180 }
2181
Caroline Tice926060e2010-10-29 21:48:37 +00002182 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002183 if (log)
2184 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2185
2186 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2187 return NULL;
2188}
2189
Chris Lattner24943d22010-06-08 16:52:24 +00002190const char *
2191ProcessGDBRemote::GetDispatchQueueNameForThread
2192(
2193 addr_t thread_dispatch_qaddr,
2194 std::string &dispatch_queue_name
2195)
2196{
2197 dispatch_queue_name.clear();
2198 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2199 {
2200 // Cache the dispatch_queue_offsets_addr value so we don't always have
2201 // to look it up
2202 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2203 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002204 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2205 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002206 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002207 if (module_sp)
2208 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2209
2210 if (dispatch_queue_offsets_symbol == NULL)
2211 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002212 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002213 if (module_sp)
2214 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2215 }
Chris Lattner24943d22010-06-08 16:52:24 +00002216 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002217 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002218
2219 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2220 return NULL;
2221 }
2222
2223 uint8_t memory_buffer[8];
2224 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2225
2226 // Excerpt from src/queue_private.h
2227 struct dispatch_queue_offsets_s
2228 {
2229 uint16_t dqo_version;
2230 uint16_t dqo_label;
2231 uint16_t dqo_label_size;
2232 } dispatch_queue_offsets;
2233
2234
2235 Error error;
2236 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2237 {
2238 uint32_t data_offset = 0;
2239 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2240 {
2241 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2242 {
2243 data_offset = 0;
2244 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2245 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2246 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2247 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2248 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2249 dispatch_queue_name.erase (bytes_read);
2250 }
2251 }
2252 }
2253 }
2254 if (dispatch_queue_name.empty())
2255 return NULL;
2256 return dispatch_queue_name.c_str();
2257}
2258
Jim Ingham7508e732010-08-09 23:31:02 +00002259uint32_t
2260ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2261{
2262 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2263 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2264 if (m_local_debugserver)
2265 {
2266 return Host::ListProcessesMatchingName (name, matches, pids);
2267 }
2268 else
2269 {
2270 // FIXME: Implement talking to the remote debugserver.
2271 return 0;
2272 }
2273
2274}