blob: 8d3675d0b7d02ec5488c2fb91d832f9811f5856e [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
Chris Lattner24943d22010-06-08 16:52:24 +0000217 {
218 LLDB_INVALID_REGNUM, // GCC reg num
219 LLDB_INVALID_REGNUM, // DWARF reg num
220 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000221 reg_num, // GDB reg num
222 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000223 }
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[],
Greg Clayton452bf612010-08-31 18:35:14 +0000378 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000379 const char *stdin_path,
380 const char *stdout_path,
381 const char *stderr_path
382)
383{
Greg Clayton4b407112010-09-30 21:49:03 +0000384 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000385 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
386 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
387 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000388
389 ObjectFile * object_file = module->GetObjectFile();
390 if (object_file)
391 {
392 ArchSpec inferior_arch(module->GetArchitecture());
393 char host_port[128];
394 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
395
396 bool start_debugserver_with_inferior_args = false;
397 if (start_debugserver_with_inferior_args)
398 {
399 // We want to launch debugserver with the inferior program and its
400 // arguments on the command line. We should only do this if we
401 // the GDB server we are talking to doesn't support the 'A' packet.
402 error = StartDebugserverProcess (host_port,
403 argv,
404 envp,
405 NULL, //stdin_path,
406 LLDB_INVALID_PROCESS_ID,
407 NULL, false,
Benjamin Kramer2653be92010-09-03 18:20:07 +0000408 (launch_flags & eLaunchFlagDisableASLR) != 0,
Chris Lattner24943d22010-06-08 16:52:24 +0000409 inferior_arch);
410 if (error.Fail())
411 return error;
412
413 error = ConnectToDebugserver (host_port);
414 if (error.Success())
415 {
416 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
417 }
418 }
419 else
420 {
421 error = StartDebugserverProcess (host_port,
422 NULL,
423 NULL,
424 NULL, //stdin_path,
425 LLDB_INVALID_PROCESS_ID,
426 NULL, false,
Benjamin Kramer2653be92010-09-03 18:20:07 +0000427 (launch_flags & eLaunchFlagDisableASLR) != 0,
Chris Lattner24943d22010-06-08 16:52:24 +0000428 inferior_arch);
429 if (error.Fail())
430 return error;
431
432 error = ConnectToDebugserver (host_port);
433 if (error.Success())
434 {
435 // Send the environment and the program + arguments after we connect
436 if (envp)
437 {
438 const char *env_entry;
439 for (int i=0; (env_entry = envp[i]); ++i)
440 {
441 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
442 break;
443 }
444 }
445
Greg Clayton960d6a42010-08-03 00:35:52 +0000446 // FIXME: convert this to use the new set/show variables when they are available
447#if 0
448 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
449 {
450 const uint32_t attach_debugserver_secs = 10;
451 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
452 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
453 {
454 printf ("%i\n", attach_debugserver_secs - i);
455 sleep (1);
456 }
457 }
458#endif
459
Chris Lattner24943d22010-06-08 16:52:24 +0000460 const uint32_t arg_timeout_seconds = 10;
461 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
462 if (arg_packet_err == 0)
463 {
464 std::string error_str;
465 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
466 {
467 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
468 }
469 else
470 {
471 error.SetErrorString (error_str.c_str());
472 }
473 }
474 else
475 {
476 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
477 }
478
479 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
480 }
481 }
482
483 if (GetID() == LLDB_INVALID_PROCESS_ID)
484 {
485 KillDebugserverProcess ();
486 return error;
487 }
488
489 StringExtractorGDBRemote response;
490 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
491 SetPrivateState (SetThreadStopInfo (response));
492
493 }
494 else
495 {
496 // Set our user ID to an invalid process ID.
497 SetID(LLDB_INVALID_PROCESS_ID);
498 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
499 }
Chris Lattner24943d22010-06-08 16:52:24 +0000500 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000501
Chris Lattner24943d22010-06-08 16:52:24 +0000502}
503
504
505Error
506ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
507{
508 Error error;
509 // Sleep and wait a bit for debugserver to start to listen...
510 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
511 if (conn_ap.get())
512 {
513 std::string connect_url("connect://");
514 connect_url.append (host_port);
515 const uint32_t max_retry_count = 50;
516 uint32_t retry_count = 0;
517 while (!m_gdb_comm.IsConnected())
518 {
519 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
520 {
521 m_gdb_comm.SetConnection (conn_ap.release());
522 break;
523 }
524 retry_count++;
525
526 if (retry_count >= max_retry_count)
527 break;
528
529 usleep (100000);
530 }
531 }
532
533 if (!m_gdb_comm.IsConnected())
534 {
535 if (error.Success())
536 error.SetErrorString("not connected to remote gdb server");
537 return error;
538 }
539
540 m_gdb_comm.SetAckMode (true);
541 if (m_gdb_comm.StartReadThread(&error))
542 {
543 // Send an initial ack
544 m_gdb_comm.SendAck('+');
545
546 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000547 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
548 this,
549 m_debugserver_pid,
550 false);
551
Chris Lattner24943d22010-06-08 16:52:24 +0000552 StringExtractorGDBRemote response;
553 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
554 {
555 if (response.IsOKPacket())
556 m_gdb_comm.SetAckMode (false);
557 }
558
559 BuildDynamicRegisterInfo ();
560 }
561 return error;
562}
563
564void
565ProcessGDBRemote::DidLaunchOrAttach ()
566{
567 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
568 if (GetID() == LLDB_INVALID_PROCESS_ID)
569 {
570 m_dynamic_loader_ap.reset();
571 }
572 else
573 {
574 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
575
Jim Ingham7508e732010-08-09 23:31:02 +0000576 Module * exe_module = GetTarget().GetExecutableModule ().get();
Chris Lattner24943d22010-06-08 16:52:24 +0000577 assert(exe_module);
578
Chris Lattner24943d22010-06-08 16:52:24 +0000579 ObjectFile *exe_objfile = exe_module->GetObjectFile();
580 assert(exe_objfile);
581
582 m_byte_order = exe_objfile->GetByteOrder();
583 assert (m_byte_order != eByteOrderInvalid);
584
585 StreamString strm;
586
587 ArchSpec inferior_arch;
588 // See if the GDB server supports the qHostInfo information
589 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
590 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Jim Ingham7508e732010-08-09 23:31:02 +0000591 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000592
Jim Ingham7508e732010-08-09 23:31:02 +0000593 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000594 {
595 // For ARM we can't trust the arch of the process as it could
596 // have an armv6 object file, but be running on armv7 kernel.
597 inferior_arch = m_gdb_comm.GetHostArchitecture();
598 }
599
600 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000601 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000602
603 if (vendor == NULL)
604 vendor = Host::GetVendorString().AsCString("apple");
605
606 if (os_type == NULL)
607 os_type = Host::GetOSString().AsCString("darwin");
608
609 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
610
611 std::transform (strm.GetString().begin(),
612 strm.GetString().end(),
613 strm.GetString().begin(),
614 ::tolower);
615
616 m_target_triple.SetCString(strm.GetString().c_str());
617 }
618}
619
620void
621ProcessGDBRemote::DidLaunch ()
622{
623 DidLaunchOrAttach ();
624 if (m_dynamic_loader_ap.get())
625 m_dynamic_loader_ap->DidLaunch();
626}
627
628Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000629ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000630{
631 Error error;
632 // Clear out and clean up from any current state
633 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000634 ArchSpec arch_spec = GetTarget().GetArchitecture();
635
Chris Lattner24943d22010-06-08 16:52:24 +0000636 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Jim Ingham7508e732010-08-09 23:31:02 +0000637
638
Chris Lattner24943d22010-06-08 16:52:24 +0000639 if (attach_pid != LLDB_INVALID_PROCESS_ID)
640 {
Chris Lattner24943d22010-06-08 16:52:24 +0000641 char host_port[128];
642 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000643 error = StartDebugserverProcess (host_port, // debugserver_url
644 NULL, // inferior_argv
645 NULL, // inferior_envp
646 NULL, // stdin_path
647 LLDB_INVALID_PROCESS_ID, // attach_pid
648 NULL, // attach_pid_name
649 false, // wait_for_launch
650 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000651 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000652
653 if (error.Fail())
654 {
655 const char *error_string = error.AsCString();
656 if (error_string == NULL)
657 error_string = "unable to launch " DEBUGSERVER_BASENAME;
658
659 SetExitStatus (-1, error_string);
660 }
661 else
662 {
663 error = ConnectToDebugserver (host_port);
664 if (error.Success())
665 {
666 char packet[64];
667 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
668 StringExtractorGDBRemote response;
669 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
670 packet,
671 packet_len,
672 response);
673 switch (stop_state)
674 {
675 case eStateStopped:
676 case eStateCrashed:
677 case eStateSuspended:
678 SetID (attach_pid);
679 m_last_stop_packet = response;
680 m_last_stop_packet.SetFilePos (0);
681 SetPrivateState (stop_state);
682 break;
683
684 case eStateExited:
685 m_last_stop_packet = response;
686 m_last_stop_packet.SetFilePos (0);
687 response.SetFilePos(1);
688 SetExitStatus(response.GetHexU8(), NULL);
689 break;
690
691 default:
692 SetExitStatus(-1, "unable to attach to process");
693 break;
694 }
695
696 }
697 }
698 }
699
700 lldb::pid_t pid = GetID();
701 if (pid == LLDB_INVALID_PROCESS_ID)
702 {
703 KillDebugserverProcess();
704 }
705 return error;
706}
707
708size_t
709ProcessGDBRemote::AttachInputReaderCallback
710(
711 void *baton,
712 InputReader *reader,
713 lldb::InputReaderAction notification,
714 const char *bytes,
715 size_t bytes_len
716)
717{
718 if (notification == eInputReaderGotToken)
719 {
720 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
721 if (gdb_process->m_waiting_for_attach)
722 gdb_process->m_waiting_for_attach = false;
723 reader->SetIsDone(true);
724 return 1;
725 }
726 return 0;
727}
728
729Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000730ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000731{
732 Error error;
733 // Clear out and clean up from any current state
734 Clear();
735 // HACK: require arch be set correctly at the target level until we can
736 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000737
738 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
739 if (process_name && process_name[0])
740 {
Chris Lattner24943d22010-06-08 16:52:24 +0000741 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000742 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000743 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000744 error = StartDebugserverProcess (host_port, // debugserver_url
745 NULL, // inferior_argv
746 NULL, // inferior_envp
747 NULL, // stdin_path
748 LLDB_INVALID_PROCESS_ID, // attach_pid
749 NULL, // attach_pid_name
750 false, // wait_for_launch
751 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000752 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000753 if (error.Fail())
754 {
755 const char *error_string = error.AsCString();
756 if (error_string == NULL)
757 error_string = "unable to launch " DEBUGSERVER_BASENAME;
758
759 SetExitStatus (-1, error_string);
760 }
761 else
762 {
763 error = ConnectToDebugserver (host_port);
764 if (error.Success())
765 {
766 StreamString packet;
767
Chris Lattner24943d22010-06-08 16:52:24 +0000768 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000769 packet.PutCString("vAttachWait");
770 else
771 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000772 packet.PutChar(';');
773 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
774 StringExtractorGDBRemote response;
775 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
776 packet.GetData(),
777 packet.GetSize(),
778 response);
779 switch (stop_state)
780 {
781 case eStateStopped:
782 case eStateCrashed:
783 case eStateSuspended:
784 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
785 m_last_stop_packet = response;
786 m_last_stop_packet.SetFilePos (0);
787 SetPrivateState (stop_state);
788 break;
789
790 case eStateExited:
791 m_last_stop_packet = response;
792 m_last_stop_packet.SetFilePos (0);
793 response.SetFilePos(1);
794 SetExitStatus(response.GetHexU8(), NULL);
795 break;
796
797 default:
798 SetExitStatus(-1, "unable to attach to process");
799 break;
800 }
801 }
802 }
803 }
804
805 lldb::pid_t pid = GetID();
806 if (pid == LLDB_INVALID_PROCESS_ID)
807 {
808 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000809
810 if (error.Success())
811 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000812 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000813
Chris Lattner24943d22010-06-08 16:52:24 +0000814 return error;
815}
816
817//
818// if (wait_for_launch)
819// {
820// InputReaderSP reader_sp (new InputReader());
821// StreamString instructions;
822// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
823// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
824// this, // baton
825// eInputReaderGranularityByte,
826// NULL, // End token
827// false);
828//
829// StringExtractorGDBRemote response;
830// m_waiting_for_attach = true;
831// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
832// while (m_waiting_for_attach)
833// {
834// // Wait for one second for the stop reply packet
835// if (m_gdb_comm.WaitForPacket(response, 1))
836// {
837// // Got some sort of packet, see if it is the stop reply packet?
838// char ch = response.GetChar(0);
839// if (ch == 'T')
840// {
841// m_waiting_for_attach = false;
842// }
843// }
844// else
845// {
846// // Put a period character every second
847// fputc('.', reader_out_fh);
848// }
849// }
850// }
851// }
852// return GetID();
853//}
854
855void
856ProcessGDBRemote::DidAttach ()
857{
Jim Ingham7508e732010-08-09 23:31:02 +0000858 // If we haven't got an executable module yet, then we should make a dynamic loader, and
859 // see if it can find the executable module for us. If we do have an executable module,
860 // make sure it matches the process we've just attached to.
861
862 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
863 if (!m_dynamic_loader_ap.get())
864 {
865 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
866 }
867
Chris Lattner24943d22010-06-08 16:52:24 +0000868 if (m_dynamic_loader_ap.get())
869 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000870
871 Module * new_exe_module = GetTarget().GetExecutableModule().get();
872 if (new_exe_module == NULL)
873 {
874
875 }
876
877 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000878}
879
880Error
881ProcessGDBRemote::WillResume ()
882{
883 m_continue_packet.Clear();
884 // Start the continue packet we will use to run the target. Each thread
885 // will append what it is supposed to be doing to this packet when the
886 // ThreadList::WillResume() is called. If a thread it supposed
887 // to stay stopped, then don't append anything to this string.
888 m_continue_packet.Printf("vCont");
889 return Error();
890}
891
892Error
893ProcessGDBRemote::DoResume ()
894{
895 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
896 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
897 return Error();
898}
899
900size_t
901ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
902{
903 const uint8_t *trap_opcode = NULL;
904 uint32_t trap_opcode_size = 0;
905
906 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
907 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
908 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
909 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
910
Jim Ingham7508e732010-08-09 23:31:02 +0000911 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000912 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000913 {
Greg Claytoncf015052010-06-11 03:25:34 +0000914 case ArchSpec::eCPU_i386:
915 case ArchSpec::eCPU_x86_64:
916 trap_opcode = g_i386_breakpoint_opcode;
917 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
918 break;
919
920 case ArchSpec::eCPU_arm:
921 // TODO: fill this in for ARM. We need to dig up the symbol for
922 // the address in the breakpoint locaiton and figure out if it is
923 // an ARM or Thumb breakpoint.
924 trap_opcode = g_arm_breakpoint_opcode;
925 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
926 break;
927
928 case ArchSpec::eCPU_ppc:
929 case ArchSpec::eCPU_ppc64:
930 trap_opcode = g_ppc_breakpoint_opcode;
931 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
932 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000933
Greg Claytoncf015052010-06-11 03:25:34 +0000934 default:
935 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
936 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000937 }
938
939 if (trap_opcode && trap_opcode_size)
940 {
941 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
942 return trap_opcode_size;
943 }
944 return 0;
945}
946
947uint32_t
948ProcessGDBRemote::UpdateThreadListIfNeeded ()
949{
950 // locker will keep a mutex locked until it goes out of scope
951 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD);
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000952 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000953 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
954
Greg Clayton5205f0b2010-09-03 17:10:42 +0000955 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000956 const uint32_t stop_id = GetStopID();
957 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
958 {
959 // Update the thread list's stop id immediately so we don't recurse into this function.
960 ThreadList curr_thread_list (this);
961 curr_thread_list.SetStopID(stop_id);
962
963 Error err;
964 StringExtractorGDBRemote response;
965 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
966 response.IsNormalPacket();
967 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
968 {
969 char ch = response.GetChar();
970 if (ch == 'l')
971 break;
972 if (ch == 'm')
973 {
974 do
975 {
976 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
977
978 if (tid != LLDB_INVALID_THREAD_ID)
979 {
980 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
981 if (thread_sp)
982 thread_sp->GetRegisterContext()->Invalidate();
983 else
984 thread_sp.reset (new ThreadGDBRemote (*this, tid));
985 curr_thread_list.AddThread(thread_sp);
986 }
987
988 ch = response.GetChar();
989 } while (ch == ',');
990 }
991 }
992
993 m_thread_list = curr_thread_list;
994
995 SetThreadStopInfo (m_last_stop_packet);
996 }
997 return GetThreadList().GetSize(false);
998}
999
1000
1001StateType
1002ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1003{
1004 const char stop_type = stop_packet.GetChar();
1005 switch (stop_type)
1006 {
1007 case 'T':
1008 case 'S':
1009 {
1010 // Stop with signal and thread info
1011 const uint8_t signo = stop_packet.GetHexU8();
1012 std::string name;
1013 std::string value;
1014 std::string thread_name;
1015 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001016 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001017 uint32_t tid = LLDB_INVALID_THREAD_ID;
1018 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1019 uint32_t exc_data_count = 0;
1020 while (stop_packet.GetNameColonValue(name, value))
1021 {
1022 if (name.compare("metype") == 0)
1023 {
1024 // exception type in big endian hex
1025 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1026 }
1027 else if (name.compare("mecount") == 0)
1028 {
1029 // exception count in big endian hex
1030 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1031 }
1032 else if (name.compare("medata") == 0)
1033 {
1034 // exception data in big endian hex
1035 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1036 }
1037 else if (name.compare("thread") == 0)
1038 {
1039 // thread in big endian hex
1040 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1041 }
1042 else if (name.compare("name") == 0)
1043 {
1044 thread_name.swap (value);
1045 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001046 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001047 {
1048 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1049 }
1050 }
1051 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1052
1053 if (thread_sp)
1054 {
1055 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1056
1057 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1058 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001059 if (exc_type != 0)
1060 {
Greg Clayton643ee732010-08-04 01:40:35 +00001061 const size_t exc_data_count = exc_data.size();
1062
1063 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1064 exc_type,
1065 exc_data_count,
1066 exc_data_count >= 1 ? exc_data[0] : 0,
1067 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001068 }
1069 else if (signo)
1070 {
Greg Clayton643ee732010-08-04 01:40:35 +00001071 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001072 }
1073 else
1074 {
Greg Clayton643ee732010-08-04 01:40:35 +00001075 StopInfoSP invalid_stop_info_sp;
1076 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001077 }
1078 }
1079 return eStateStopped;
1080 }
1081 break;
1082
1083 case 'W':
1084 // process exited
1085 return eStateExited;
1086
1087 default:
1088 break;
1089 }
1090 return eStateInvalid;
1091}
1092
1093void
1094ProcessGDBRemote::RefreshStateAfterStop ()
1095{
Jim Ingham7508e732010-08-09 23:31:02 +00001096 // FIXME - add a variable to tell that we're in the middle of attaching if we
1097 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001098 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001099// if (!GetTarget().GetArchitecture().IsValid())
1100// {
1101// Module *exe_module = GetTarget().GetExecutableModule().get();
1102// if (exe_module)
1103// m_arch_spec = exe_module->GetArchitecture();
1104// }
1105
Chris Lattner24943d22010-06-08 16:52:24 +00001106 // Let all threads recover from stopping and do any clean up based
1107 // on the previous thread state (if any).
1108 m_thread_list.RefreshStateAfterStop();
1109
1110 // Discover new threads:
1111 UpdateThreadListIfNeeded ();
1112}
1113
1114Error
1115ProcessGDBRemote::DoHalt ()
1116{
1117 Error error;
1118 if (m_gdb_comm.IsRunning())
1119 {
1120 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001121 Mutex::Locker locker;
1122 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001123 {
1124 if (timed_out)
1125 error.SetErrorString("timed out sending interrupt packet");
1126 else
1127 error.SetErrorString("unknown error sending interrupt packet");
1128 }
1129 }
1130 return error;
1131}
1132
1133Error
1134ProcessGDBRemote::WillDetach ()
1135{
1136 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001137
Greg Clayton4fb400f2010-09-27 21:07:38 +00001138 if (m_gdb_comm.IsRunning())
1139 {
1140 bool timed_out = false;
1141 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001142 PausePrivateStateThread();
1143 m_thread_list.DiscardThreadPlans();
1144 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001145 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1146 {
1147 if (timed_out)
1148 error.SetErrorString("timed out sending interrupt packet");
1149 else
1150 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001151 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001152 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001153 TimeValue timeout_time;
1154 timeout_time = TimeValue::Now();
1155 timeout_time.OffsetWithSeconds(2);
1156
1157 EventSP event_sp;
1158 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1159 if (state != eStateStopped)
1160 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001161 }
Chris Lattner24943d22010-06-08 16:52:24 +00001162 return error;
1163}
1164
Greg Clayton4fb400f2010-09-27 21:07:38 +00001165Error
1166ProcessGDBRemote::DoDetach()
1167{
1168 Error error;
1169 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1170 if (log)
1171 log->Printf ("ProcessGDBRemote::DoDetach()");
1172
1173 DisableAllBreakpointSites ();
1174
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001175 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001176
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001177 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1178 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001179 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001180 if (response_size)
1181 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1182 else
1183 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001184 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001185 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001186 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001187
Greg Clayton4fb400f2010-09-27 21:07:38 +00001188 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001189 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001190
1191 SetPrivateState (eStateDetached);
1192 ResumePrivateStateThread();
1193
1194 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001195 return error;
1196}
Chris Lattner24943d22010-06-08 16:52:24 +00001197
1198Error
1199ProcessGDBRemote::DoDestroy ()
1200{
1201 Error error;
1202 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1203 if (log)
1204 log->Printf ("ProcessGDBRemote::DoDestroy()");
1205
1206 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001207 Mutex::Locker locker;
1208 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001209 DisableAllBreakpointSites ();
1210 SetExitStatus(-1, "process killed");
1211
1212 StringExtractorGDBRemote response;
1213 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1214 {
Caroline Tice926060e2010-10-29 21:48:37 +00001215 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001216 if (log)
1217 {
1218 if (response.IsOKPacket())
1219 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1220 else
1221 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1222 }
1223 }
1224
1225 StopAsyncThread ();
1226 m_gdb_comm.StopReadThread();
1227 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001228 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001229 return error;
1230}
1231
1232ByteOrder
1233ProcessGDBRemote::GetByteOrder () const
1234{
1235 return m_byte_order;
1236}
1237
1238//------------------------------------------------------------------
1239// Process Queries
1240//------------------------------------------------------------------
1241
1242bool
1243ProcessGDBRemote::IsAlive ()
1244{
1245 return m_gdb_comm.IsConnected();
1246}
1247
1248addr_t
1249ProcessGDBRemote::GetImageInfoAddress()
1250{
1251 if (!m_gdb_comm.IsRunning())
1252 {
1253 StringExtractorGDBRemote response;
1254 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1255 {
1256 if (response.IsNormalPacket())
1257 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1258 }
1259 }
1260 return LLDB_INVALID_ADDRESS;
1261}
1262
1263DynamicLoader *
1264ProcessGDBRemote::GetDynamicLoader()
1265{
1266 return m_dynamic_loader_ap.get();
1267}
1268
1269//------------------------------------------------------------------
1270// Process Memory
1271//------------------------------------------------------------------
1272size_t
1273ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1274{
1275 if (size > m_max_memory_size)
1276 {
1277 // Keep memory read sizes down to a sane limit. This function will be
1278 // called multiple times in order to complete the task by
1279 // lldb_private::Process so it is ok to do this.
1280 size = m_max_memory_size;
1281 }
1282
1283 char packet[64];
1284 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1285 assert (packet_len + 1 < sizeof(packet));
1286 StringExtractorGDBRemote response;
1287 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1288 {
1289 if (response.IsNormalPacket())
1290 {
1291 error.Clear();
1292 return response.GetHexBytes(buf, size, '\xdd');
1293 }
1294 else if (response.IsErrorPacket())
1295 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1296 else if (response.IsUnsupportedPacket())
1297 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1298 else
1299 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1300 }
1301 else
1302 {
1303 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1304 }
1305 return 0;
1306}
1307
1308size_t
1309ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1310{
1311 StreamString packet;
1312 packet.Printf("M%llx,%zx:", addr, size);
1313 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1314 StringExtractorGDBRemote response;
1315 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1316 {
1317 if (response.IsOKPacket())
1318 {
1319 error.Clear();
1320 return size;
1321 }
1322 else if (response.IsErrorPacket())
1323 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1324 else if (response.IsUnsupportedPacket())
1325 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1326 else
1327 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1328 }
1329 else
1330 {
1331 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1332 }
1333 return 0;
1334}
1335
1336lldb::addr_t
1337ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1338{
1339 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1340 if (allocated_addr == LLDB_INVALID_ADDRESS)
1341 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1342 else
1343 error.Clear();
1344 return allocated_addr;
1345}
1346
1347Error
1348ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1349{
1350 Error error;
1351 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1352 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1353 return error;
1354}
1355
1356
1357//------------------------------------------------------------------
1358// Process STDIO
1359//------------------------------------------------------------------
1360
1361size_t
1362ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1363{
1364 Mutex::Locker locker(m_stdio_mutex);
1365 size_t bytes_available = m_stdout_data.size();
1366 if (bytes_available > 0)
1367 {
1368 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1369 if (bytes_available > buf_size)
1370 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001371 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001372 m_stdout_data.erase(0, buf_size);
1373 bytes_available = buf_size;
1374 }
1375 else
1376 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001377 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001378 m_stdout_data.clear();
1379
1380 //ResetEventBits(eBroadcastBitSTDOUT);
1381 }
1382 }
1383 return bytes_available;
1384}
1385
1386size_t
1387ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1388{
1389 // Can we get STDERR through the remote protocol?
1390 return 0;
1391}
1392
1393size_t
1394ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1395{
1396 if (m_stdio_communication.IsConnected())
1397 {
1398 ConnectionStatus status;
1399 m_stdio_communication.Write(src, src_len, status, NULL);
1400 }
1401 return 0;
1402}
1403
1404Error
1405ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1406{
1407 Error error;
1408 assert (bp_site != NULL);
1409
1410 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1411 user_id_t site_id = bp_site->GetID();
1412 const addr_t addr = bp_site->GetLoadAddress();
1413 if (log)
1414 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1415
1416 if (bp_site->IsEnabled())
1417 {
1418 if (log)
1419 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1420 return error;
1421 }
1422 else
1423 {
1424 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1425
1426 if (bp_site->HardwarePreferred())
1427 {
1428 // Try and set hardware breakpoint, and if that fails, fall through
1429 // and set a software breakpoint?
1430 }
1431
1432 if (m_z0_supported)
1433 {
1434 char packet[64];
1435 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1436 assert (packet_len + 1 < sizeof(packet));
1437 StringExtractorGDBRemote response;
1438 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1439 {
1440 if (response.IsUnsupportedPacket())
1441 {
1442 // Disable z packet support and try again
1443 m_z0_supported = 0;
1444 return EnableBreakpoint (bp_site);
1445 }
1446 else if (response.IsOKPacket())
1447 {
1448 bp_site->SetEnabled(true);
1449 bp_site->SetType (BreakpointSite::eExternal);
1450 return error;
1451 }
1452 else
1453 {
1454 uint8_t error_byte = response.GetError();
1455 if (error_byte)
1456 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1457 }
1458 }
1459 }
1460 else
1461 {
1462 return EnableSoftwareBreakpoint (bp_site);
1463 }
1464 }
1465
1466 if (log)
1467 {
1468 const char *err_string = error.AsCString();
1469 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1470 bp_site->GetLoadAddress(),
1471 err_string ? err_string : "NULL");
1472 }
1473 // We shouldn't reach here on a successful breakpoint enable...
1474 if (error.Success())
1475 error.SetErrorToGenericError();
1476 return error;
1477}
1478
1479Error
1480ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1481{
1482 Error error;
1483 assert (bp_site != NULL);
1484 addr_t addr = bp_site->GetLoadAddress();
1485 user_id_t site_id = bp_site->GetID();
1486 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1487 if (log)
1488 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1489
1490 if (bp_site->IsEnabled())
1491 {
1492 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1493
1494 if (bp_site->IsHardware())
1495 {
1496 // TODO: disable hardware breakpoint...
1497 }
1498 else
1499 {
1500 if (m_z0_supported)
1501 {
1502 char packet[64];
1503 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1504 assert (packet_len + 1 < sizeof(packet));
1505 StringExtractorGDBRemote response;
1506 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1507 {
1508 if (response.IsUnsupportedPacket())
1509 {
1510 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1511 }
1512 else if (response.IsOKPacket())
1513 {
1514 if (log)
1515 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1516 bp_site->SetEnabled(false);
1517 return error;
1518 }
1519 else
1520 {
1521 uint8_t error_byte = response.GetError();
1522 if (error_byte)
1523 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1524 }
1525 }
1526 }
1527 else
1528 {
1529 return DisableSoftwareBreakpoint (bp_site);
1530 }
1531 }
1532 }
1533 else
1534 {
1535 if (log)
1536 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1537 return error;
1538 }
1539
1540 if (error.Success())
1541 error.SetErrorToGenericError();
1542 return error;
1543}
1544
1545Error
1546ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1547{
1548 Error error;
1549 if (wp)
1550 {
1551 user_id_t watchID = wp->GetID();
1552 addr_t addr = wp->GetLoadAddress();
1553 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1554 if (log)
1555 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1556 if (wp->IsEnabled())
1557 {
1558 if (log)
1559 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1560 return error;
1561 }
1562 else
1563 {
1564 // Pass down an appropriate z/Z packet...
1565 error.SetErrorString("watchpoints not supported");
1566 }
1567 }
1568 else
1569 {
1570 error.SetErrorString("Watchpoint location argument was NULL.");
1571 }
1572 if (error.Success())
1573 error.SetErrorToGenericError();
1574 return error;
1575}
1576
1577Error
1578ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1579{
1580 Error error;
1581 if (wp)
1582 {
1583 user_id_t watchID = wp->GetID();
1584
1585 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1586
1587 addr_t addr = wp->GetLoadAddress();
1588 if (log)
1589 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1590
1591 if (wp->IsHardware())
1592 {
1593 // Pass down an appropriate z/Z packet...
1594 error.SetErrorString("watchpoints not supported");
1595 }
1596 // TODO: clear software watchpoints if we implement them
1597 }
1598 else
1599 {
1600 error.SetErrorString("Watchpoint location argument was NULL.");
1601 }
1602 if (error.Success())
1603 error.SetErrorToGenericError();
1604 return error;
1605}
1606
1607void
1608ProcessGDBRemote::Clear()
1609{
1610 m_flags = 0;
1611 m_thread_list.Clear();
1612 {
1613 Mutex::Locker locker(m_stdio_mutex);
1614 m_stdout_data.clear();
1615 }
1616 DestoryLibUnwindAddressSpace();
1617}
1618
1619Error
1620ProcessGDBRemote::DoSignal (int signo)
1621{
1622 Error error;
1623 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1624 if (log)
1625 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1626
1627 if (!m_gdb_comm.SendAsyncSignal (signo))
1628 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1629 return error;
1630}
1631
Chris Lattner24943d22010-06-08 16:52:24 +00001632void
1633ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1634{
1635 ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1636 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1637}
1638
1639void
1640ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1641{
1642 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1643 Mutex::Locker locker(m_stdio_mutex);
1644 m_stdout_data.append(s, len);
1645
1646 // FIXME: Make a real data object for this and put it out.
1647 BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1648}
1649
1650
1651Error
1652ProcessGDBRemote::StartDebugserverProcess
1653(
1654 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1655 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1656 char const *inferior_envp[], // Environment to pass along to the inferior program
1657 char const *stdio_path,
1658 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID then attach to this attach_pid
1659 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1660 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Clayton452bf612010-08-31 18:35:14 +00001661 bool disable_aslr, // Disable ASLR
Chris Lattner24943d22010-06-08 16:52:24 +00001662 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1663)
1664{
1665 Error error;
1666 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1667 {
1668 // If we locate debugserver, keep that located version around
1669 static FileSpec g_debugserver_file_spec;
1670
1671 FileSpec debugserver_file_spec;
1672 char debugserver_path[PATH_MAX];
1673
1674 // Always check to see if we have an environment override for the path
1675 // to the debugserver to use and use it if we do.
1676 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1677 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001678 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001679 else
1680 debugserver_file_spec = g_debugserver_file_spec;
1681 bool debugserver_exists = debugserver_file_spec.Exists();
1682 if (!debugserver_exists)
1683 {
1684 // The debugserver binary is in the LLDB.framework/Resources
1685 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001686 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001687 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001688 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001689 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001690 if (debugserver_exists)
1691 {
1692 g_debugserver_file_spec = debugserver_file_spec;
1693 }
1694 else
1695 {
1696 g_debugserver_file_spec.Clear();
1697 debugserver_file_spec.Clear();
1698 }
Chris Lattner24943d22010-06-08 16:52:24 +00001699 }
1700 }
1701
1702 if (debugserver_exists)
1703 {
1704 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1705
1706 m_stdio_communication.Clear();
1707 posix_spawnattr_t attr;
1708
1709 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
1710
1711 Error local_err; // Errors that don't affect the spawning.
1712 if (log)
1713 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1714 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1715 if (error.Fail() || log)
1716 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
1717 if (error.Fail())
1718 return error;;
1719
1720#if !defined (__arm__)
1721
Greg Clayton24b48ff2010-10-17 22:03:32 +00001722 // We don't need to do this for ARM, and we really shouldn't now
1723 // that we have multiple CPU subtypes and no posix_spawnattr call
1724 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001725 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001726 {
Greg Claytoncf015052010-06-11 03:25:34 +00001727 cpu_type_t cpu = inferior_arch.GetCPUType();
1728 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1729 {
1730 size_t ocount = 0;
1731 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1732 if (error.Fail() || log)
1733 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 +00001734
Greg Claytoncf015052010-06-11 03:25:34 +00001735 if (error.Fail() != 0 || ocount != 1)
1736 return error;
1737 }
Chris Lattner24943d22010-06-08 16:52:24 +00001738 }
1739
1740#endif
1741
1742 Args debugserver_args;
1743 char arg_cstr[PATH_MAX];
1744 bool launch_process = true;
1745
1746 if (inferior_argv == NULL && attach_pid != LLDB_INVALID_PROCESS_ID)
1747 launch_process = false;
1748 else if (attach_name)
1749 launch_process = false; // Wait for a process whose basename matches that in inferior_argv[0]
1750
1751 bool pass_stdio_path_to_debugserver = true;
1752 lldb_utility::PseudoTerminal pty;
1753 if (stdio_path == NULL)
1754 {
Caroline Tice91a1dab2010-11-05 22:37:44 +00001755 if (! m_local_debugserver)
1756 pass_stdio_path_to_debugserver = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001757 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
1758 {
1759 struct termios stdin_termios;
1760 if (::tcgetattr (pty.GetMasterFileDescriptor(), &stdin_termios) == 0)
1761 {
1762 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing
1763 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time
1764 ::tcsetattr (pty.GetMasterFileDescriptor(), TCSANOW, &stdin_termios);
1765 }
1766 stdio_path = pty.GetSlaveName (NULL, 0);
1767 }
1768 }
1769
1770 // Start args with "debugserver /file/path -r --"
1771 debugserver_args.AppendArgument(debugserver_path);
1772 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001773 // use native registers, not the GDB registers
1774 debugserver_args.AppendArgument("--native-regs");
1775 // make debugserver run in its own session so signals generated by
1776 // special terminal key sequences (^C) don't affect debugserver
1777 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001778
Greg Clayton452bf612010-08-31 18:35:14 +00001779 if (disable_aslr)
1780 debugserver_args.AppendArguments("--disable-aslr");
1781
Chris Lattner24943d22010-06-08 16:52:24 +00001782 // Only set the inferior
1783 if (launch_process)
1784 {
1785 if (stdio_path && pass_stdio_path_to_debugserver)
1786 {
1787 debugserver_args.AppendArgument("-s"); // short for --stdio-path
1788 StreamString strm;
Caroline Tice91a1dab2010-11-05 22:37:44 +00001789 strm.Printf("%s", stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001790 debugserver_args.AppendArgument(strm.GetData()); // path to file to have inferior open as it's STDIO
1791 }
1792 }
1793
1794 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1795 if (env_debugserver_log_file)
1796 {
1797 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1798 debugserver_args.AppendArgument(arg_cstr);
1799 }
1800
1801 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1802 if (env_debugserver_log_flags)
1803 {
1804 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1805 debugserver_args.AppendArgument(arg_cstr);
1806 }
1807// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1808// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1809
1810 // Now append the program arguments
1811 if (launch_process)
1812 {
1813 if (inferior_argv)
1814 {
1815 // Terminate the debugserver args so we can now append the inferior args
1816 debugserver_args.AppendArgument("--");
1817
1818 for (int i = 0; inferior_argv[i] != NULL; ++i)
1819 debugserver_args.AppendArgument (inferior_argv[i]);
1820 }
1821 else
1822 {
1823 // Will send environment entries with the 'QEnvironment:' packet
1824 // Will send arguments with the 'A' packet
1825 }
1826 }
1827 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1828 {
1829 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1830 debugserver_args.AppendArgument (arg_cstr);
1831 }
1832 else if (attach_name && attach_name[0])
1833 {
1834 if (wait_for_launch)
1835 debugserver_args.AppendArgument ("--waitfor");
1836 else
1837 debugserver_args.AppendArgument ("--attach");
1838 debugserver_args.AppendArgument (attach_name);
1839 }
1840
1841 Error file_actions_err;
1842 posix_spawn_file_actions_t file_actions;
1843#if DONT_CLOSE_DEBUGSERVER_STDIO
1844 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1845#else
1846 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1847 if (file_actions_err.Success())
1848 {
1849 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1850 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1851 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1852 }
1853#endif
1854
1855 if (log)
1856 {
1857 StreamString strm;
1858 debugserver_args.Dump (&strm);
1859 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1860 }
1861
1862 error.SetError(::posix_spawnp (&m_debugserver_pid,
1863 debugserver_path,
1864 file_actions_err.Success() ? &file_actions : NULL,
1865 &attr,
1866 debugserver_args.GetArgumentVector(),
1867 (char * const*)inferior_envp),
1868 eErrorTypePOSIX);
1869
Greg Claytone9d0df42010-07-02 01:29:13 +00001870
1871 ::posix_spawnattr_destroy (&attr);
1872
Chris Lattner24943d22010-06-08 16:52:24 +00001873 if (file_actions_err.Success())
1874 ::posix_spawn_file_actions_destroy (&file_actions);
1875
1876 // We have seen some cases where posix_spawnp was returning a valid
1877 // looking pid even when an error was returned, so clear it out
1878 if (error.Fail())
1879 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1880
1881 if (error.Fail() || log)
1882 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);
1883
Caroline Tice91a1dab2010-11-05 22:37:44 +00001884 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1885 {
1886 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true));
1887 if (conn_ap.get())
1888 {
1889 m_stdio_communication.SetConnection(conn_ap.release());
1890 if (m_stdio_communication.IsConnected())
1891 {
1892 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1893 m_stdio_communication.StartReadThread();
1894 }
1895 }
1896 }
Chris Lattner24943d22010-06-08 16:52:24 +00001897 }
1898 else
1899 {
1900 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1901 }
1902
1903 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1904 StartAsyncThread ();
1905 }
1906 return error;
1907}
1908
1909bool
1910ProcessGDBRemote::MonitorDebugserverProcess
1911(
1912 void *callback_baton,
1913 lldb::pid_t debugserver_pid,
1914 int signo, // Zero for no signal
1915 int exit_status // Exit value of process if signal is zero
1916)
1917{
1918 // We pass in the ProcessGDBRemote inferior process it and name it
1919 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1920 // pointer value itself, thus we need the double cast...
1921
1922 // "debugserver_pid" argument passed in is the process ID for
1923 // debugserver that we are tracking...
1924
Greg Clayton75ccf502010-08-21 02:22:51 +00001925 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1926
1927 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001928 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001929 // Sleep for a half a second to make sure our inferior process has
1930 // time to set its exit status before we set it incorrectly when
1931 // both the debugserver and the inferior process shut down.
1932 usleep (500000);
1933 // If our process hasn't yet exited, debugserver might have died.
1934 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001935 const StateType state = process->GetState();
1936
1937 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1938 state != eStateInvalid &&
1939 state != eStateUnloaded &&
1940 state != eStateExited &&
1941 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001942 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001943 char error_str[1024];
1944 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001945 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001946 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1947 if (signal_cstr)
1948 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001949 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001950 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001951 }
1952 else
1953 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001954 ::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 +00001955 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001956
1957 process->SetExitStatus (-1, error_str);
1958 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001959 // Debugserver has exited we need to let our ProcessGDBRemote
1960 // know that it no longer has a debugserver instance
1961 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1962 // We are returning true to this function below, so we can
1963 // forget about the monitor handle.
1964 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001965 }
1966 return true;
1967}
1968
1969void
1970ProcessGDBRemote::KillDebugserverProcess ()
1971{
1972 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1973 {
1974 ::kill (m_debugserver_pid, SIGINT);
1975 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1976 }
1977}
1978
1979void
1980ProcessGDBRemote::Initialize()
1981{
1982 static bool g_initialized = false;
1983
1984 if (g_initialized == false)
1985 {
1986 g_initialized = true;
1987 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1988 GetPluginDescriptionStatic(),
1989 CreateInstance);
1990
1991 Log::Callbacks log_callbacks = {
1992 ProcessGDBRemoteLog::DisableLog,
1993 ProcessGDBRemoteLog::EnableLog,
1994 ProcessGDBRemoteLog::ListLogCategories
1995 };
1996
1997 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1998 }
1999}
2000
2001bool
2002ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2003{
2004 if (m_curr_tid == tid)
2005 return true;
2006
2007 char packet[32];
2008 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2009 assert (packet_len + 1 < sizeof(packet));
2010 StringExtractorGDBRemote response;
2011 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2012 {
2013 if (response.IsOKPacket())
2014 {
2015 m_curr_tid = tid;
2016 return true;
2017 }
2018 }
2019 return false;
2020}
2021
2022bool
2023ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2024{
2025 if (m_curr_tid_run == tid)
2026 return true;
2027
2028 char packet[32];
2029 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2030 assert (packet_len + 1 < sizeof(packet));
2031 StringExtractorGDBRemote response;
2032 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2033 {
2034 if (response.IsOKPacket())
2035 {
2036 m_curr_tid_run = tid;
2037 return true;
2038 }
2039 }
2040 return false;
2041}
2042
2043void
2044ProcessGDBRemote::ResetGDBRemoteState ()
2045{
2046 // Reset and GDB remote state
2047 m_curr_tid = LLDB_INVALID_THREAD_ID;
2048 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2049 m_z0_supported = 1;
2050}
2051
2052
2053bool
2054ProcessGDBRemote::StartAsyncThread ()
2055{
2056 ResetGDBRemoteState ();
2057
2058 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2059
2060 if (log)
2061 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2062
2063 // Create a thread that watches our internal state and controls which
2064 // events make it to clients (into the DCProcess event queue).
2065 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2066 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2067}
2068
2069void
2070ProcessGDBRemote::StopAsyncThread ()
2071{
2072 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2073
2074 if (log)
2075 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2076
2077 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2078
2079 // Stop the stdio thread
2080 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2081 {
2082 Host::ThreadJoin (m_async_thread, NULL, NULL);
2083 }
2084}
2085
2086
2087void *
2088ProcessGDBRemote::AsyncThread (void *arg)
2089{
2090 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2091
2092 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
2093 if (log)
2094 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2095
2096 Listener listener ("ProcessGDBRemote::AsyncThread");
2097 EventSP event_sp;
2098 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2099 eBroadcastBitAsyncThreadShouldExit;
2100
2101 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2102 {
2103 bool done = false;
2104 while (!done)
2105 {
Caroline Tice926060e2010-10-29 21:48:37 +00002106 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002107 if (log)
2108 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2109 if (listener.WaitForEvent (NULL, event_sp))
2110 {
2111 const uint32_t event_type = event_sp->GetType();
2112 switch (event_type)
2113 {
2114 case eBroadcastBitAsyncContinue:
2115 {
2116 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2117
2118 if (continue_packet)
2119 {
2120 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2121 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002122 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002123 if (log)
2124 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2125
2126 process->SetPrivateState(eStateRunning);
2127 StringExtractorGDBRemote response;
2128 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2129
2130 switch (stop_state)
2131 {
2132 case eStateStopped:
2133 case eStateCrashed:
2134 case eStateSuspended:
2135 process->m_last_stop_packet = response;
2136 process->m_last_stop_packet.SetFilePos (0);
2137 process->SetPrivateState (stop_state);
2138 break;
2139
2140 case eStateExited:
2141 process->m_last_stop_packet = response;
2142 process->m_last_stop_packet.SetFilePos (0);
2143 response.SetFilePos(1);
2144 process->SetExitStatus(response.GetHexU8(), NULL);
2145 done = true;
2146 break;
2147
2148 case eStateInvalid:
2149 break;
2150
2151 default:
2152 process->SetPrivateState (stop_state);
2153 break;
2154 }
2155 }
2156 }
2157 break;
2158
2159 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002160 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002161 if (log)
2162 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2163 done = true;
2164 break;
2165
2166 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002167 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002168 if (log)
2169 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2170 done = true;
2171 break;
2172 }
2173 }
2174 else
2175 {
Caroline Tice926060e2010-10-29 21:48:37 +00002176 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002177 if (log)
2178 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2179 done = true;
2180 }
2181 }
2182 }
2183
Caroline Tice926060e2010-10-29 21:48:37 +00002184 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002185 if (log)
2186 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2187
2188 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2189 return NULL;
2190}
2191
2192lldb_private::unw_addr_space_t
2193ProcessGDBRemote::GetLibUnwindAddressSpace ()
2194{
2195 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002196
2197 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2198 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002199 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002200 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002201 target_type = UNW_TARGET_X86_64;
2202
2203 if (m_libunwind_addr_space)
2204 {
2205 if (m_libunwind_target_type != target_type)
2206 DestoryLibUnwindAddressSpace();
2207 else
2208 return m_libunwind_addr_space;
2209 }
2210 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2211 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2212 if (m_libunwind_addr_space)
2213 m_libunwind_target_type = target_type;
2214 else
2215 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2216 return m_libunwind_addr_space;
2217}
2218
2219void
2220ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2221{
2222 if (m_libunwind_addr_space)
2223 {
2224 unw_destroy_addr_space (m_libunwind_addr_space);
2225 m_libunwind_addr_space = NULL;
2226 }
2227 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2228}
2229
2230
2231const char *
2232ProcessGDBRemote::GetDispatchQueueNameForThread
2233(
2234 addr_t thread_dispatch_qaddr,
2235 std::string &dispatch_queue_name
2236)
2237{
2238 dispatch_queue_name.clear();
2239 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2240 {
2241 // Cache the dispatch_queue_offsets_addr value so we don't always have
2242 // to look it up
2243 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2244 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002245 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2246 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002247 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002248 if (module_sp)
2249 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2250
2251 if (dispatch_queue_offsets_symbol == NULL)
2252 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002253 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002254 if (module_sp)
2255 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2256 }
Chris Lattner24943d22010-06-08 16:52:24 +00002257 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002258 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002259
2260 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2261 return NULL;
2262 }
2263
2264 uint8_t memory_buffer[8];
2265 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2266
2267 // Excerpt from src/queue_private.h
2268 struct dispatch_queue_offsets_s
2269 {
2270 uint16_t dqo_version;
2271 uint16_t dqo_label;
2272 uint16_t dqo_label_size;
2273 } dispatch_queue_offsets;
2274
2275
2276 Error error;
2277 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2278 {
2279 uint32_t data_offset = 0;
2280 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2281 {
2282 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2283 {
2284 data_offset = 0;
2285 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2286 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2287 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2288 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2289 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2290 dispatch_queue_name.erase (bytes_read);
2291 }
2292 }
2293 }
2294 }
2295 if (dispatch_queue_name.empty())
2296 return NULL;
2297 return dispatch_queue_name.c_str();
2298}
2299
Jim Ingham7508e732010-08-09 23:31:02 +00002300uint32_t
2301ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2302{
2303 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2304 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2305 if (m_local_debugserver)
2306 {
2307 return Host::ListProcessesMatchingName (name, matches, pids);
2308 }
2309 else
2310 {
2311 // FIXME: Implement talking to the remote debugserver.
2312 return 0;
2313 }
2314
2315}