blob: 1c6b164ca6155aeb62b75850387813d0e7bbfc4b [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"
Chris Lattner24943d22010-06-08 16:52:24 +000048#include "MacOSXLibunwindCallbacks.h"
Greg Clayton643ee732010-08-04 01:40:35 +000049#include "StopInfoMachException.h"
50
Chris Lattner24943d22010-06-08 16:52:24 +000051
Chris Lattner24943d22010-06-08 16:52:24 +000052
53#define DEBUGSERVER_BASENAME "debugserver"
54using namespace lldb;
55using namespace lldb_private;
56
57static inline uint16_t
58get_random_port ()
59{
60 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u;
61}
62
63
64const char *
65ProcessGDBRemote::GetPluginNameStatic()
66{
67 return "process.gdb-remote";
68}
69
70const char *
71ProcessGDBRemote::GetPluginDescriptionStatic()
72{
73 return "GDB Remote protocol based debugging plug-in.";
74}
75
76void
77ProcessGDBRemote::Terminate()
78{
79 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
80}
81
82
83Process*
84ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
85{
86 return new ProcessGDBRemote (target, listener);
87}
88
89bool
90ProcessGDBRemote::CanDebug(Target &target)
91{
92 // For now we are just making sure the file exists for a given module
93 ModuleSP exe_module_sp(target.GetExecutableModule());
94 if (exe_module_sp.get())
95 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +000096 // However, if there is no executable module, we return true since we might be preparing to attach.
97 return true;
Chris Lattner24943d22010-06-08 16:52:24 +000098}
99
100//----------------------------------------------------------------------
101// ProcessGDBRemote constructor
102//----------------------------------------------------------------------
103ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
104 Process (target, listener),
105 m_dynamic_loader_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000106 m_flags (0),
107 m_stdio_communication ("gdb-remote.stdio"),
108 m_stdio_mutex (Mutex::eMutexTypeRecursive),
109 m_stdout_data (),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000110 m_byte_order (eByteOrderHost),
Chris Lattner24943d22010-06-08 16:52:24 +0000111 m_gdb_comm(),
112 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
113 m_debugserver_monitor (0),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000114 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000115 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000116 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
117 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000118 m_curr_tid (LLDB_INVALID_THREAD_ID),
119 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000120 m_z0_supported (1),
121 m_continue_packet(),
122 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000123 m_packet_timeout (1),
124 m_max_memory_size (512),
Chris Lattner24943d22010-06-08 16:52:24 +0000125 m_libunwind_target_type (UNW_TARGET_UNSPECIFIED),
126 m_libunwind_addr_space (NULL),
Jim Ingham7508e732010-08-09 23:31:02 +0000127 m_waiting_for_attach (false),
128 m_local_debugserver (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000129{
130}
131
132//----------------------------------------------------------------------
133// Destructor
134//----------------------------------------------------------------------
135ProcessGDBRemote::~ProcessGDBRemote()
136{
137 // m_mach_process.UnregisterNotificationCallbacks (this);
138 Clear();
139}
140
141//----------------------------------------------------------------------
142// PluginInterface
143//----------------------------------------------------------------------
144const char *
145ProcessGDBRemote::GetPluginName()
146{
147 return "Process debugging plug-in that uses the GDB remote protocol";
148}
149
150const char *
151ProcessGDBRemote::GetShortPluginName()
152{
153 return GetPluginNameStatic();
154}
155
156uint32_t
157ProcessGDBRemote::GetPluginVersion()
158{
159 return 1;
160}
161
162void
163ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
164{
165 strm->Printf("TODO: fill this in\n");
166}
167
168Error
169ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
170{
171 Error error;
172 error.SetErrorString("No plug-in commands are currently supported.");
173 return error;
174}
175
176Log *
177ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
178{
179 return NULL;
180}
181
182void
183ProcessGDBRemote::BuildDynamicRegisterInfo ()
184{
185 char register_info_command[64];
186 m_register_info.Clear();
187 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
188 uint32_t reg_offset = 0;
189 uint32_t reg_num = 0;
190 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
191 {
192 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
193 StringExtractorGDBRemote response;
194 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
195 {
196 packet_type = response.GetType();
197 if (packet_type == StringExtractorGDBRemote::eResponse)
198 {
199 std::string name;
200 std::string value;
201 ConstString reg_name;
202 ConstString alt_name;
203 ConstString set_name;
204 RegisterInfo reg_info = { NULL, // Name
205 NULL, // Alt name
206 0, // byte size
207 reg_offset, // offset
208 eEncodingUint, // encoding
209 eFormatHex, // formate
210 reg_num, // native register number
211 {
212 LLDB_INVALID_REGNUM, // GCC reg num
213 LLDB_INVALID_REGNUM, // DWARF reg num
214 LLDB_INVALID_REGNUM, // generic reg num
215 reg_num // GDB reg num
216 }
217 };
218
219 while (response.GetNameColonValue(name, value))
220 {
221 if (name.compare("name") == 0)
222 {
223 reg_name.SetCString(value.c_str());
224 }
225 else if (name.compare("alt-name") == 0)
226 {
227 alt_name.SetCString(value.c_str());
228 }
229 else if (name.compare("bitsize") == 0)
230 {
231 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
232 }
233 else if (name.compare("offset") == 0)
234 {
235 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000236 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000237 {
238 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000239 }
240 }
241 else if (name.compare("encoding") == 0)
242 {
243 if (value.compare("uint") == 0)
244 reg_info.encoding = eEncodingUint;
245 else if (value.compare("sint") == 0)
246 reg_info.encoding = eEncodingSint;
247 else if (value.compare("ieee754") == 0)
248 reg_info.encoding = eEncodingIEEE754;
249 else if (value.compare("vector") == 0)
250 reg_info.encoding = eEncodingVector;
251 }
252 else if (name.compare("format") == 0)
253 {
254 if (value.compare("binary") == 0)
255 reg_info.format = eFormatBinary;
256 else if (value.compare("decimal") == 0)
257 reg_info.format = eFormatDecimal;
258 else if (value.compare("hex") == 0)
259 reg_info.format = eFormatHex;
260 else if (value.compare("float") == 0)
261 reg_info.format = eFormatFloat;
262 else if (value.compare("vector-sint8") == 0)
263 reg_info.format = eFormatVectorOfSInt8;
264 else if (value.compare("vector-uint8") == 0)
265 reg_info.format = eFormatVectorOfUInt8;
266 else if (value.compare("vector-sint16") == 0)
267 reg_info.format = eFormatVectorOfSInt16;
268 else if (value.compare("vector-uint16") == 0)
269 reg_info.format = eFormatVectorOfUInt16;
270 else if (value.compare("vector-sint32") == 0)
271 reg_info.format = eFormatVectorOfSInt32;
272 else if (value.compare("vector-uint32") == 0)
273 reg_info.format = eFormatVectorOfUInt32;
274 else if (value.compare("vector-float32") == 0)
275 reg_info.format = eFormatVectorOfFloat32;
276 else if (value.compare("vector-uint128") == 0)
277 reg_info.format = eFormatVectorOfUInt128;
278 }
279 else if (name.compare("set") == 0)
280 {
281 set_name.SetCString(value.c_str());
282 }
283 else if (name.compare("gcc") == 0)
284 {
285 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
286 }
287 else if (name.compare("dwarf") == 0)
288 {
289 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
290 }
291 else if (name.compare("generic") == 0)
292 {
293 if (value.compare("pc") == 0)
294 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
295 else if (value.compare("sp") == 0)
296 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
297 else if (value.compare("fp") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
299 else if (value.compare("ra") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
301 else if (value.compare("flags") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
303 }
304 }
305
Jason Molenda53d96862010-06-11 23:44:18 +0000306 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000307 assert (reg_info.byte_size != 0);
308 reg_offset += reg_info.byte_size;
309 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
310 }
311 }
312 else
313 {
314 packet_type = StringExtractorGDBRemote::eError;
315 }
316 }
317
318 if (reg_num == 0)
319 {
320 // We didn't get anything. See if we are debugging ARM and fill with
321 // a hard coded register set until we can get an updated debugserver
322 // down on the devices.
323 ArchSpec arm_arch ("arm");
324 if (GetTarget().GetArchitecture() == arm_arch)
325 m_register_info.HardcodeARMRegisters();
326 }
327 m_register_info.Finalize ();
328}
329
330Error
331ProcessGDBRemote::WillLaunch (Module* module)
332{
333 return WillLaunchOrAttach ();
334}
335
336Error
337ProcessGDBRemote::WillAttach (lldb::pid_t pid)
338{
339 return WillLaunchOrAttach ();
340}
341
342Error
343ProcessGDBRemote::WillAttach (const char *process_name, bool wait_for_launch)
344{
345 return WillLaunchOrAttach ();
346}
347
348Error
349ProcessGDBRemote::WillLaunchOrAttach ()
350{
351 Error error;
352 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
353 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
354
355 if (m_dynamic_loader_ap.get() == NULL)
356 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
357 m_stdio_communication.Clear ();
358
359 return error;
360}
361
362//----------------------------------------------------------------------
363// Process Control
364//----------------------------------------------------------------------
365Error
366ProcessGDBRemote::DoLaunch
367(
368 Module* module,
369 char const *argv[],
370 char const *envp[],
371 const char *stdin_path,
372 const char *stdout_path,
373 const char *stderr_path
374)
375{
376 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
377 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
378 // ::LogSetLogFile ("/dev/stdout");
379 Error error;
380
381 ObjectFile * object_file = module->GetObjectFile();
382 if (object_file)
383 {
384 ArchSpec inferior_arch(module->GetArchitecture());
385 char host_port[128];
386 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
387
388 bool start_debugserver_with_inferior_args = false;
389 if (start_debugserver_with_inferior_args)
390 {
391 // We want to launch debugserver with the inferior program and its
392 // arguments on the command line. We should only do this if we
393 // the GDB server we are talking to doesn't support the 'A' packet.
394 error = StartDebugserverProcess (host_port,
395 argv,
396 envp,
397 NULL, //stdin_path,
398 LLDB_INVALID_PROCESS_ID,
399 NULL, false,
400 inferior_arch);
401 if (error.Fail())
402 return error;
403
404 error = ConnectToDebugserver (host_port);
405 if (error.Success())
406 {
407 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
408 }
409 }
410 else
411 {
412 error = StartDebugserverProcess (host_port,
413 NULL,
414 NULL,
415 NULL, //stdin_path,
416 LLDB_INVALID_PROCESS_ID,
417 NULL, false,
418 inferior_arch);
419 if (error.Fail())
420 return error;
421
422 error = ConnectToDebugserver (host_port);
423 if (error.Success())
424 {
425 // Send the environment and the program + arguments after we connect
426 if (envp)
427 {
428 const char *env_entry;
429 for (int i=0; (env_entry = envp[i]); ++i)
430 {
431 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
432 break;
433 }
434 }
435
Greg Clayton960d6a42010-08-03 00:35:52 +0000436 // FIXME: convert this to use the new set/show variables when they are available
437#if 0
438 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
439 {
440 const uint32_t attach_debugserver_secs = 10;
441 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
442 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
443 {
444 printf ("%i\n", attach_debugserver_secs - i);
445 sleep (1);
446 }
447 }
448#endif
449
Chris Lattner24943d22010-06-08 16:52:24 +0000450 const uint32_t arg_timeout_seconds = 10;
451 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
452 if (arg_packet_err == 0)
453 {
454 std::string error_str;
455 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
456 {
457 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
458 }
459 else
460 {
461 error.SetErrorString (error_str.c_str());
462 }
463 }
464 else
465 {
466 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
467 }
468
469 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
470 }
471 }
472
473 if (GetID() == LLDB_INVALID_PROCESS_ID)
474 {
475 KillDebugserverProcess ();
476 return error;
477 }
478
479 StringExtractorGDBRemote response;
480 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
481 SetPrivateState (SetThreadStopInfo (response));
482
483 }
484 else
485 {
486 // Set our user ID to an invalid process ID.
487 SetID(LLDB_INVALID_PROCESS_ID);
488 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
489 }
490
491 // Return the process ID we have
492 return error;
493}
494
495
496Error
497ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
498{
499 Error error;
500 // Sleep and wait a bit for debugserver to start to listen...
501 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
502 if (conn_ap.get())
503 {
504 std::string connect_url("connect://");
505 connect_url.append (host_port);
506 const uint32_t max_retry_count = 50;
507 uint32_t retry_count = 0;
508 while (!m_gdb_comm.IsConnected())
509 {
510 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
511 {
512 m_gdb_comm.SetConnection (conn_ap.release());
513 break;
514 }
515 retry_count++;
516
517 if (retry_count >= max_retry_count)
518 break;
519
520 usleep (100000);
521 }
522 }
523
524 if (!m_gdb_comm.IsConnected())
525 {
526 if (error.Success())
527 error.SetErrorString("not connected to remote gdb server");
528 return error;
529 }
530
531 m_gdb_comm.SetAckMode (true);
532 if (m_gdb_comm.StartReadThread(&error))
533 {
534 // Send an initial ack
535 m_gdb_comm.SendAck('+');
536
537 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
538 m_debugserver_monitor = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
539 (void*)(intptr_t)GetID(), // Pass the inferior pid in the thread argument (which is a void *)
540 m_debugserver_pid,
541 false);
542
543 StringExtractorGDBRemote response;
544 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
545 {
546 if (response.IsOKPacket())
547 m_gdb_comm.SetAckMode (false);
548 }
549
550 BuildDynamicRegisterInfo ();
551 }
552 return error;
553}
554
555void
556ProcessGDBRemote::DidLaunchOrAttach ()
557{
558 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
559 if (GetID() == LLDB_INVALID_PROCESS_ID)
560 {
561 m_dynamic_loader_ap.reset();
562 }
563 else
564 {
565 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
566
Jim Ingham7508e732010-08-09 23:31:02 +0000567 Module * exe_module = GetTarget().GetExecutableModule ().get();
Chris Lattner24943d22010-06-08 16:52:24 +0000568 assert(exe_module);
569
Chris Lattner24943d22010-06-08 16:52:24 +0000570 ObjectFile *exe_objfile = exe_module->GetObjectFile();
571 assert(exe_objfile);
572
573 m_byte_order = exe_objfile->GetByteOrder();
574 assert (m_byte_order != eByteOrderInvalid);
575
576 StreamString strm;
577
578 ArchSpec inferior_arch;
579 // See if the GDB server supports the qHostInfo information
580 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
581 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Jim Ingham7508e732010-08-09 23:31:02 +0000582 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000583
Jim Ingham7508e732010-08-09 23:31:02 +0000584 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000585 {
586 // For ARM we can't trust the arch of the process as it could
587 // have an armv6 object file, but be running on armv7 kernel.
588 inferior_arch = m_gdb_comm.GetHostArchitecture();
589 }
590
591 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000592 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000593
594 if (vendor == NULL)
595 vendor = Host::GetVendorString().AsCString("apple");
596
597 if (os_type == NULL)
598 os_type = Host::GetOSString().AsCString("darwin");
599
600 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
601
602 std::transform (strm.GetString().begin(),
603 strm.GetString().end(),
604 strm.GetString().begin(),
605 ::tolower);
606
607 m_target_triple.SetCString(strm.GetString().c_str());
608 }
609}
610
611void
612ProcessGDBRemote::DidLaunch ()
613{
614 DidLaunchOrAttach ();
615 if (m_dynamic_loader_ap.get())
616 m_dynamic_loader_ap->DidLaunch();
617}
618
619Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000620ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000621{
622 Error error;
623 // Clear out and clean up from any current state
624 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000625 ArchSpec arch_spec = GetTarget().GetArchitecture();
626
Chris Lattner24943d22010-06-08 16:52:24 +0000627 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Jim Ingham7508e732010-08-09 23:31:02 +0000628
629
Chris Lattner24943d22010-06-08 16:52:24 +0000630 if (attach_pid != LLDB_INVALID_PROCESS_ID)
631 {
632 SetPrivateState (eStateAttaching);
633 char host_port[128];
634 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
635 error = StartDebugserverProcess (host_port,
636 NULL,
637 NULL,
638 NULL,
639 LLDB_INVALID_PROCESS_ID,
640 NULL, false,
Jim Ingham7508e732010-08-09 23:31:02 +0000641 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000642
643 if (error.Fail())
644 {
645 const char *error_string = error.AsCString();
646 if (error_string == NULL)
647 error_string = "unable to launch " DEBUGSERVER_BASENAME;
648
649 SetExitStatus (-1, error_string);
650 }
651 else
652 {
653 error = ConnectToDebugserver (host_port);
654 if (error.Success())
655 {
656 char packet[64];
657 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
658 StringExtractorGDBRemote response;
659 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
660 packet,
661 packet_len,
662 response);
663 switch (stop_state)
664 {
665 case eStateStopped:
666 case eStateCrashed:
667 case eStateSuspended:
668 SetID (attach_pid);
669 m_last_stop_packet = response;
670 m_last_stop_packet.SetFilePos (0);
671 SetPrivateState (stop_state);
672 break;
673
674 case eStateExited:
675 m_last_stop_packet = response;
676 m_last_stop_packet.SetFilePos (0);
677 response.SetFilePos(1);
678 SetExitStatus(response.GetHexU8(), NULL);
679 break;
680
681 default:
682 SetExitStatus(-1, "unable to attach to process");
683 break;
684 }
685
686 }
687 }
688 }
689
690 lldb::pid_t pid = GetID();
691 if (pid == LLDB_INVALID_PROCESS_ID)
692 {
693 KillDebugserverProcess();
694 }
695 return error;
696}
697
698size_t
699ProcessGDBRemote::AttachInputReaderCallback
700(
701 void *baton,
702 InputReader *reader,
703 lldb::InputReaderAction notification,
704 const char *bytes,
705 size_t bytes_len
706)
707{
708 if (notification == eInputReaderGotToken)
709 {
710 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
711 if (gdb_process->m_waiting_for_attach)
712 gdb_process->m_waiting_for_attach = false;
713 reader->SetIsDone(true);
714 return 1;
715 }
716 return 0;
717}
718
719Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000720ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000721{
722 Error error;
723 // Clear out and clean up from any current state
724 Clear();
725 // HACK: require arch be set correctly at the target level until we can
726 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000727
728 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
729 if (process_name && process_name[0])
730 {
731
732 SetPrivateState (eStateAttaching);
733 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000734 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000735 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
736 error = StartDebugserverProcess (host_port,
737 NULL,
738 NULL,
739 NULL,
740 LLDB_INVALID_PROCESS_ID,
741 NULL, false,
Jim Ingham7508e732010-08-09 23:31:02 +0000742 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000743 if (error.Fail())
744 {
745 const char *error_string = error.AsCString();
746 if (error_string == NULL)
747 error_string = "unable to launch " DEBUGSERVER_BASENAME;
748
749 SetExitStatus (-1, error_string);
750 }
751 else
752 {
753 error = ConnectToDebugserver (host_port);
754 if (error.Success())
755 {
756 StreamString packet;
757
758 packet.PutCString("vAttach");
759 if (wait_for_launch)
760 packet.PutCString("Wait");
761 packet.PutChar(';');
762 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
763 StringExtractorGDBRemote response;
764 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
765 packet.GetData(),
766 packet.GetSize(),
767 response);
768 switch (stop_state)
769 {
770 case eStateStopped:
771 case eStateCrashed:
772 case eStateSuspended:
773 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
774 m_last_stop_packet = response;
775 m_last_stop_packet.SetFilePos (0);
776 SetPrivateState (stop_state);
777 break;
778
779 case eStateExited:
780 m_last_stop_packet = response;
781 m_last_stop_packet.SetFilePos (0);
782 response.SetFilePos(1);
783 SetExitStatus(response.GetHexU8(), NULL);
784 break;
785
786 default:
787 SetExitStatus(-1, "unable to attach to process");
788 break;
789 }
790 }
791 }
792 }
793
794 lldb::pid_t pid = GetID();
795 if (pid == LLDB_INVALID_PROCESS_ID)
796 {
797 KillDebugserverProcess();
798 }
799 return error;
800}
801
802//
803// if (wait_for_launch)
804// {
805// InputReaderSP reader_sp (new InputReader());
806// StreamString instructions;
807// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
808// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
809// this, // baton
810// eInputReaderGranularityByte,
811// NULL, // End token
812// false);
813//
814// StringExtractorGDBRemote response;
815// m_waiting_for_attach = true;
816// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
817// while (m_waiting_for_attach)
818// {
819// // Wait for one second for the stop reply packet
820// if (m_gdb_comm.WaitForPacket(response, 1))
821// {
822// // Got some sort of packet, see if it is the stop reply packet?
823// char ch = response.GetChar(0);
824// if (ch == 'T')
825// {
826// m_waiting_for_attach = false;
827// }
828// }
829// else
830// {
831// // Put a period character every second
832// fputc('.', reader_out_fh);
833// }
834// }
835// }
836// }
837// return GetID();
838//}
839
840void
841ProcessGDBRemote::DidAttach ()
842{
Jim Ingham7508e732010-08-09 23:31:02 +0000843 // If we haven't got an executable module yet, then we should make a dynamic loader, and
844 // see if it can find the executable module for us. If we do have an executable module,
845 // make sure it matches the process we've just attached to.
846
847 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
848 if (!m_dynamic_loader_ap.get())
849 {
850 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
851 }
852
Chris Lattner24943d22010-06-08 16:52:24 +0000853 if (m_dynamic_loader_ap.get())
854 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000855
856 Module * new_exe_module = GetTarget().GetExecutableModule().get();
857 if (new_exe_module == NULL)
858 {
859
860 }
861
862 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000863}
864
865Error
866ProcessGDBRemote::WillResume ()
867{
868 m_continue_packet.Clear();
869 // Start the continue packet we will use to run the target. Each thread
870 // will append what it is supposed to be doing to this packet when the
871 // ThreadList::WillResume() is called. If a thread it supposed
872 // to stay stopped, then don't append anything to this string.
873 m_continue_packet.Printf("vCont");
874 return Error();
875}
876
877Error
878ProcessGDBRemote::DoResume ()
879{
880 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
881 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
882 return Error();
883}
884
885size_t
886ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
887{
888 const uint8_t *trap_opcode = NULL;
889 uint32_t trap_opcode_size = 0;
890
891 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
892 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
893 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
894 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
895
Jim Ingham7508e732010-08-09 23:31:02 +0000896 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000897 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000898 {
Greg Claytoncf015052010-06-11 03:25:34 +0000899 case ArchSpec::eCPU_i386:
900 case ArchSpec::eCPU_x86_64:
901 trap_opcode = g_i386_breakpoint_opcode;
902 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
903 break;
904
905 case ArchSpec::eCPU_arm:
906 // TODO: fill this in for ARM. We need to dig up the symbol for
907 // the address in the breakpoint locaiton and figure out if it is
908 // an ARM or Thumb breakpoint.
909 trap_opcode = g_arm_breakpoint_opcode;
910 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
911 break;
912
913 case ArchSpec::eCPU_ppc:
914 case ArchSpec::eCPU_ppc64:
915 trap_opcode = g_ppc_breakpoint_opcode;
916 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
917 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000918
Greg Claytoncf015052010-06-11 03:25:34 +0000919 default:
920 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
921 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000922 }
923
924 if (trap_opcode && trap_opcode_size)
925 {
926 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
927 return trap_opcode_size;
928 }
929 return 0;
930}
931
932uint32_t
933ProcessGDBRemote::UpdateThreadListIfNeeded ()
934{
935 // locker will keep a mutex locked until it goes out of scope
936 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD);
937 if (log && log->GetMask().IsSet(GDBR_LOG_VERBOSE))
938 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
939
940 const uint32_t stop_id = GetStopID();
941 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
942 {
943 // Update the thread list's stop id immediately so we don't recurse into this function.
944 ThreadList curr_thread_list (this);
945 curr_thread_list.SetStopID(stop_id);
946
947 Error err;
948 StringExtractorGDBRemote response;
949 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
950 response.IsNormalPacket();
951 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
952 {
953 char ch = response.GetChar();
954 if (ch == 'l')
955 break;
956 if (ch == 'm')
957 {
958 do
959 {
960 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
961
962 if (tid != LLDB_INVALID_THREAD_ID)
963 {
964 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
965 if (thread_sp)
966 thread_sp->GetRegisterContext()->Invalidate();
967 else
968 thread_sp.reset (new ThreadGDBRemote (*this, tid));
969 curr_thread_list.AddThread(thread_sp);
970 }
971
972 ch = response.GetChar();
973 } while (ch == ',');
974 }
975 }
976
977 m_thread_list = curr_thread_list;
978
979 SetThreadStopInfo (m_last_stop_packet);
980 }
981 return GetThreadList().GetSize(false);
982}
983
984
985StateType
986ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
987{
988 const char stop_type = stop_packet.GetChar();
989 switch (stop_type)
990 {
991 case 'T':
992 case 'S':
993 {
994 // Stop with signal and thread info
995 const uint8_t signo = stop_packet.GetHexU8();
996 std::string name;
997 std::string value;
998 std::string thread_name;
999 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001000 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001001 uint32_t tid = LLDB_INVALID_THREAD_ID;
1002 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1003 uint32_t exc_data_count = 0;
1004 while (stop_packet.GetNameColonValue(name, value))
1005 {
1006 if (name.compare("metype") == 0)
1007 {
1008 // exception type in big endian hex
1009 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1010 }
1011 else if (name.compare("mecount") == 0)
1012 {
1013 // exception count in big endian hex
1014 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1015 }
1016 else if (name.compare("medata") == 0)
1017 {
1018 // exception data in big endian hex
1019 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1020 }
1021 else if (name.compare("thread") == 0)
1022 {
1023 // thread in big endian hex
1024 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1025 }
1026 else if (name.compare("name") == 0)
1027 {
1028 thread_name.swap (value);
1029 }
1030 else if (name.compare("dispatchqaddr") == 0)
1031 {
1032 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1033 }
1034 }
1035 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1036
1037 if (thread_sp)
1038 {
1039 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1040
1041 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1042 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001043 if (exc_type != 0)
1044 {
Greg Clayton643ee732010-08-04 01:40:35 +00001045 const size_t exc_data_count = exc_data.size();
1046
1047 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1048 exc_type,
1049 exc_data_count,
1050 exc_data_count >= 1 ? exc_data[0] : 0,
1051 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001052 }
1053 else if (signo)
1054 {
Greg Clayton643ee732010-08-04 01:40:35 +00001055 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001056 }
1057 else
1058 {
Greg Clayton643ee732010-08-04 01:40:35 +00001059 StopInfoSP invalid_stop_info_sp;
1060 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001061 }
1062 }
1063 return eStateStopped;
1064 }
1065 break;
1066
1067 case 'W':
1068 // process exited
1069 return eStateExited;
1070
1071 default:
1072 break;
1073 }
1074 return eStateInvalid;
1075}
1076
1077void
1078ProcessGDBRemote::RefreshStateAfterStop ()
1079{
Jim Ingham7508e732010-08-09 23:31:02 +00001080 // FIXME - add a variable to tell that we're in the middle of attaching if we
1081 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001082 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001083// if (!GetTarget().GetArchitecture().IsValid())
1084// {
1085// Module *exe_module = GetTarget().GetExecutableModule().get();
1086// if (exe_module)
1087// m_arch_spec = exe_module->GetArchitecture();
1088// }
1089
Chris Lattner24943d22010-06-08 16:52:24 +00001090 // Let all threads recover from stopping and do any clean up based
1091 // on the previous thread state (if any).
1092 m_thread_list.RefreshStateAfterStop();
1093
1094 // Discover new threads:
1095 UpdateThreadListIfNeeded ();
1096}
1097
1098Error
1099ProcessGDBRemote::DoHalt ()
1100{
1101 Error error;
1102 if (m_gdb_comm.IsRunning())
1103 {
1104 bool timed_out = false;
1105 if (!m_gdb_comm.SendInterrupt (2, &timed_out))
1106 {
1107 if (timed_out)
1108 error.SetErrorString("timed out sending interrupt packet");
1109 else
1110 error.SetErrorString("unknown error sending interrupt packet");
1111 }
1112 }
1113 return error;
1114}
1115
1116Error
1117ProcessGDBRemote::WillDetach ()
1118{
1119 Error error;
1120 const StateType state = m_private_state.GetValue();
1121
1122 if (IsRunning(state))
1123 error.SetErrorString("Process must be stopped in order to detach.");
1124
1125 return error;
1126}
1127
1128
1129Error
1130ProcessGDBRemote::DoDestroy ()
1131{
1132 Error error;
1133 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1134 if (log)
1135 log->Printf ("ProcessGDBRemote::DoDestroy()");
1136
1137 // Interrupt if our inferior is running...
1138 m_gdb_comm.SendInterrupt (1);
1139 DisableAllBreakpointSites ();
1140 SetExitStatus(-1, "process killed");
1141
1142 StringExtractorGDBRemote response;
1143 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1144 {
1145 if (log)
1146 {
1147 if (response.IsOKPacket())
1148 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1149 else
1150 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1151 }
1152 }
1153
1154 StopAsyncThread ();
1155 m_gdb_comm.StopReadThread();
1156 KillDebugserverProcess ();
1157 return error;
1158}
1159
1160ByteOrder
1161ProcessGDBRemote::GetByteOrder () const
1162{
1163 return m_byte_order;
1164}
1165
1166//------------------------------------------------------------------
1167// Process Queries
1168//------------------------------------------------------------------
1169
1170bool
1171ProcessGDBRemote::IsAlive ()
1172{
1173 return m_gdb_comm.IsConnected();
1174}
1175
1176addr_t
1177ProcessGDBRemote::GetImageInfoAddress()
1178{
1179 if (!m_gdb_comm.IsRunning())
1180 {
1181 StringExtractorGDBRemote response;
1182 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1183 {
1184 if (response.IsNormalPacket())
1185 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1186 }
1187 }
1188 return LLDB_INVALID_ADDRESS;
1189}
1190
1191DynamicLoader *
1192ProcessGDBRemote::GetDynamicLoader()
1193{
1194 return m_dynamic_loader_ap.get();
1195}
1196
1197//------------------------------------------------------------------
1198// Process Memory
1199//------------------------------------------------------------------
1200size_t
1201ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1202{
1203 if (size > m_max_memory_size)
1204 {
1205 // Keep memory read sizes down to a sane limit. This function will be
1206 // called multiple times in order to complete the task by
1207 // lldb_private::Process so it is ok to do this.
1208 size = m_max_memory_size;
1209 }
1210
1211 char packet[64];
1212 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1213 assert (packet_len + 1 < sizeof(packet));
1214 StringExtractorGDBRemote response;
1215 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1216 {
1217 if (response.IsNormalPacket())
1218 {
1219 error.Clear();
1220 return response.GetHexBytes(buf, size, '\xdd');
1221 }
1222 else if (response.IsErrorPacket())
1223 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1224 else if (response.IsUnsupportedPacket())
1225 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1226 else
1227 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1228 }
1229 else
1230 {
1231 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1232 }
1233 return 0;
1234}
1235
1236size_t
1237ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1238{
1239 StreamString packet;
1240 packet.Printf("M%llx,%zx:", addr, size);
1241 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1242 StringExtractorGDBRemote response;
1243 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1244 {
1245 if (response.IsOKPacket())
1246 {
1247 error.Clear();
1248 return size;
1249 }
1250 else if (response.IsErrorPacket())
1251 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1252 else if (response.IsUnsupportedPacket())
1253 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1254 else
1255 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1256 }
1257 else
1258 {
1259 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1260 }
1261 return 0;
1262}
1263
1264lldb::addr_t
1265ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1266{
1267 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1268 if (allocated_addr == LLDB_INVALID_ADDRESS)
1269 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1270 else
1271 error.Clear();
1272 return allocated_addr;
1273}
1274
1275Error
1276ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1277{
1278 Error error;
1279 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1280 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1281 return error;
1282}
1283
1284
1285//------------------------------------------------------------------
1286// Process STDIO
1287//------------------------------------------------------------------
1288
1289size_t
1290ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1291{
1292 Mutex::Locker locker(m_stdio_mutex);
1293 size_t bytes_available = m_stdout_data.size();
1294 if (bytes_available > 0)
1295 {
1296 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1297 if (bytes_available > buf_size)
1298 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001299 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001300 m_stdout_data.erase(0, buf_size);
1301 bytes_available = buf_size;
1302 }
1303 else
1304 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001305 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001306 m_stdout_data.clear();
1307
1308 //ResetEventBits(eBroadcastBitSTDOUT);
1309 }
1310 }
1311 return bytes_available;
1312}
1313
1314size_t
1315ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1316{
1317 // Can we get STDERR through the remote protocol?
1318 return 0;
1319}
1320
1321size_t
1322ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1323{
1324 if (m_stdio_communication.IsConnected())
1325 {
1326 ConnectionStatus status;
1327 m_stdio_communication.Write(src, src_len, status, NULL);
1328 }
1329 return 0;
1330}
1331
1332Error
1333ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1334{
1335 Error error;
1336 assert (bp_site != NULL);
1337
1338 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1339 user_id_t site_id = bp_site->GetID();
1340 const addr_t addr = bp_site->GetLoadAddress();
1341 if (log)
1342 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1343
1344 if (bp_site->IsEnabled())
1345 {
1346 if (log)
1347 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1348 return error;
1349 }
1350 else
1351 {
1352 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1353
1354 if (bp_site->HardwarePreferred())
1355 {
1356 // Try and set hardware breakpoint, and if that fails, fall through
1357 // and set a software breakpoint?
1358 }
1359
1360 if (m_z0_supported)
1361 {
1362 char packet[64];
1363 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1364 assert (packet_len + 1 < sizeof(packet));
1365 StringExtractorGDBRemote response;
1366 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1367 {
1368 if (response.IsUnsupportedPacket())
1369 {
1370 // Disable z packet support and try again
1371 m_z0_supported = 0;
1372 return EnableBreakpoint (bp_site);
1373 }
1374 else if (response.IsOKPacket())
1375 {
1376 bp_site->SetEnabled(true);
1377 bp_site->SetType (BreakpointSite::eExternal);
1378 return error;
1379 }
1380 else
1381 {
1382 uint8_t error_byte = response.GetError();
1383 if (error_byte)
1384 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1385 }
1386 }
1387 }
1388 else
1389 {
1390 return EnableSoftwareBreakpoint (bp_site);
1391 }
1392 }
1393
1394 if (log)
1395 {
1396 const char *err_string = error.AsCString();
1397 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1398 bp_site->GetLoadAddress(),
1399 err_string ? err_string : "NULL");
1400 }
1401 // We shouldn't reach here on a successful breakpoint enable...
1402 if (error.Success())
1403 error.SetErrorToGenericError();
1404 return error;
1405}
1406
1407Error
1408ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1409{
1410 Error error;
1411 assert (bp_site != NULL);
1412 addr_t addr = bp_site->GetLoadAddress();
1413 user_id_t site_id = bp_site->GetID();
1414 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1415 if (log)
1416 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1417
1418 if (bp_site->IsEnabled())
1419 {
1420 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1421
1422 if (bp_site->IsHardware())
1423 {
1424 // TODO: disable hardware breakpoint...
1425 }
1426 else
1427 {
1428 if (m_z0_supported)
1429 {
1430 char packet[64];
1431 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1432 assert (packet_len + 1 < sizeof(packet));
1433 StringExtractorGDBRemote response;
1434 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1435 {
1436 if (response.IsUnsupportedPacket())
1437 {
1438 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1439 }
1440 else if (response.IsOKPacket())
1441 {
1442 if (log)
1443 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1444 bp_site->SetEnabled(false);
1445 return error;
1446 }
1447 else
1448 {
1449 uint8_t error_byte = response.GetError();
1450 if (error_byte)
1451 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1452 }
1453 }
1454 }
1455 else
1456 {
1457 return DisableSoftwareBreakpoint (bp_site);
1458 }
1459 }
1460 }
1461 else
1462 {
1463 if (log)
1464 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1465 return error;
1466 }
1467
1468 if (error.Success())
1469 error.SetErrorToGenericError();
1470 return error;
1471}
1472
1473Error
1474ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1475{
1476 Error error;
1477 if (wp)
1478 {
1479 user_id_t watchID = wp->GetID();
1480 addr_t addr = wp->GetLoadAddress();
1481 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1482 if (log)
1483 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1484 if (wp->IsEnabled())
1485 {
1486 if (log)
1487 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1488 return error;
1489 }
1490 else
1491 {
1492 // Pass down an appropriate z/Z packet...
1493 error.SetErrorString("watchpoints not supported");
1494 }
1495 }
1496 else
1497 {
1498 error.SetErrorString("Watchpoint location argument was NULL.");
1499 }
1500 if (error.Success())
1501 error.SetErrorToGenericError();
1502 return error;
1503}
1504
1505Error
1506ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1507{
1508 Error error;
1509 if (wp)
1510 {
1511 user_id_t watchID = wp->GetID();
1512
1513 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1514
1515 addr_t addr = wp->GetLoadAddress();
1516 if (log)
1517 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1518
1519 if (wp->IsHardware())
1520 {
1521 // Pass down an appropriate z/Z packet...
1522 error.SetErrorString("watchpoints not supported");
1523 }
1524 // TODO: clear software watchpoints if we implement them
1525 }
1526 else
1527 {
1528 error.SetErrorString("Watchpoint location argument was NULL.");
1529 }
1530 if (error.Success())
1531 error.SetErrorToGenericError();
1532 return error;
1533}
1534
1535void
1536ProcessGDBRemote::Clear()
1537{
1538 m_flags = 0;
1539 m_thread_list.Clear();
1540 {
1541 Mutex::Locker locker(m_stdio_mutex);
1542 m_stdout_data.clear();
1543 }
1544 DestoryLibUnwindAddressSpace();
1545}
1546
1547Error
1548ProcessGDBRemote::DoSignal (int signo)
1549{
1550 Error error;
1551 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1552 if (log)
1553 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1554
1555 if (!m_gdb_comm.SendAsyncSignal (signo))
1556 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1557 return error;
1558}
1559
1560
1561Error
1562ProcessGDBRemote::DoDetach()
1563{
1564 Error error;
1565 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1566 if (log)
1567 log->Printf ("ProcessGDBRemote::DoDetach()");
1568
1569 // if (DoSIGSTOP (true))
1570 // {
1571 // CloseChildFileDescriptors ();
1572 //
1573 // // Scope for "locker" so we can reply to all of our exceptions (the SIGSTOP
1574 // // exception).
1575 // {
1576 // Mutex::Locker locker(m_exception_messages_mutex);
1577 // ReplyToAllExceptions();
1578 // }
1579 //
1580 // // Shut down the exception thread and cleanup our exception remappings
1581 // Task().ShutDownExceptionThread();
1582 //
1583 // pid_t pid = GetID();
1584 //
1585 // // Detach from our process while we are stopped.
1586 // errno = 0;
1587 //
1588 // // Detach from our process
1589 // ::ptrace (PT_DETACH, pid, (caddr_t)1, 0);
1590 //
1591 // error.SetErrorToErrno();
1592 //
1593 // if (log || error.Fail())
1594 // error.PutToLog(log, "::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid);
1595 //
1596 // // Resume our task
1597 // Task().Resume();
1598 //
1599 // // NULL our task out as we have already retored all exception ports
1600 // Task().Clear();
1601 //
1602 // // Clear out any notion of the process we once were
1603 // Clear();
1604 //
1605 // SetPrivateState (eStateDetached);
1606 // return true;
1607 // }
1608 return error;
1609}
1610
1611void
1612ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1613{
1614 ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1615 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1616}
1617
1618void
1619ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1620{
1621 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1622 Mutex::Locker locker(m_stdio_mutex);
1623 m_stdout_data.append(s, len);
1624
1625 // FIXME: Make a real data object for this and put it out.
1626 BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1627}
1628
1629
1630Error
1631ProcessGDBRemote::StartDebugserverProcess
1632(
1633 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1634 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1635 char const *inferior_envp[], // Environment to pass along to the inferior program
1636 char const *stdio_path,
1637 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID then attach to this attach_pid
1638 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1639 bool wait_for_launch, // Wait for the process named "attach_name" to launch
1640 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1641)
1642{
1643 Error error;
1644 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1645 {
1646 // If we locate debugserver, keep that located version around
1647 static FileSpec g_debugserver_file_spec;
1648
1649 FileSpec debugserver_file_spec;
1650 char debugserver_path[PATH_MAX];
1651
1652 // Always check to see if we have an environment override for the path
1653 // to the debugserver to use and use it if we do.
1654 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1655 if (env_debugserver_path)
1656 debugserver_file_spec.SetFile (env_debugserver_path);
1657 else
1658 debugserver_file_spec = g_debugserver_file_spec;
1659 bool debugserver_exists = debugserver_file_spec.Exists();
1660 if (!debugserver_exists)
1661 {
1662 // The debugserver binary is in the LLDB.framework/Resources
1663 // directory.
1664 FileSpec framework_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)lldb_private::Initialize));
1665 const char *framework_dir = framework_file_spec.GetDirectory().AsCString();
1666 const char *lldb_framework = ::strstr (framework_dir, "/LLDB.framework");
1667
1668 if (lldb_framework)
1669 {
1670 int len = lldb_framework - framework_dir + strlen ("/LLDB.framework");
1671 ::snprintf (debugserver_path,
1672 sizeof(debugserver_path),
1673 "%.*s/Resources/%s",
1674 len,
1675 framework_dir,
1676 DEBUGSERVER_BASENAME);
1677 debugserver_file_spec.SetFile (debugserver_path);
1678 debugserver_exists = debugserver_file_spec.Exists();
1679 }
1680
1681 if (debugserver_exists)
1682 {
1683 g_debugserver_file_spec = debugserver_file_spec;
1684 }
1685 else
1686 {
1687 g_debugserver_file_spec.Clear();
1688 debugserver_file_spec.Clear();
1689 }
1690 }
1691
1692 if (debugserver_exists)
1693 {
1694 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1695
1696 m_stdio_communication.Clear();
1697 posix_spawnattr_t attr;
1698
1699 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
1700
1701 Error local_err; // Errors that don't affect the spawning.
1702 if (log)
1703 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1704 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1705 if (error.Fail() || log)
1706 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
1707 if (error.Fail())
1708 return error;;
1709
1710#if !defined (__arm__)
1711
1712 // We don't need to do this for ARM, and we really shouldn't now that we
1713 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1714 // to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001715 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001716 {
Greg Claytoncf015052010-06-11 03:25:34 +00001717 cpu_type_t cpu = inferior_arch.GetCPUType();
1718 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1719 {
1720 size_t ocount = 0;
1721 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1722 if (error.Fail() || log)
1723 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount);
Chris Lattner24943d22010-06-08 16:52:24 +00001724
Greg Claytoncf015052010-06-11 03:25:34 +00001725 if (error.Fail() != 0 || ocount != 1)
1726 return error;
1727 }
Chris Lattner24943d22010-06-08 16:52:24 +00001728 }
1729
1730#endif
1731
1732 Args debugserver_args;
1733 char arg_cstr[PATH_MAX];
1734 bool launch_process = true;
1735
1736 if (inferior_argv == NULL && attach_pid != LLDB_INVALID_PROCESS_ID)
1737 launch_process = false;
1738 else if (attach_name)
1739 launch_process = false; // Wait for a process whose basename matches that in inferior_argv[0]
1740
1741 bool pass_stdio_path_to_debugserver = true;
1742 lldb_utility::PseudoTerminal pty;
1743 if (stdio_path == NULL)
1744 {
1745 pass_stdio_path_to_debugserver = false;
1746 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
1747 {
1748 struct termios stdin_termios;
1749 if (::tcgetattr (pty.GetMasterFileDescriptor(), &stdin_termios) == 0)
1750 {
1751 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing
1752 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time
1753 ::tcsetattr (pty.GetMasterFileDescriptor(), TCSANOW, &stdin_termios);
1754 }
1755 stdio_path = pty.GetSlaveName (NULL, 0);
1756 }
1757 }
1758
1759 // Start args with "debugserver /file/path -r --"
1760 debugserver_args.AppendArgument(debugserver_path);
1761 debugserver_args.AppendArgument(debugserver_url);
1762 debugserver_args.AppendArgument("--native-regs"); // use native registers, not the GDB registers
1763 debugserver_args.AppendArgument("--setsid"); // make debugserver run in its own session so
1764 // signals generated by special terminal key
1765 // sequences (^C) don't affect debugserver
1766
1767 // Only set the inferior
1768 if (launch_process)
1769 {
1770 if (stdio_path && pass_stdio_path_to_debugserver)
1771 {
1772 debugserver_args.AppendArgument("-s"); // short for --stdio-path
1773 StreamString strm;
1774 strm.Printf("'%s'", stdio_path);
1775 debugserver_args.AppendArgument(strm.GetData()); // path to file to have inferior open as it's STDIO
1776 }
1777 }
1778
1779 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1780 if (env_debugserver_log_file)
1781 {
1782 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1783 debugserver_args.AppendArgument(arg_cstr);
1784 }
1785
1786 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1787 if (env_debugserver_log_flags)
1788 {
1789 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1790 debugserver_args.AppendArgument(arg_cstr);
1791 }
1792// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1793// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1794
1795 // Now append the program arguments
1796 if (launch_process)
1797 {
1798 if (inferior_argv)
1799 {
1800 // Terminate the debugserver args so we can now append the inferior args
1801 debugserver_args.AppendArgument("--");
1802
1803 for (int i = 0; inferior_argv[i] != NULL; ++i)
1804 debugserver_args.AppendArgument (inferior_argv[i]);
1805 }
1806 else
1807 {
1808 // Will send environment entries with the 'QEnvironment:' packet
1809 // Will send arguments with the 'A' packet
1810 }
1811 }
1812 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1813 {
1814 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1815 debugserver_args.AppendArgument (arg_cstr);
1816 }
1817 else if (attach_name && attach_name[0])
1818 {
1819 if (wait_for_launch)
1820 debugserver_args.AppendArgument ("--waitfor");
1821 else
1822 debugserver_args.AppendArgument ("--attach");
1823 debugserver_args.AppendArgument (attach_name);
1824 }
1825
1826 Error file_actions_err;
1827 posix_spawn_file_actions_t file_actions;
1828#if DONT_CLOSE_DEBUGSERVER_STDIO
1829 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1830#else
1831 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1832 if (file_actions_err.Success())
1833 {
1834 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1835 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1836 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1837 }
1838#endif
1839
1840 if (log)
1841 {
1842 StreamString strm;
1843 debugserver_args.Dump (&strm);
1844 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1845 }
1846
1847 error.SetError(::posix_spawnp (&m_debugserver_pid,
1848 debugserver_path,
1849 file_actions_err.Success() ? &file_actions : NULL,
1850 &attr,
1851 debugserver_args.GetArgumentVector(),
1852 (char * const*)inferior_envp),
1853 eErrorTypePOSIX);
1854
Greg Claytone9d0df42010-07-02 01:29:13 +00001855
1856 ::posix_spawnattr_destroy (&attr);
1857
Chris Lattner24943d22010-06-08 16:52:24 +00001858 if (file_actions_err.Success())
1859 ::posix_spawn_file_actions_destroy (&file_actions);
1860
1861 // We have seen some cases where posix_spawnp was returning a valid
1862 // looking pid even when an error was returned, so clear it out
1863 if (error.Fail())
1864 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1865
1866 if (error.Fail() || log)
1867 error.PutToLog(log, "::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);
1868
1869// if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1870// {
1871// std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true));
1872// if (conn_ap.get())
1873// {
1874// m_stdio_communication.SetConnection(conn_ap.release());
1875// if (m_stdio_communication.IsConnected())
1876// {
1877// m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1878// m_stdio_communication.StartReadThread();
1879// }
1880// }
1881// }
1882 }
1883 else
1884 {
1885 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1886 }
1887
1888 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1889 StartAsyncThread ();
1890 }
1891 return error;
1892}
1893
1894bool
1895ProcessGDBRemote::MonitorDebugserverProcess
1896(
1897 void *callback_baton,
1898 lldb::pid_t debugserver_pid,
1899 int signo, // Zero for no signal
1900 int exit_status // Exit value of process if signal is zero
1901)
1902{
1903 // We pass in the ProcessGDBRemote inferior process it and name it
1904 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1905 // pointer value itself, thus we need the double cast...
1906
1907 // "debugserver_pid" argument passed in is the process ID for
1908 // debugserver that we are tracking...
1909
1910 lldb::pid_t gdb_remote_pid = (lldb::pid_t)(intptr_t)callback_baton;
Greg Clayton63094e02010-06-23 01:19:29 +00001911 TargetSP target_sp(Debugger::FindTargetWithProcessID (gdb_remote_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001912 if (target_sp)
1913 {
1914 ProcessSP process_sp (target_sp->GetProcessSP());
1915 if (process_sp)
1916 {
1917 // Sleep for a half a second to make sure our inferior process has
1918 // time to set its exit status before we set it incorrectly when
1919 // both the debugserver and the inferior process shut down.
1920 usleep (500000);
1921 // If our process hasn't yet exited, debugserver might have died.
1922 // If the process did exit, the we are reaping it.
1923 if (process_sp->GetState() != eStateExited)
1924 {
1925 char error_str[1024];
1926 if (signo)
1927 {
1928 const char *signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1929 if (signal_cstr)
1930 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
1931 else
1932 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
1933 }
1934 else
1935 {
1936 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
1937 }
1938
1939 process_sp->SetExitStatus (-1, error_str);
1940 }
1941 else
1942 {
1943 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)process_sp.get();
1944 // Debugserver has exited we need to let our ProcessGDBRemote
1945 // know that it no longer has a debugserver instance
1946 gdb_process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1947 // We are returning true to this function below, so we can
1948 // forget about the monitor handle.
1949 gdb_process->m_debugserver_monitor = 0;
1950 }
1951 }
1952 }
1953 return true;
1954}
1955
1956void
1957ProcessGDBRemote::KillDebugserverProcess ()
1958{
1959 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1960 {
1961 ::kill (m_debugserver_pid, SIGINT);
1962 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1963 }
1964}
1965
1966void
1967ProcessGDBRemote::Initialize()
1968{
1969 static bool g_initialized = false;
1970
1971 if (g_initialized == false)
1972 {
1973 g_initialized = true;
1974 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1975 GetPluginDescriptionStatic(),
1976 CreateInstance);
1977
1978 Log::Callbacks log_callbacks = {
1979 ProcessGDBRemoteLog::DisableLog,
1980 ProcessGDBRemoteLog::EnableLog,
1981 ProcessGDBRemoteLog::ListLogCategories
1982 };
1983
1984 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1985 }
1986}
1987
1988bool
1989ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1990{
1991 if (m_curr_tid == tid)
1992 return true;
1993
1994 char packet[32];
1995 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1996 assert (packet_len + 1 < sizeof(packet));
1997 StringExtractorGDBRemote response;
1998 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1999 {
2000 if (response.IsOKPacket())
2001 {
2002 m_curr_tid = tid;
2003 return true;
2004 }
2005 }
2006 return false;
2007}
2008
2009bool
2010ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2011{
2012 if (m_curr_tid_run == tid)
2013 return true;
2014
2015 char packet[32];
2016 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2017 assert (packet_len + 1 < sizeof(packet));
2018 StringExtractorGDBRemote response;
2019 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2020 {
2021 if (response.IsOKPacket())
2022 {
2023 m_curr_tid_run = tid;
2024 return true;
2025 }
2026 }
2027 return false;
2028}
2029
2030void
2031ProcessGDBRemote::ResetGDBRemoteState ()
2032{
2033 // Reset and GDB remote state
2034 m_curr_tid = LLDB_INVALID_THREAD_ID;
2035 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2036 m_z0_supported = 1;
2037}
2038
2039
2040bool
2041ProcessGDBRemote::StartAsyncThread ()
2042{
2043 ResetGDBRemoteState ();
2044
2045 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2046
2047 if (log)
2048 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2049
2050 // Create a thread that watches our internal state and controls which
2051 // events make it to clients (into the DCProcess event queue).
2052 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2053 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2054}
2055
2056void
2057ProcessGDBRemote::StopAsyncThread ()
2058{
2059 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2060
2061 if (log)
2062 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2063
2064 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2065
2066 // Stop the stdio thread
2067 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2068 {
2069 Host::ThreadJoin (m_async_thread, NULL, NULL);
2070 }
2071}
2072
2073
2074void *
2075ProcessGDBRemote::AsyncThread (void *arg)
2076{
2077 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2078
2079 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
2080 if (log)
2081 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2082
2083 Listener listener ("ProcessGDBRemote::AsyncThread");
2084 EventSP event_sp;
2085 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2086 eBroadcastBitAsyncThreadShouldExit;
2087
2088 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2089 {
2090 bool done = false;
2091 while (!done)
2092 {
2093 if (log)
2094 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2095 if (listener.WaitForEvent (NULL, event_sp))
2096 {
2097 const uint32_t event_type = event_sp->GetType();
2098 switch (event_type)
2099 {
2100 case eBroadcastBitAsyncContinue:
2101 {
2102 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2103
2104 if (continue_packet)
2105 {
2106 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2107 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2108 if (log)
2109 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2110
2111 process->SetPrivateState(eStateRunning);
2112 StringExtractorGDBRemote response;
2113 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2114
2115 switch (stop_state)
2116 {
2117 case eStateStopped:
2118 case eStateCrashed:
2119 case eStateSuspended:
2120 process->m_last_stop_packet = response;
2121 process->m_last_stop_packet.SetFilePos (0);
2122 process->SetPrivateState (stop_state);
2123 break;
2124
2125 case eStateExited:
2126 process->m_last_stop_packet = response;
2127 process->m_last_stop_packet.SetFilePos (0);
2128 response.SetFilePos(1);
2129 process->SetExitStatus(response.GetHexU8(), NULL);
2130 done = true;
2131 break;
2132
2133 case eStateInvalid:
2134 break;
2135
2136 default:
2137 process->SetPrivateState (stop_state);
2138 break;
2139 }
2140 }
2141 }
2142 break;
2143
2144 case eBroadcastBitAsyncThreadShouldExit:
2145 if (log)
2146 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2147 done = true;
2148 break;
2149
2150 default:
2151 if (log)
2152 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2153 done = true;
2154 break;
2155 }
2156 }
2157 else
2158 {
2159 if (log)
2160 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2161 done = true;
2162 }
2163 }
2164 }
2165
2166 if (log)
2167 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2168
2169 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2170 return NULL;
2171}
2172
2173lldb_private::unw_addr_space_t
2174ProcessGDBRemote::GetLibUnwindAddressSpace ()
2175{
2176 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002177
2178 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2179 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002180 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002181 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002182 target_type = UNW_TARGET_X86_64;
2183
2184 if (m_libunwind_addr_space)
2185 {
2186 if (m_libunwind_target_type != target_type)
2187 DestoryLibUnwindAddressSpace();
2188 else
2189 return m_libunwind_addr_space;
2190 }
2191 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2192 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2193 if (m_libunwind_addr_space)
2194 m_libunwind_target_type = target_type;
2195 else
2196 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2197 return m_libunwind_addr_space;
2198}
2199
2200void
2201ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2202{
2203 if (m_libunwind_addr_space)
2204 {
2205 unw_destroy_addr_space (m_libunwind_addr_space);
2206 m_libunwind_addr_space = NULL;
2207 }
2208 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2209}
2210
2211
2212const char *
2213ProcessGDBRemote::GetDispatchQueueNameForThread
2214(
2215 addr_t thread_dispatch_qaddr,
2216 std::string &dispatch_queue_name
2217)
2218{
2219 dispatch_queue_name.clear();
2220 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2221 {
2222 // Cache the dispatch_queue_offsets_addr value so we don't always have
2223 // to look it up
2224 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2225 {
2226 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib")));
2227 if (module_sp.get() == NULL)
2228 return NULL;
2229
2230 const Symbol *dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (ConstString("dispatch_queue_offsets"), eSymbolTypeData);
2231 if (dispatch_queue_offsets_symbol)
2232 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(this);
2233
2234 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2235 return NULL;
2236 }
2237
2238 uint8_t memory_buffer[8];
2239 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2240
2241 // Excerpt from src/queue_private.h
2242 struct dispatch_queue_offsets_s
2243 {
2244 uint16_t dqo_version;
2245 uint16_t dqo_label;
2246 uint16_t dqo_label_size;
2247 } dispatch_queue_offsets;
2248
2249
2250 Error error;
2251 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2252 {
2253 uint32_t data_offset = 0;
2254 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2255 {
2256 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2257 {
2258 data_offset = 0;
2259 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2260 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2261 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2262 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2263 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2264 dispatch_queue_name.erase (bytes_read);
2265 }
2266 }
2267 }
2268 }
2269 if (dispatch_queue_name.empty())
2270 return NULL;
2271 return dispatch_queue_name.c_str();
2272}
2273
Jim Ingham7508e732010-08-09 23:31:02 +00002274uint32_t
2275ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2276{
2277 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2278 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2279 if (m_local_debugserver)
2280 {
2281 return Host::ListProcessesMatchingName (name, matches, pids);
2282 }
2283 else
2284 {
2285 // FIXME: Implement talking to the remote debugserver.
2286 return 0;
2287 }
2288
2289}