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