blob: 1f0bc149833fd45a8b363e9271dcdecbad7435bf [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),
Chris Lattner24943d22010-06-08 16:52:24 +0000107 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000108 m_gdb_comm(),
109 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000110 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000111 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000112 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000113 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
114 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000115 m_curr_tid (LLDB_INVALID_THREAD_ID),
116 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000117 m_z0_supported (1),
118 m_continue_packet(),
119 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000120 m_packet_timeout (1),
121 m_max_memory_size (512),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_libunwind_target_type (UNW_TARGET_UNSPECIFIED),
123 m_libunwind_addr_space (NULL),
Jim Ingham7508e732010-08-09 23:31:02 +0000124 m_waiting_for_attach (false),
125 m_local_debugserver (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000126{
127}
128
129//----------------------------------------------------------------------
130// Destructor
131//----------------------------------------------------------------------
132ProcessGDBRemote::~ProcessGDBRemote()
133{
Greg Claytonff5cac22010-12-13 18:11:18 +0000134 m_dynamic_loader_ap.reset();
135
Greg Clayton75ccf502010-08-21 02:22:51 +0000136 if (m_debugserver_thread != LLDB_INVALID_HOST_THREAD)
137 {
138 Host::ThreadCancel (m_debugserver_thread, NULL);
139 thread_result_t thread_result;
140 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
141 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
142 }
Chris Lattner24943d22010-06-08 16:52:24 +0000143 // m_mach_process.UnregisterNotificationCallbacks (this);
144 Clear();
145}
146
147//----------------------------------------------------------------------
148// PluginInterface
149//----------------------------------------------------------------------
150const char *
151ProcessGDBRemote::GetPluginName()
152{
153 return "Process debugging plug-in that uses the GDB remote protocol";
154}
155
156const char *
157ProcessGDBRemote::GetShortPluginName()
158{
159 return GetPluginNameStatic();
160}
161
162uint32_t
163ProcessGDBRemote::GetPluginVersion()
164{
165 return 1;
166}
167
168void
169ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
170{
171 strm->Printf("TODO: fill this in\n");
172}
173
174Error
175ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
176{
177 Error error;
178 error.SetErrorString("No plug-in commands are currently supported.");
179 return error;
180}
181
182Log *
183ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
184{
185 return NULL;
186}
187
188void
189ProcessGDBRemote::BuildDynamicRegisterInfo ()
190{
191 char register_info_command[64];
192 m_register_info.Clear();
193 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
194 uint32_t reg_offset = 0;
195 uint32_t reg_num = 0;
196 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
197 {
198 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
199 StringExtractorGDBRemote response;
200 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
201 {
202 packet_type = response.GetType();
203 if (packet_type == StringExtractorGDBRemote::eResponse)
204 {
205 std::string name;
206 std::string value;
207 ConstString reg_name;
208 ConstString alt_name;
209 ConstString set_name;
210 RegisterInfo reg_info = { NULL, // Name
211 NULL, // Alt name
212 0, // byte size
213 reg_offset, // offset
214 eEncodingUint, // encoding
215 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000216 {
217 LLDB_INVALID_REGNUM, // GCC reg num
218 LLDB_INVALID_REGNUM, // DWARF reg num
219 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000220 reg_num, // GDB reg num
221 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000222 }
223 };
224
225 while (response.GetNameColonValue(name, value))
226 {
227 if (name.compare("name") == 0)
228 {
229 reg_name.SetCString(value.c_str());
230 }
231 else if (name.compare("alt-name") == 0)
232 {
233 alt_name.SetCString(value.c_str());
234 }
235 else if (name.compare("bitsize") == 0)
236 {
237 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
238 }
239 else if (name.compare("offset") == 0)
240 {
241 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000242 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000243 {
244 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000245 }
246 }
247 else if (name.compare("encoding") == 0)
248 {
249 if (value.compare("uint") == 0)
250 reg_info.encoding = eEncodingUint;
251 else if (value.compare("sint") == 0)
252 reg_info.encoding = eEncodingSint;
253 else if (value.compare("ieee754") == 0)
254 reg_info.encoding = eEncodingIEEE754;
255 else if (value.compare("vector") == 0)
256 reg_info.encoding = eEncodingVector;
257 }
258 else if (name.compare("format") == 0)
259 {
260 if (value.compare("binary") == 0)
261 reg_info.format = eFormatBinary;
262 else if (value.compare("decimal") == 0)
263 reg_info.format = eFormatDecimal;
264 else if (value.compare("hex") == 0)
265 reg_info.format = eFormatHex;
266 else if (value.compare("float") == 0)
267 reg_info.format = eFormatFloat;
268 else if (value.compare("vector-sint8") == 0)
269 reg_info.format = eFormatVectorOfSInt8;
270 else if (value.compare("vector-uint8") == 0)
271 reg_info.format = eFormatVectorOfUInt8;
272 else if (value.compare("vector-sint16") == 0)
273 reg_info.format = eFormatVectorOfSInt16;
274 else if (value.compare("vector-uint16") == 0)
275 reg_info.format = eFormatVectorOfUInt16;
276 else if (value.compare("vector-sint32") == 0)
277 reg_info.format = eFormatVectorOfSInt32;
278 else if (value.compare("vector-uint32") == 0)
279 reg_info.format = eFormatVectorOfUInt32;
280 else if (value.compare("vector-float32") == 0)
281 reg_info.format = eFormatVectorOfFloat32;
282 else if (value.compare("vector-uint128") == 0)
283 reg_info.format = eFormatVectorOfUInt128;
284 }
285 else if (name.compare("set") == 0)
286 {
287 set_name.SetCString(value.c_str());
288 }
289 else if (name.compare("gcc") == 0)
290 {
291 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
292 }
293 else if (name.compare("dwarf") == 0)
294 {
295 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
296 }
297 else if (name.compare("generic") == 0)
298 {
299 if (value.compare("pc") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
301 else if (value.compare("sp") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
303 else if (value.compare("fp") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
305 else if (value.compare("ra") == 0)
306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
307 else if (value.compare("flags") == 0)
308 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
309 }
310 }
311
Jason Molenda53d96862010-06-11 23:44:18 +0000312 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000313 assert (reg_info.byte_size != 0);
314 reg_offset += reg_info.byte_size;
315 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
316 }
317 }
318 else
319 {
320 packet_type = StringExtractorGDBRemote::eError;
321 }
322 }
323
324 if (reg_num == 0)
325 {
326 // We didn't get anything. See if we are debugging ARM and fill with
327 // a hard coded register set until we can get an updated debugserver
328 // down on the devices.
329 ArchSpec arm_arch ("arm");
330 if (GetTarget().GetArchitecture() == arm_arch)
331 m_register_info.HardcodeARMRegisters();
332 }
333 m_register_info.Finalize ();
334}
335
336Error
337ProcessGDBRemote::WillLaunch (Module* module)
338{
339 return WillLaunchOrAttach ();
340}
341
342Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000343ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000344{
345 return WillLaunchOrAttach ();
346}
347
348Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000349ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000350{
351 return WillLaunchOrAttach ();
352}
353
354Error
355ProcessGDBRemote::WillLaunchOrAttach ()
356{
357 Error error;
358 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
359 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
360
361 if (m_dynamic_loader_ap.get() == NULL)
362 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
363 m_stdio_communication.Clear ();
364
365 return error;
366}
367
368//----------------------------------------------------------------------
369// Process Control
370//----------------------------------------------------------------------
371Error
372ProcessGDBRemote::DoLaunch
373(
374 Module* module,
375 char const *argv[],
376 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000377 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000378 const char *stdin_path,
379 const char *stdout_path,
380 const char *stderr_path
381)
382{
Greg Clayton4b407112010-09-30 21:49:03 +0000383 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000384 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
385 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
386 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000387
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
Greg Clayton23cf0c72010-11-08 04:29:11 +0000395 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000396 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,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000406 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000407 LLDB_INVALID_PROCESS_ID,
408 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000409 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000410 inferior_arch);
411 if (error.Fail())
412 return error;
413
414 error = ConnectToDebugserver (host_port);
415 if (error.Success())
416 {
417 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
418 }
419 }
420 else
421 {
422 error = StartDebugserverProcess (host_port,
423 NULL,
424 NULL,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000425 NULL, //stdin_path
426 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000427 LLDB_INVALID_PROCESS_ID,
428 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000429 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000430 inferior_arch);
431 if (error.Fail())
432 return error;
433
434 error = ConnectToDebugserver (host_port);
435 if (error.Success())
436 {
437 // Send the environment and the program + arguments after we connect
438 if (envp)
439 {
440 const char *env_entry;
441 for (int i=0; (env_entry = envp[i]); ++i)
442 {
443 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
444 break;
445 }
446 }
447
Greg Clayton960d6a42010-08-03 00:35:52 +0000448 // FIXME: convert this to use the new set/show variables when they are available
449#if 0
450 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
451 {
452 const uint32_t attach_debugserver_secs = 10;
453 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
454 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
455 {
456 printf ("%i\n", attach_debugserver_secs - i);
457 sleep (1);
458 }
459 }
460#endif
461
Chris Lattner24943d22010-06-08 16:52:24 +0000462 const uint32_t arg_timeout_seconds = 10;
463 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
464 if (arg_packet_err == 0)
465 {
466 std::string error_str;
467 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
468 {
469 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
470 }
471 else
472 {
473 error.SetErrorString (error_str.c_str());
474 }
475 }
476 else
477 {
478 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
479 }
480
481 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
482 }
483 }
484
485 if (GetID() == LLDB_INVALID_PROCESS_ID)
486 {
487 KillDebugserverProcess ();
488 return error;
489 }
490
491 StringExtractorGDBRemote response;
492 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
493 SetPrivateState (SetThreadStopInfo (response));
494
495 }
496 else
497 {
498 // Set our user ID to an invalid process ID.
499 SetID(LLDB_INVALID_PROCESS_ID);
500 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
501 }
Chris Lattner24943d22010-06-08 16:52:24 +0000502 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000503
Chris Lattner24943d22010-06-08 16:52:24 +0000504}
505
506
507Error
508ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
509{
510 Error error;
511 // Sleep and wait a bit for debugserver to start to listen...
512 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
513 if (conn_ap.get())
514 {
515 std::string connect_url("connect://");
516 connect_url.append (host_port);
517 const uint32_t max_retry_count = 50;
518 uint32_t retry_count = 0;
519 while (!m_gdb_comm.IsConnected())
520 {
521 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
522 {
523 m_gdb_comm.SetConnection (conn_ap.release());
524 break;
525 }
526 retry_count++;
527
528 if (retry_count >= max_retry_count)
529 break;
530
531 usleep (100000);
532 }
533 }
534
535 if (!m_gdb_comm.IsConnected())
536 {
537 if (error.Success())
538 error.SetErrorString("not connected to remote gdb server");
539 return error;
540 }
541
542 m_gdb_comm.SetAckMode (true);
543 if (m_gdb_comm.StartReadThread(&error))
544 {
545 // Send an initial ack
546 m_gdb_comm.SendAck('+');
547
548 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000549 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
550 this,
551 m_debugserver_pid,
552 false);
553
Chris Lattner24943d22010-06-08 16:52:24 +0000554 StringExtractorGDBRemote response;
555 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
556 {
557 if (response.IsOKPacket())
558 m_gdb_comm.SetAckMode (false);
559 }
Chris Lattner24943d22010-06-08 16:52:24 +0000560 }
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
Greg Clayton20d338f2010-11-18 05:57:03 +0000576 BuildDynamicRegisterInfo ();
577
578 m_byte_order = m_gdb_comm.GetByteOrder();
579
580 Module * exe_module = GetTarget().GetExecutableModule().get();
Chris Lattner24943d22010-06-08 16:52:24 +0000581 assert(exe_module);
582
Chris Lattner24943d22010-06-08 16:52:24 +0000583 ObjectFile *exe_objfile = exe_module->GetObjectFile();
584 assert(exe_objfile);
585
Chris Lattner24943d22010-06-08 16:52:24 +0000586 StreamString strm;
587
588 ArchSpec inferior_arch;
589 // See if the GDB server supports the qHostInfo information
590 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
591 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Clayton20d338f2010-11-18 05:57:03 +0000592 ArchSpec arch_spec (GetTarget().GetArchitecture());
Chris Lattner24943d22010-06-08 16:52:24 +0000593
Jim Ingham7508e732010-08-09 23:31:02 +0000594 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000595 {
596 // For ARM we can't trust the arch of the process as it could
597 // have an armv6 object file, but be running on armv7 kernel.
598 inferior_arch = m_gdb_comm.GetHostArchitecture();
599 }
600
601 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000602 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000603
604 if (vendor == NULL)
605 vendor = Host::GetVendorString().AsCString("apple");
606
607 if (os_type == NULL)
608 os_type = Host::GetOSString().AsCString("darwin");
609
610 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
611
612 std::transform (strm.GetString().begin(),
613 strm.GetString().end(),
614 strm.GetString().begin(),
615 ::tolower);
616
617 m_target_triple.SetCString(strm.GetString().c_str());
618 }
619}
620
621void
622ProcessGDBRemote::DidLaunch ()
623{
624 DidLaunchOrAttach ();
625 if (m_dynamic_loader_ap.get())
626 m_dynamic_loader_ap->DidLaunch();
627}
628
629Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000630ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000631{
632 Error error;
633 // Clear out and clean up from any current state
634 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000635 ArchSpec arch_spec = GetTarget().GetArchitecture();
636
Greg Claytone005f2c2010-11-06 01:53:30 +0000637 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000638
639
Chris Lattner24943d22010-06-08 16:52:24 +0000640 if (attach_pid != LLDB_INVALID_PROCESS_ID)
641 {
Chris Lattner24943d22010-06-08 16:52:24 +0000642 char host_port[128];
643 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000644 error = StartDebugserverProcess (host_port, // debugserver_url
645 NULL, // inferior_argv
646 NULL, // inferior_envp
647 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000648 false, // launch_process == false (we are attaching)
649 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
650 NULL, // Don't send any attach by process name option to debugserver
651 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000652 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000653 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000654
655 if (error.Fail())
656 {
657 const char *error_string = error.AsCString();
658 if (error_string == NULL)
659 error_string = "unable to launch " DEBUGSERVER_BASENAME;
660
661 SetExitStatus (-1, error_string);
662 }
663 else
664 {
665 error = ConnectToDebugserver (host_port);
666 if (error.Success())
667 {
668 char packet[64];
669 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
670 StringExtractorGDBRemote response;
671 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
672 packet,
673 packet_len,
674 response);
675 switch (stop_state)
676 {
677 case eStateStopped:
678 case eStateCrashed:
679 case eStateSuspended:
680 SetID (attach_pid);
681 m_last_stop_packet = response;
682 m_last_stop_packet.SetFilePos (0);
683 SetPrivateState (stop_state);
684 break;
685
686 case eStateExited:
687 m_last_stop_packet = response;
688 m_last_stop_packet.SetFilePos (0);
689 response.SetFilePos(1);
690 SetExitStatus(response.GetHexU8(), NULL);
691 break;
692
693 default:
694 SetExitStatus(-1, "unable to attach to process");
695 break;
696 }
697
698 }
699 }
700 }
701
702 lldb::pid_t pid = GetID();
703 if (pid == LLDB_INVALID_PROCESS_ID)
704 {
705 KillDebugserverProcess();
706 }
707 return error;
708}
709
710size_t
711ProcessGDBRemote::AttachInputReaderCallback
712(
713 void *baton,
714 InputReader *reader,
715 lldb::InputReaderAction notification,
716 const char *bytes,
717 size_t bytes_len
718)
719{
720 if (notification == eInputReaderGotToken)
721 {
722 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
723 if (gdb_process->m_waiting_for_attach)
724 gdb_process->m_waiting_for_attach = false;
725 reader->SetIsDone(true);
726 return 1;
727 }
728 return 0;
729}
730
731Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000732ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000733{
734 Error error;
735 // Clear out and clean up from any current state
736 Clear();
737 // HACK: require arch be set correctly at the target level until we can
738 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000739
Greg Claytone005f2c2010-11-06 01:53:30 +0000740 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000741 if (process_name && process_name[0])
742 {
Chris Lattner24943d22010-06-08 16:52:24 +0000743 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000744 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000745 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000746 error = StartDebugserverProcess (host_port, // debugserver_url
747 NULL, // inferior_argv
748 NULL, // inferior_envp
749 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000750 false, // launch_process == false (we are attaching)
751 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
752 NULL, // Don't send any attach by process name option to debugserver
753 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000754 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000755 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000756 if (error.Fail())
757 {
758 const char *error_string = error.AsCString();
759 if (error_string == NULL)
760 error_string = "unable to launch " DEBUGSERVER_BASENAME;
761
762 SetExitStatus (-1, error_string);
763 }
764 else
765 {
766 error = ConnectToDebugserver (host_port);
767 if (error.Success())
768 {
769 StreamString packet;
770
Chris Lattner24943d22010-06-08 16:52:24 +0000771 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000772 packet.PutCString("vAttachWait");
773 else
774 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000775 packet.PutChar(';');
776 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
777 StringExtractorGDBRemote response;
778 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
779 packet.GetData(),
780 packet.GetSize(),
781 response);
782 switch (stop_state)
783 {
784 case eStateStopped:
785 case eStateCrashed:
786 case eStateSuspended:
787 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
788 m_last_stop_packet = response;
789 m_last_stop_packet.SetFilePos (0);
790 SetPrivateState (stop_state);
791 break;
792
793 case eStateExited:
794 m_last_stop_packet = response;
795 m_last_stop_packet.SetFilePos (0);
796 response.SetFilePos(1);
797 SetExitStatus(response.GetHexU8(), NULL);
798 break;
799
800 default:
801 SetExitStatus(-1, "unable to attach to process");
802 break;
803 }
804 }
805 }
806 }
807
808 lldb::pid_t pid = GetID();
809 if (pid == LLDB_INVALID_PROCESS_ID)
810 {
811 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000812
813 if (error.Success())
814 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000815 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000816
Chris Lattner24943d22010-06-08 16:52:24 +0000817 return error;
818}
819
820//
821// if (wait_for_launch)
822// {
823// InputReaderSP reader_sp (new InputReader());
824// StreamString instructions;
825// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
826// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
827// this, // baton
828// eInputReaderGranularityByte,
829// NULL, // End token
830// false);
831//
832// StringExtractorGDBRemote response;
833// m_waiting_for_attach = true;
834// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
835// while (m_waiting_for_attach)
836// {
837// // Wait for one second for the stop reply packet
838// if (m_gdb_comm.WaitForPacket(response, 1))
839// {
840// // Got some sort of packet, see if it is the stop reply packet?
841// char ch = response.GetChar(0);
842// if (ch == 'T')
843// {
844// m_waiting_for_attach = false;
845// }
846// }
847// else
848// {
849// // Put a period character every second
850// fputc('.', reader_out_fh);
851// }
852// }
853// }
854// }
855// return GetID();
856//}
857
858void
859ProcessGDBRemote::DidAttach ()
860{
Chris Lattner24943d22010-06-08 16:52:24 +0000861 if (m_dynamic_loader_ap.get())
862 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000863 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000864}
865
866Error
867ProcessGDBRemote::WillResume ()
868{
869 m_continue_packet.Clear();
870 // Start the continue packet we will use to run the target. Each thread
871 // will append what it is supposed to be doing to this packet when the
872 // ThreadList::WillResume() is called. If a thread it supposed
873 // to stay stopped, then don't append anything to this string.
874 m_continue_packet.Printf("vCont");
875 return Error();
876}
877
878Error
879ProcessGDBRemote::DoResume ()
880{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000881 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000882 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000883
884 Listener listener ("gdb-remote.resume-packet-sent");
885 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
886 {
887 EventSP event_sp;
888 TimeValue timeout;
889 timeout = TimeValue::Now();
890 timeout.OffsetWithSeconds (5);
891 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
892
893 if (listener.WaitForEvent (&timeout, event_sp) == false)
894 error.SetErrorString("Resume timed out.");
895 }
896
Jim Ingham3ae449a2010-11-17 02:32:00 +0000897 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000898}
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
Greg Claytone005f2c2010-11-06 01:53:30 +0000951 LogSP 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
Jim Ingham3ae449a2010-11-17 02:32:00 +00001115ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001116{
1117 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001118
Chris Lattner24943d22010-06-08 16:52:24 +00001119 if (m_gdb_comm.IsRunning())
1120 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001121 caused_stop = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001122 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001123 Mutex::Locker locker;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001124
Greg Clayton20d338f2010-11-18 05:57:03 +00001125 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001126 {
1127 if (timed_out)
1128 error.SetErrorString("timed out sending interrupt packet");
1129 else
1130 error.SetErrorString("unknown error sending interrupt packet");
1131 }
1132 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001133 else
1134 {
1135 caused_stop = false;
1136 }
1137
Chris Lattner24943d22010-06-08 16:52:24 +00001138 return error;
1139}
1140
1141Error
1142ProcessGDBRemote::WillDetach ()
1143{
1144 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001145
Greg Clayton4fb400f2010-09-27 21:07:38 +00001146 if (m_gdb_comm.IsRunning())
1147 {
1148 bool timed_out = false;
1149 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001150 PausePrivateStateThread();
1151 m_thread_list.DiscardThreadPlans();
1152 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001153 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1154 {
1155 if (timed_out)
1156 error.SetErrorString("timed out sending interrupt packet");
1157 else
1158 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001159 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001160 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001161 TimeValue timeout_time;
1162 timeout_time = TimeValue::Now();
1163 timeout_time.OffsetWithSeconds(2);
1164
1165 EventSP event_sp;
1166 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1167 if (state != eStateStopped)
1168 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001169 }
Chris Lattner24943d22010-06-08 16:52:24 +00001170 return error;
1171}
1172
Greg Clayton4fb400f2010-09-27 21:07:38 +00001173Error
1174ProcessGDBRemote::DoDetach()
1175{
1176 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001177 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001178 if (log)
1179 log->Printf ("ProcessGDBRemote::DoDetach()");
1180
1181 DisableAllBreakpointSites ();
1182
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001183 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001184
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001185 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1186 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001187 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001188 if (response_size)
1189 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1190 else
1191 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001192 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001193 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001194 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001195
Greg Clayton4fb400f2010-09-27 21:07:38 +00001196 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001197 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001198
1199 SetPrivateState (eStateDetached);
1200 ResumePrivateStateThread();
1201
1202 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001203 return error;
1204}
Chris Lattner24943d22010-06-08 16:52:24 +00001205
1206Error
1207ProcessGDBRemote::DoDestroy ()
1208{
1209 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001210 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001211 if (log)
1212 log->Printf ("ProcessGDBRemote::DoDestroy()");
1213
1214 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001215 Mutex::Locker locker;
1216 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001217 DisableAllBreakpointSites ();
1218 SetExitStatus(-1, "process killed");
1219
1220 StringExtractorGDBRemote response;
Greg Claytonb749a262010-12-03 06:02:24 +00001221 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 1, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001222 {
Caroline Tice926060e2010-10-29 21:48:37 +00001223 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001224 if (log)
1225 {
1226 if (response.IsOKPacket())
1227 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1228 else
1229 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1230 }
1231 }
1232
1233 StopAsyncThread ();
1234 m_gdb_comm.StopReadThread();
1235 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001236 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001237 return error;
1238}
1239
Chris Lattner24943d22010-06-08 16:52:24 +00001240//------------------------------------------------------------------
1241// Process Queries
1242//------------------------------------------------------------------
1243
1244bool
1245ProcessGDBRemote::IsAlive ()
1246{
Greg Clayton58e844b2010-12-08 05:08:21 +00001247 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001248}
1249
1250addr_t
1251ProcessGDBRemote::GetImageInfoAddress()
1252{
1253 if (!m_gdb_comm.IsRunning())
1254 {
1255 StringExtractorGDBRemote response;
1256 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1257 {
1258 if (response.IsNormalPacket())
1259 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1260 }
1261 }
1262 return LLDB_INVALID_ADDRESS;
1263}
1264
1265DynamicLoader *
1266ProcessGDBRemote::GetDynamicLoader()
1267{
1268 return m_dynamic_loader_ap.get();
1269}
1270
1271//------------------------------------------------------------------
1272// Process Memory
1273//------------------------------------------------------------------
1274size_t
1275ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1276{
1277 if (size > m_max_memory_size)
1278 {
1279 // Keep memory read sizes down to a sane limit. This function will be
1280 // called multiple times in order to complete the task by
1281 // lldb_private::Process so it is ok to do this.
1282 size = m_max_memory_size;
1283 }
1284
1285 char packet[64];
1286 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1287 assert (packet_len + 1 < sizeof(packet));
1288 StringExtractorGDBRemote response;
1289 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1290 {
1291 if (response.IsNormalPacket())
1292 {
1293 error.Clear();
1294 return response.GetHexBytes(buf, size, '\xdd');
1295 }
1296 else if (response.IsErrorPacket())
1297 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1298 else if (response.IsUnsupportedPacket())
1299 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1300 else
1301 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1302 }
1303 else
1304 {
1305 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1306 }
1307 return 0;
1308}
1309
1310size_t
1311ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1312{
1313 StreamString packet;
1314 packet.Printf("M%llx,%zx:", addr, size);
1315 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1316 StringExtractorGDBRemote response;
1317 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1318 {
1319 if (response.IsOKPacket())
1320 {
1321 error.Clear();
1322 return size;
1323 }
1324 else if (response.IsErrorPacket())
1325 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1326 else if (response.IsUnsupportedPacket())
1327 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1328 else
1329 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1330 }
1331 else
1332 {
1333 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1334 }
1335 return 0;
1336}
1337
1338lldb::addr_t
1339ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1340{
1341 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1342 if (allocated_addr == LLDB_INVALID_ADDRESS)
1343 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1344 else
1345 error.Clear();
1346 return allocated_addr;
1347}
1348
1349Error
1350ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1351{
1352 Error error;
1353 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1354 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1355 return error;
1356}
1357
1358
1359//------------------------------------------------------------------
1360// Process STDIO
1361//------------------------------------------------------------------
1362
1363size_t
1364ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1365{
1366 Mutex::Locker locker(m_stdio_mutex);
1367 size_t bytes_available = m_stdout_data.size();
1368 if (bytes_available > 0)
1369 {
1370 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1371 if (bytes_available > buf_size)
1372 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001373 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001374 m_stdout_data.erase(0, buf_size);
1375 bytes_available = buf_size;
1376 }
1377 else
1378 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001379 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001380 m_stdout_data.clear();
1381
1382 //ResetEventBits(eBroadcastBitSTDOUT);
1383 }
1384 }
1385 return bytes_available;
1386}
1387
1388size_t
1389ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1390{
1391 // Can we get STDERR through the remote protocol?
1392 return 0;
1393}
1394
1395size_t
1396ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1397{
1398 if (m_stdio_communication.IsConnected())
1399 {
1400 ConnectionStatus status;
1401 m_stdio_communication.Write(src, src_len, status, NULL);
1402 }
1403 return 0;
1404}
1405
1406Error
1407ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1408{
1409 Error error;
1410 assert (bp_site != NULL);
1411
Greg Claytone005f2c2010-11-06 01:53:30 +00001412 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001413 user_id_t site_id = bp_site->GetID();
1414 const addr_t addr = bp_site->GetLoadAddress();
1415 if (log)
1416 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1417
1418 if (bp_site->IsEnabled())
1419 {
1420 if (log)
1421 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1422 return error;
1423 }
1424 else
1425 {
1426 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1427
1428 if (bp_site->HardwarePreferred())
1429 {
1430 // Try and set hardware breakpoint, and if that fails, fall through
1431 // and set a software breakpoint?
1432 }
1433
1434 if (m_z0_supported)
1435 {
1436 char packet[64];
1437 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1438 assert (packet_len + 1 < sizeof(packet));
1439 StringExtractorGDBRemote response;
1440 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1441 {
1442 if (response.IsUnsupportedPacket())
1443 {
1444 // Disable z packet support and try again
1445 m_z0_supported = 0;
1446 return EnableBreakpoint (bp_site);
1447 }
1448 else if (response.IsOKPacket())
1449 {
1450 bp_site->SetEnabled(true);
1451 bp_site->SetType (BreakpointSite::eExternal);
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 EnableSoftwareBreakpoint (bp_site);
1465 }
1466 }
1467
1468 if (log)
1469 {
1470 const char *err_string = error.AsCString();
1471 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1472 bp_site->GetLoadAddress(),
1473 err_string ? err_string : "NULL");
1474 }
1475 // We shouldn't reach here on a successful breakpoint enable...
1476 if (error.Success())
1477 error.SetErrorToGenericError();
1478 return error;
1479}
1480
1481Error
1482ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1483{
1484 Error error;
1485 assert (bp_site != NULL);
1486 addr_t addr = bp_site->GetLoadAddress();
1487 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001488 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001489 if (log)
1490 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1491
1492 if (bp_site->IsEnabled())
1493 {
1494 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1495
1496 if (bp_site->IsHardware())
1497 {
1498 // TODO: disable hardware breakpoint...
1499 }
1500 else
1501 {
1502 if (m_z0_supported)
1503 {
1504 char packet[64];
1505 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1506 assert (packet_len + 1 < sizeof(packet));
1507 StringExtractorGDBRemote response;
1508 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1509 {
1510 if (response.IsUnsupportedPacket())
1511 {
1512 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1513 }
1514 else if (response.IsOKPacket())
1515 {
1516 if (log)
1517 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1518 bp_site->SetEnabled(false);
1519 return error;
1520 }
1521 else
1522 {
1523 uint8_t error_byte = response.GetError();
1524 if (error_byte)
1525 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1526 }
1527 }
1528 }
1529 else
1530 {
1531 return DisableSoftwareBreakpoint (bp_site);
1532 }
1533 }
1534 }
1535 else
1536 {
1537 if (log)
1538 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1539 return error;
1540 }
1541
1542 if (error.Success())
1543 error.SetErrorToGenericError();
1544 return error;
1545}
1546
1547Error
1548ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1549{
1550 Error error;
1551 if (wp)
1552 {
1553 user_id_t watchID = wp->GetID();
1554 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001555 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001556 if (log)
1557 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1558 if (wp->IsEnabled())
1559 {
1560 if (log)
1561 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1562 return error;
1563 }
1564 else
1565 {
1566 // Pass down an appropriate z/Z packet...
1567 error.SetErrorString("watchpoints not supported");
1568 }
1569 }
1570 else
1571 {
1572 error.SetErrorString("Watchpoint location argument was NULL.");
1573 }
1574 if (error.Success())
1575 error.SetErrorToGenericError();
1576 return error;
1577}
1578
1579Error
1580ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1581{
1582 Error error;
1583 if (wp)
1584 {
1585 user_id_t watchID = wp->GetID();
1586
Greg Claytone005f2c2010-11-06 01:53:30 +00001587 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001588
1589 addr_t addr = wp->GetLoadAddress();
1590 if (log)
1591 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1592
1593 if (wp->IsHardware())
1594 {
1595 // Pass down an appropriate z/Z packet...
1596 error.SetErrorString("watchpoints not supported");
1597 }
1598 // TODO: clear software watchpoints if we implement them
1599 }
1600 else
1601 {
1602 error.SetErrorString("Watchpoint location argument was NULL.");
1603 }
1604 if (error.Success())
1605 error.SetErrorToGenericError();
1606 return error;
1607}
1608
1609void
1610ProcessGDBRemote::Clear()
1611{
1612 m_flags = 0;
1613 m_thread_list.Clear();
1614 {
1615 Mutex::Locker locker(m_stdio_mutex);
1616 m_stdout_data.clear();
1617 }
1618 DestoryLibUnwindAddressSpace();
1619}
1620
1621Error
1622ProcessGDBRemote::DoSignal (int signo)
1623{
1624 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001625 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001626 if (log)
1627 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1628
1629 if (!m_gdb_comm.SendAsyncSignal (signo))
1630 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1631 return error;
1632}
1633
Caroline Tice861efb32010-11-16 05:07:41 +00001634//void
1635//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1636//{
1637// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1638// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1639//}
Chris Lattner24943d22010-06-08 16:52:24 +00001640
Caroline Tice861efb32010-11-16 05:07:41 +00001641//void
1642//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1643//{
1644// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1645// Mutex::Locker locker(m_stdio_mutex);
1646// m_stdout_data.append(s, len);
1647//
1648// // FIXME: Make a real data object for this and put it out.
1649// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1650//}
Chris Lattner24943d22010-06-08 16:52:24 +00001651
1652
1653Error
1654ProcessGDBRemote::StartDebugserverProcess
1655(
1656 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1657 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1658 char const *inferior_envp[], // Environment to pass along to the inferior program
1659 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001660 bool launch_process, // Set to true if we are going to be launching a the process
1661 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID send this pid as an argument to debugserver
Chris Lattner24943d22010-06-08 16:52:24 +00001662 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1663 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001664 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001665 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1666)
1667{
1668 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001669 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1670 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001671 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1672 {
1673 // If we locate debugserver, keep that located version around
1674 static FileSpec g_debugserver_file_spec;
1675
1676 FileSpec debugserver_file_spec;
1677 char debugserver_path[PATH_MAX];
1678
1679 // Always check to see if we have an environment override for the path
1680 // to the debugserver to use and use it if we do.
1681 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1682 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001683 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001684 else
1685 debugserver_file_spec = g_debugserver_file_spec;
1686 bool debugserver_exists = debugserver_file_spec.Exists();
1687 if (!debugserver_exists)
1688 {
1689 // The debugserver binary is in the LLDB.framework/Resources
1690 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001691 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001692 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001693 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001694 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001695 if (debugserver_exists)
1696 {
1697 g_debugserver_file_spec = debugserver_file_spec;
1698 }
1699 else
1700 {
1701 g_debugserver_file_spec.Clear();
1702 debugserver_file_spec.Clear();
1703 }
Chris Lattner24943d22010-06-08 16:52:24 +00001704 }
1705 }
1706
1707 if (debugserver_exists)
1708 {
1709 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1710
1711 m_stdio_communication.Clear();
1712 posix_spawnattr_t attr;
1713
Greg Claytone005f2c2010-11-06 01:53:30 +00001714 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001715
1716 Error local_err; // Errors that don't affect the spawning.
1717 if (log)
1718 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1719 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1720 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001721 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001722 if (error.Fail())
1723 return error;;
1724
1725#if !defined (__arm__)
1726
Greg Clayton24b48ff2010-10-17 22:03:32 +00001727 // We don't need to do this for ARM, and we really shouldn't now
1728 // that we have multiple CPU subtypes and no posix_spawnattr call
1729 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001730 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001731 {
Greg Claytoncf015052010-06-11 03:25:34 +00001732 cpu_type_t cpu = inferior_arch.GetCPUType();
1733 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1734 {
1735 size_t ocount = 0;
1736 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1737 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001738 error.PutToLog(log.get(), "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount);
Chris Lattner24943d22010-06-08 16:52:24 +00001739
Greg Claytoncf015052010-06-11 03:25:34 +00001740 if (error.Fail() != 0 || ocount != 1)
1741 return error;
1742 }
Chris Lattner24943d22010-06-08 16:52:24 +00001743 }
1744
1745#endif
1746
1747 Args debugserver_args;
1748 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001749
Chris Lattner24943d22010-06-08 16:52:24 +00001750 lldb_utility::PseudoTerminal pty;
Caroline Ticebd666012010-12-03 18:46:09 +00001751 if (launch_process && stdio_path == NULL && m_local_debugserver && !no_stdio)
Chris Lattner24943d22010-06-08 16:52:24 +00001752 {
Chris Lattner24943d22010-06-08 16:52:24 +00001753 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001754 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001755 }
1756
1757 // Start args with "debugserver /file/path -r --"
1758 debugserver_args.AppendArgument(debugserver_path);
1759 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001760 // use native registers, not the GDB registers
1761 debugserver_args.AppendArgument("--native-regs");
1762 // make debugserver run in its own session so signals generated by
1763 // special terminal key sequences (^C) don't affect debugserver
1764 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001765
Greg Clayton452bf612010-08-31 18:35:14 +00001766 if (disable_aslr)
1767 debugserver_args.AppendArguments("--disable-aslr");
1768
Chris Lattner24943d22010-06-08 16:52:24 +00001769 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001770 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001771 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001772 debugserver_args.AppendArgument("--stdio-path");
1773 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001774 }
Caroline Ticebd666012010-12-03 18:46:09 +00001775 else if (launch_process && no_stdio)
1776 {
1777 debugserver_args.AppendArgument("--no-stdio");
1778 }
Chris Lattner24943d22010-06-08 16:52:24 +00001779
1780 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1781 if (env_debugserver_log_file)
1782 {
1783 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1784 debugserver_args.AppendArgument(arg_cstr);
1785 }
1786
1787 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1788 if (env_debugserver_log_flags)
1789 {
1790 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1791 debugserver_args.AppendArgument(arg_cstr);
1792 }
1793// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1794// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1795
1796 // Now append the program arguments
1797 if (launch_process)
1798 {
1799 if (inferior_argv)
1800 {
1801 // Terminate the debugserver args so we can now append the inferior args
1802 debugserver_args.AppendArgument("--");
1803
1804 for (int i = 0; inferior_argv[i] != NULL; ++i)
1805 debugserver_args.AppendArgument (inferior_argv[i]);
1806 }
1807 else
1808 {
1809 // Will send environment entries with the 'QEnvironment:' packet
1810 // Will send arguments with the 'A' packet
1811 }
1812 }
1813 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1814 {
1815 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1816 debugserver_args.AppendArgument (arg_cstr);
1817 }
1818 else if (attach_name && attach_name[0])
1819 {
1820 if (wait_for_launch)
1821 debugserver_args.AppendArgument ("--waitfor");
1822 else
1823 debugserver_args.AppendArgument ("--attach");
1824 debugserver_args.AppendArgument (attach_name);
1825 }
1826
1827 Error file_actions_err;
1828 posix_spawn_file_actions_t file_actions;
1829#if DONT_CLOSE_DEBUGSERVER_STDIO
1830 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1831#else
1832 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1833 if (file_actions_err.Success())
1834 {
1835 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1836 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1837 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1838 }
1839#endif
1840
1841 if (log)
1842 {
1843 StreamString strm;
1844 debugserver_args.Dump (&strm);
1845 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1846 }
1847
1848 error.SetError(::posix_spawnp (&m_debugserver_pid,
1849 debugserver_path,
1850 file_actions_err.Success() ? &file_actions : NULL,
1851 &attr,
1852 debugserver_args.GetArgumentVector(),
1853 (char * const*)inferior_envp),
1854 eErrorTypePOSIX);
1855
Greg Claytone9d0df42010-07-02 01:29:13 +00001856
1857 ::posix_spawnattr_destroy (&attr);
1858
Chris Lattner24943d22010-06-08 16:52:24 +00001859 if (file_actions_err.Success())
1860 ::posix_spawn_file_actions_destroy (&file_actions);
1861
1862 // We have seen some cases where posix_spawnp was returning a valid
1863 // looking pid even when an error was returned, so clear it out
1864 if (error.Fail())
1865 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1866
1867 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001868 error.PutToLog(log.get(), "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", m_debugserver_pid, debugserver_path, NULL, &attr, inferior_argv, inferior_envp);
Chris Lattner24943d22010-06-08 16:52:24 +00001869
Caroline Ticebd666012010-12-03 18:46:09 +00001870 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00001871 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001872 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001873 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001874 }
Chris Lattner24943d22010-06-08 16:52:24 +00001875 }
1876 else
1877 {
1878 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1879 }
1880
1881 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1882 StartAsyncThread ();
1883 }
1884 return error;
1885}
1886
1887bool
1888ProcessGDBRemote::MonitorDebugserverProcess
1889(
1890 void *callback_baton,
1891 lldb::pid_t debugserver_pid,
1892 int signo, // Zero for no signal
1893 int exit_status // Exit value of process if signal is zero
1894)
1895{
1896 // We pass in the ProcessGDBRemote inferior process it and name it
1897 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1898 // pointer value itself, thus we need the double cast...
1899
1900 // "debugserver_pid" argument passed in is the process ID for
1901 // debugserver that we are tracking...
1902
Greg Clayton75ccf502010-08-21 02:22:51 +00001903 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1904
1905 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001906 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001907 // Sleep for a half a second to make sure our inferior process has
1908 // time to set its exit status before we set it incorrectly when
1909 // both the debugserver and the inferior process shut down.
1910 usleep (500000);
1911 // If our process hasn't yet exited, debugserver might have died.
1912 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001913 const StateType state = process->GetState();
1914
1915 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1916 state != eStateInvalid &&
1917 state != eStateUnloaded &&
1918 state != eStateExited &&
1919 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001920 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001921 char error_str[1024];
1922 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001923 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001924 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1925 if (signal_cstr)
1926 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001927 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001928 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001929 }
1930 else
1931 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001932 ::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 +00001933 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001934
1935 process->SetExitStatus (-1, error_str);
1936 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001937 // Debugserver has exited we need to let our ProcessGDBRemote
1938 // know that it no longer has a debugserver instance
1939 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1940 // We are returning true to this function below, so we can
1941 // forget about the monitor handle.
1942 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001943 }
1944 return true;
1945}
1946
1947void
1948ProcessGDBRemote::KillDebugserverProcess ()
1949{
1950 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1951 {
1952 ::kill (m_debugserver_pid, SIGINT);
1953 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1954 }
1955}
1956
1957void
1958ProcessGDBRemote::Initialize()
1959{
1960 static bool g_initialized = false;
1961
1962 if (g_initialized == false)
1963 {
1964 g_initialized = true;
1965 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1966 GetPluginDescriptionStatic(),
1967 CreateInstance);
1968
1969 Log::Callbacks log_callbacks = {
1970 ProcessGDBRemoteLog::DisableLog,
1971 ProcessGDBRemoteLog::EnableLog,
1972 ProcessGDBRemoteLog::ListLogCategories
1973 };
1974
1975 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1976 }
1977}
1978
1979bool
1980ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1981{
1982 if (m_curr_tid == tid)
1983 return true;
1984
1985 char packet[32];
1986 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1987 assert (packet_len + 1 < sizeof(packet));
1988 StringExtractorGDBRemote response;
1989 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1990 {
1991 if (response.IsOKPacket())
1992 {
1993 m_curr_tid = tid;
1994 return true;
1995 }
1996 }
1997 return false;
1998}
1999
2000bool
2001ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2002{
2003 if (m_curr_tid_run == tid)
2004 return true;
2005
2006 char packet[32];
2007 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2008 assert (packet_len + 1 < sizeof(packet));
2009 StringExtractorGDBRemote response;
2010 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2011 {
2012 if (response.IsOKPacket())
2013 {
2014 m_curr_tid_run = tid;
2015 return true;
2016 }
2017 }
2018 return false;
2019}
2020
2021void
2022ProcessGDBRemote::ResetGDBRemoteState ()
2023{
2024 // Reset and GDB remote state
2025 m_curr_tid = LLDB_INVALID_THREAD_ID;
2026 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2027 m_z0_supported = 1;
2028}
2029
2030
2031bool
2032ProcessGDBRemote::StartAsyncThread ()
2033{
2034 ResetGDBRemoteState ();
2035
Greg Claytone005f2c2010-11-06 01:53:30 +00002036 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002037
2038 if (log)
2039 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2040
2041 // Create a thread that watches our internal state and controls which
2042 // events make it to clients (into the DCProcess event queue).
2043 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2044 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2045}
2046
2047void
2048ProcessGDBRemote::StopAsyncThread ()
2049{
Greg Claytone005f2c2010-11-06 01:53:30 +00002050 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002051
2052 if (log)
2053 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2054
2055 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2056
2057 // Stop the stdio thread
2058 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2059 {
2060 Host::ThreadJoin (m_async_thread, NULL, NULL);
2061 }
2062}
2063
2064
2065void *
2066ProcessGDBRemote::AsyncThread (void *arg)
2067{
2068 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2069
Greg Claytone005f2c2010-11-06 01:53:30 +00002070 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002071 if (log)
2072 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2073
2074 Listener listener ("ProcessGDBRemote::AsyncThread");
2075 EventSP event_sp;
2076 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2077 eBroadcastBitAsyncThreadShouldExit;
2078
2079 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2080 {
2081 bool done = false;
2082 while (!done)
2083 {
Caroline Tice926060e2010-10-29 21:48:37 +00002084 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002085 if (log)
2086 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2087 if (listener.WaitForEvent (NULL, event_sp))
2088 {
2089 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002090 if (log)
2091 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2092
Chris Lattner24943d22010-06-08 16:52:24 +00002093 switch (event_type)
2094 {
2095 case eBroadcastBitAsyncContinue:
2096 {
2097 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2098
2099 if (continue_packet)
2100 {
2101 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2102 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002103 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002104 if (log)
2105 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2106
2107 process->SetPrivateState(eStateRunning);
2108 StringExtractorGDBRemote response;
2109 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2110
2111 switch (stop_state)
2112 {
2113 case eStateStopped:
2114 case eStateCrashed:
2115 case eStateSuspended:
2116 process->m_last_stop_packet = response;
2117 process->m_last_stop_packet.SetFilePos (0);
2118 process->SetPrivateState (stop_state);
2119 break;
2120
2121 case eStateExited:
2122 process->m_last_stop_packet = response;
2123 process->m_last_stop_packet.SetFilePos (0);
2124 response.SetFilePos(1);
2125 process->SetExitStatus(response.GetHexU8(), NULL);
2126 done = true;
2127 break;
2128
2129 case eStateInvalid:
2130 break;
2131
2132 default:
2133 process->SetPrivateState (stop_state);
2134 break;
2135 }
2136 }
2137 }
2138 break;
2139
2140 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002141 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002142 if (log)
2143 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2144 done = true;
2145 break;
2146
2147 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002148 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002149 if (log)
2150 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2151 done = true;
2152 break;
2153 }
2154 }
2155 else
2156 {
Caroline Tice926060e2010-10-29 21:48:37 +00002157 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002158 if (log)
2159 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2160 done = true;
2161 }
2162 }
2163 }
2164
Caroline Tice926060e2010-10-29 21:48:37 +00002165 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002166 if (log)
2167 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2168
2169 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2170 return NULL;
2171}
2172
2173lldb_private::unw_addr_space_t
2174ProcessGDBRemote::GetLibUnwindAddressSpace ()
2175{
2176 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002177
2178 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2179 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002180 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002181 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002182 target_type = UNW_TARGET_X86_64;
2183
2184 if (m_libunwind_addr_space)
2185 {
2186 if (m_libunwind_target_type != target_type)
2187 DestoryLibUnwindAddressSpace();
2188 else
2189 return m_libunwind_addr_space;
2190 }
2191 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2192 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2193 if (m_libunwind_addr_space)
2194 m_libunwind_target_type = target_type;
2195 else
2196 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2197 return m_libunwind_addr_space;
2198}
2199
2200void
2201ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2202{
2203 if (m_libunwind_addr_space)
2204 {
2205 unw_destroy_addr_space (m_libunwind_addr_space);
2206 m_libunwind_addr_space = NULL;
2207 }
2208 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2209}
2210
2211
2212const char *
2213ProcessGDBRemote::GetDispatchQueueNameForThread
2214(
2215 addr_t thread_dispatch_qaddr,
2216 std::string &dispatch_queue_name
2217)
2218{
2219 dispatch_queue_name.clear();
2220 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2221 {
2222 // Cache the dispatch_queue_offsets_addr value so we don't always have
2223 // to look it up
2224 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2225 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002226 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2227 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002228 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002229 if (module_sp)
2230 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2231
2232 if (dispatch_queue_offsets_symbol == NULL)
2233 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002234 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002235 if (module_sp)
2236 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2237 }
Chris Lattner24943d22010-06-08 16:52:24 +00002238 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002239 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002240
2241 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2242 return NULL;
2243 }
2244
2245 uint8_t memory_buffer[8];
2246 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2247
2248 // Excerpt from src/queue_private.h
2249 struct dispatch_queue_offsets_s
2250 {
2251 uint16_t dqo_version;
2252 uint16_t dqo_label;
2253 uint16_t dqo_label_size;
2254 } dispatch_queue_offsets;
2255
2256
2257 Error error;
2258 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2259 {
2260 uint32_t data_offset = 0;
2261 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2262 {
2263 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2264 {
2265 data_offset = 0;
2266 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2267 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2268 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2269 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2270 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2271 dispatch_queue_name.erase (bytes_read);
2272 }
2273 }
2274 }
2275 }
2276 if (dispatch_queue_name.empty())
2277 return NULL;
2278 return dispatch_queue_name.c_str();
2279}
2280
Jim Ingham7508e732010-08-09 23:31:02 +00002281uint32_t
2282ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2283{
2284 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2285 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2286 if (m_local_debugserver)
2287 {
2288 return Host::ListProcessesMatchingName (name, matches, pids);
2289 }
2290 else
2291 {
2292 // FIXME: Implement talking to the remote debugserver.
2293 return 0;
2294 }
2295
2296}