blob: 52499ba173aed57eded0d55698775cb952344951 [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),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000108 m_byte_order (eByteOrderHost),
Chris Lattner24943d22010-06-08 16:52:24 +0000109 m_gdb_comm(),
110 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000111 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000112 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000113 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000114 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
115 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000116 m_curr_tid (LLDB_INVALID_THREAD_ID),
117 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000118 m_z0_supported (1),
119 m_continue_packet(),
120 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000121 m_packet_timeout (1),
122 m_max_memory_size (512),
Chris Lattner24943d22010-06-08 16:52:24 +0000123 m_libunwind_target_type (UNW_TARGET_UNSPECIFIED),
124 m_libunwind_addr_space (NULL),
Jim Ingham7508e732010-08-09 23:31:02 +0000125 m_waiting_for_attach (false),
126 m_local_debugserver (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000127{
128}
129
130//----------------------------------------------------------------------
131// Destructor
132//----------------------------------------------------------------------
133ProcessGDBRemote::~ProcessGDBRemote()
134{
Greg Clayton75ccf502010-08-21 02:22:51 +0000135 if (m_debugserver_thread != LLDB_INVALID_HOST_THREAD)
136 {
137 Host::ThreadCancel (m_debugserver_thread, NULL);
138 thread_result_t thread_result;
139 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
140 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
141 }
Chris Lattner24943d22010-06-08 16:52:24 +0000142 // m_mach_process.UnregisterNotificationCallbacks (this);
143 Clear();
144}
145
146//----------------------------------------------------------------------
147// PluginInterface
148//----------------------------------------------------------------------
149const char *
150ProcessGDBRemote::GetPluginName()
151{
152 return "Process debugging plug-in that uses the GDB remote protocol";
153}
154
155const char *
156ProcessGDBRemote::GetShortPluginName()
157{
158 return GetPluginNameStatic();
159}
160
161uint32_t
162ProcessGDBRemote::GetPluginVersion()
163{
164 return 1;
165}
166
167void
168ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
169{
170 strm->Printf("TODO: fill this in\n");
171}
172
173Error
174ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
175{
176 Error error;
177 error.SetErrorString("No plug-in commands are currently supported.");
178 return error;
179}
180
181Log *
182ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
183{
184 return NULL;
185}
186
187void
188ProcessGDBRemote::BuildDynamicRegisterInfo ()
189{
190 char register_info_command[64];
191 m_register_info.Clear();
192 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
193 uint32_t reg_offset = 0;
194 uint32_t reg_num = 0;
195 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
196 {
197 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
198 StringExtractorGDBRemote response;
199 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
200 {
201 packet_type = response.GetType();
202 if (packet_type == StringExtractorGDBRemote::eResponse)
203 {
204 std::string name;
205 std::string value;
206 ConstString reg_name;
207 ConstString alt_name;
208 ConstString set_name;
209 RegisterInfo reg_info = { NULL, // Name
210 NULL, // Alt name
211 0, // byte size
212 reg_offset, // offset
213 eEncodingUint, // encoding
214 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000215 {
216 LLDB_INVALID_REGNUM, // GCC reg num
217 LLDB_INVALID_REGNUM, // DWARF reg num
218 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000219 reg_num, // GDB reg num
220 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000221 }
222 };
223
224 while (response.GetNameColonValue(name, value))
225 {
226 if (name.compare("name") == 0)
227 {
228 reg_name.SetCString(value.c_str());
229 }
230 else if (name.compare("alt-name") == 0)
231 {
232 alt_name.SetCString(value.c_str());
233 }
234 else if (name.compare("bitsize") == 0)
235 {
236 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
237 }
238 else if (name.compare("offset") == 0)
239 {
240 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000241 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000242 {
243 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000244 }
245 }
246 else if (name.compare("encoding") == 0)
247 {
248 if (value.compare("uint") == 0)
249 reg_info.encoding = eEncodingUint;
250 else if (value.compare("sint") == 0)
251 reg_info.encoding = eEncodingSint;
252 else if (value.compare("ieee754") == 0)
253 reg_info.encoding = eEncodingIEEE754;
254 else if (value.compare("vector") == 0)
255 reg_info.encoding = eEncodingVector;
256 }
257 else if (name.compare("format") == 0)
258 {
259 if (value.compare("binary") == 0)
260 reg_info.format = eFormatBinary;
261 else if (value.compare("decimal") == 0)
262 reg_info.format = eFormatDecimal;
263 else if (value.compare("hex") == 0)
264 reg_info.format = eFormatHex;
265 else if (value.compare("float") == 0)
266 reg_info.format = eFormatFloat;
267 else if (value.compare("vector-sint8") == 0)
268 reg_info.format = eFormatVectorOfSInt8;
269 else if (value.compare("vector-uint8") == 0)
270 reg_info.format = eFormatVectorOfUInt8;
271 else if (value.compare("vector-sint16") == 0)
272 reg_info.format = eFormatVectorOfSInt16;
273 else if (value.compare("vector-uint16") == 0)
274 reg_info.format = eFormatVectorOfUInt16;
275 else if (value.compare("vector-sint32") == 0)
276 reg_info.format = eFormatVectorOfSInt32;
277 else if (value.compare("vector-uint32") == 0)
278 reg_info.format = eFormatVectorOfUInt32;
279 else if (value.compare("vector-float32") == 0)
280 reg_info.format = eFormatVectorOfFloat32;
281 else if (value.compare("vector-uint128") == 0)
282 reg_info.format = eFormatVectorOfUInt128;
283 }
284 else if (name.compare("set") == 0)
285 {
286 set_name.SetCString(value.c_str());
287 }
288 else if (name.compare("gcc") == 0)
289 {
290 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
291 }
292 else if (name.compare("dwarf") == 0)
293 {
294 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
295 }
296 else if (name.compare("generic") == 0)
297 {
298 if (value.compare("pc") == 0)
299 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
300 else if (value.compare("sp") == 0)
301 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
302 else if (value.compare("fp") == 0)
303 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
304 else if (value.compare("ra") == 0)
305 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
306 else if (value.compare("flags") == 0)
307 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
308 }
309 }
310
Jason Molenda53d96862010-06-11 23:44:18 +0000311 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000312 assert (reg_info.byte_size != 0);
313 reg_offset += reg_info.byte_size;
314 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
315 }
316 }
317 else
318 {
319 packet_type = StringExtractorGDBRemote::eError;
320 }
321 }
322
323 if (reg_num == 0)
324 {
325 // We didn't get anything. See if we are debugging ARM and fill with
326 // a hard coded register set until we can get an updated debugserver
327 // down on the devices.
328 ArchSpec arm_arch ("arm");
329 if (GetTarget().GetArchitecture() == arm_arch)
330 m_register_info.HardcodeARMRegisters();
331 }
332 m_register_info.Finalize ();
333}
334
335Error
336ProcessGDBRemote::WillLaunch (Module* module)
337{
338 return WillLaunchOrAttach ();
339}
340
341Error
342ProcessGDBRemote::WillAttach (lldb::pid_t pid)
343{
344 return WillLaunchOrAttach ();
345}
346
347Error
348ProcessGDBRemote::WillAttach (const char *process_name, bool wait_for_launch)
349{
350 return WillLaunchOrAttach ();
351}
352
353Error
354ProcessGDBRemote::WillLaunchOrAttach ()
355{
356 Error error;
357 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
358 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
359
360 if (m_dynamic_loader_ap.get() == NULL)
361 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
362 m_stdio_communication.Clear ();
363
364 return error;
365}
366
367//----------------------------------------------------------------------
368// Process Control
369//----------------------------------------------------------------------
370Error
371ProcessGDBRemote::DoLaunch
372(
373 Module* module,
374 char const *argv[],
375 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000376 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000377 const char *stdin_path,
378 const char *stdout_path,
379 const char *stderr_path
380)
381{
Greg Clayton4b407112010-09-30 21:49:03 +0000382 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000383 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
384 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
385 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000386
387 ObjectFile * object_file = module->GetObjectFile();
388 if (object_file)
389 {
390 ArchSpec inferior_arch(module->GetArchitecture());
391 char host_port[128];
392 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
393
Greg Clayton23cf0c72010-11-08 04:29:11 +0000394 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000395 bool start_debugserver_with_inferior_args = false;
396 if (start_debugserver_with_inferior_args)
397 {
398 // We want to launch debugserver with the inferior program and its
399 // arguments on the command line. We should only do this if we
400 // the GDB server we are talking to doesn't support the 'A' packet.
401 error = StartDebugserverProcess (host_port,
402 argv,
403 envp,
404 NULL, //stdin_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000405 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000406 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,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000424 NULL, //stdin_path
425 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000426 LLDB_INVALID_PROCESS_ID,
427 NULL, false,
Benjamin Kramer2653be92010-09-03 18:20:07 +0000428 (launch_flags & eLaunchFlagDisableASLR) != 0,
Chris Lattner24943d22010-06-08 16:52:24 +0000429 inferior_arch);
430 if (error.Fail())
431 return error;
432
433 error = ConnectToDebugserver (host_port);
434 if (error.Success())
435 {
436 // Send the environment and the program + arguments after we connect
437 if (envp)
438 {
439 const char *env_entry;
440 for (int i=0; (env_entry = envp[i]); ++i)
441 {
442 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
443 break;
444 }
445 }
446
Greg Clayton960d6a42010-08-03 00:35:52 +0000447 // FIXME: convert this to use the new set/show variables when they are available
448#if 0
449 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
450 {
451 const uint32_t attach_debugserver_secs = 10;
452 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
453 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
454 {
455 printf ("%i\n", attach_debugserver_secs - i);
456 sleep (1);
457 }
458 }
459#endif
460
Chris Lattner24943d22010-06-08 16:52:24 +0000461 const uint32_t arg_timeout_seconds = 10;
462 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
463 if (arg_packet_err == 0)
464 {
465 std::string error_str;
466 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
467 {
468 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
469 }
470 else
471 {
472 error.SetErrorString (error_str.c_str());
473 }
474 }
475 else
476 {
477 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
478 }
479
480 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
481 }
482 }
483
484 if (GetID() == LLDB_INVALID_PROCESS_ID)
485 {
486 KillDebugserverProcess ();
487 return error;
488 }
489
490 StringExtractorGDBRemote response;
491 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
492 SetPrivateState (SetThreadStopInfo (response));
493
494 }
495 else
496 {
497 // Set our user ID to an invalid process ID.
498 SetID(LLDB_INVALID_PROCESS_ID);
499 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
500 }
Chris Lattner24943d22010-06-08 16:52:24 +0000501 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000502
Chris Lattner24943d22010-06-08 16:52:24 +0000503}
504
505
506Error
507ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
508{
509 Error error;
510 // Sleep and wait a bit for debugserver to start to listen...
511 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
512 if (conn_ap.get())
513 {
514 std::string connect_url("connect://");
515 connect_url.append (host_port);
516 const uint32_t max_retry_count = 50;
517 uint32_t retry_count = 0;
518 while (!m_gdb_comm.IsConnected())
519 {
520 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
521 {
522 m_gdb_comm.SetConnection (conn_ap.release());
523 break;
524 }
525 retry_count++;
526
527 if (retry_count >= max_retry_count)
528 break;
529
530 usleep (100000);
531 }
532 }
533
534 if (!m_gdb_comm.IsConnected())
535 {
536 if (error.Success())
537 error.SetErrorString("not connected to remote gdb server");
538 return error;
539 }
540
541 m_gdb_comm.SetAckMode (true);
542 if (m_gdb_comm.StartReadThread(&error))
543 {
544 // Send an initial ack
545 m_gdb_comm.SendAck('+');
546
547 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000548 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
549 this,
550 m_debugserver_pid,
551 false);
552
Chris Lattner24943d22010-06-08 16:52:24 +0000553 StringExtractorGDBRemote response;
554 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
555 {
556 if (response.IsOKPacket())
557 m_gdb_comm.SetAckMode (false);
558 }
559
560 BuildDynamicRegisterInfo ();
561 }
562 return error;
563}
564
565void
566ProcessGDBRemote::DidLaunchOrAttach ()
567{
568 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
569 if (GetID() == LLDB_INVALID_PROCESS_ID)
570 {
571 m_dynamic_loader_ap.reset();
572 }
573 else
574 {
575 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
576
Jim Ingham7508e732010-08-09 23:31:02 +0000577 Module * exe_module = GetTarget().GetExecutableModule ().get();
Chris Lattner24943d22010-06-08 16:52:24 +0000578 assert(exe_module);
579
Chris Lattner24943d22010-06-08 16:52:24 +0000580 ObjectFile *exe_objfile = exe_module->GetObjectFile();
581 assert(exe_objfile);
582
583 m_byte_order = exe_objfile->GetByteOrder();
584 assert (m_byte_order != eByteOrderInvalid);
585
586 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();
Jim Ingham7508e732010-08-09 23:31:02 +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
Greg Clayton452bf612010-08-31 18:35:14 +0000652 false, // disable_aslr
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
Greg Clayton452bf612010-08-31 18:35:14 +0000754 false, // disable_aslr
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{
Jim Ingham7508e732010-08-09 23:31:02 +0000861 // If we haven't got an executable module yet, then we should make a dynamic loader, and
862 // see if it can find the executable module for us. If we do have an executable module,
863 // make sure it matches the process we've just attached to.
864
865 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
866 if (!m_dynamic_loader_ap.get())
867 {
868 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
869 }
870
Chris Lattner24943d22010-06-08 16:52:24 +0000871 if (m_dynamic_loader_ap.get())
872 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000873
874 Module * new_exe_module = GetTarget().GetExecutableModule().get();
875 if (new_exe_module == NULL)
876 {
877
878 }
879
880 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000881}
882
883Error
884ProcessGDBRemote::WillResume ()
885{
886 m_continue_packet.Clear();
887 // Start the continue packet we will use to run the target. Each thread
888 // will append what it is supposed to be doing to this packet when the
889 // ThreadList::WillResume() is called. If a thread it supposed
890 // to stay stopped, then don't append anything to this string.
891 m_continue_packet.Printf("vCont");
892 return Error();
893}
894
895Error
896ProcessGDBRemote::DoResume ()
897{
898 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
899 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
900 return Error();
901}
902
903size_t
904ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
905{
906 const uint8_t *trap_opcode = NULL;
907 uint32_t trap_opcode_size = 0;
908
909 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
910 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
911 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
912 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
913
Jim Ingham7508e732010-08-09 23:31:02 +0000914 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000915 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000916 {
Greg Claytoncf015052010-06-11 03:25:34 +0000917 case ArchSpec::eCPU_i386:
918 case ArchSpec::eCPU_x86_64:
919 trap_opcode = g_i386_breakpoint_opcode;
920 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
921 break;
922
923 case ArchSpec::eCPU_arm:
924 // TODO: fill this in for ARM. We need to dig up the symbol for
925 // the address in the breakpoint locaiton and figure out if it is
926 // an ARM or Thumb breakpoint.
927 trap_opcode = g_arm_breakpoint_opcode;
928 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
929 break;
930
931 case ArchSpec::eCPU_ppc:
932 case ArchSpec::eCPU_ppc64:
933 trap_opcode = g_ppc_breakpoint_opcode;
934 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
935 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000936
Greg Claytoncf015052010-06-11 03:25:34 +0000937 default:
938 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
939 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000940 }
941
942 if (trap_opcode && trap_opcode_size)
943 {
944 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
945 return trap_opcode_size;
946 }
947 return 0;
948}
949
950uint32_t
951ProcessGDBRemote::UpdateThreadListIfNeeded ()
952{
953 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000954 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000955 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000956 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
957
Greg Clayton5205f0b2010-09-03 17:10:42 +0000958 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000959 const uint32_t stop_id = GetStopID();
960 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
961 {
962 // Update the thread list's stop id immediately so we don't recurse into this function.
963 ThreadList curr_thread_list (this);
964 curr_thread_list.SetStopID(stop_id);
965
966 Error err;
967 StringExtractorGDBRemote response;
968 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
969 response.IsNormalPacket();
970 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
971 {
972 char ch = response.GetChar();
973 if (ch == 'l')
974 break;
975 if (ch == 'm')
976 {
977 do
978 {
979 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
980
981 if (tid != LLDB_INVALID_THREAD_ID)
982 {
983 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
984 if (thread_sp)
985 thread_sp->GetRegisterContext()->Invalidate();
986 else
987 thread_sp.reset (new ThreadGDBRemote (*this, tid));
988 curr_thread_list.AddThread(thread_sp);
989 }
990
991 ch = response.GetChar();
992 } while (ch == ',');
993 }
994 }
995
996 m_thread_list = curr_thread_list;
997
998 SetThreadStopInfo (m_last_stop_packet);
999 }
1000 return GetThreadList().GetSize(false);
1001}
1002
1003
1004StateType
1005ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1006{
1007 const char stop_type = stop_packet.GetChar();
1008 switch (stop_type)
1009 {
1010 case 'T':
1011 case 'S':
1012 {
1013 // Stop with signal and thread info
1014 const uint8_t signo = stop_packet.GetHexU8();
1015 std::string name;
1016 std::string value;
1017 std::string thread_name;
1018 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001019 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001020 uint32_t tid = LLDB_INVALID_THREAD_ID;
1021 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1022 uint32_t exc_data_count = 0;
1023 while (stop_packet.GetNameColonValue(name, value))
1024 {
1025 if (name.compare("metype") == 0)
1026 {
1027 // exception type in big endian hex
1028 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1029 }
1030 else if (name.compare("mecount") == 0)
1031 {
1032 // exception count in big endian hex
1033 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1034 }
1035 else if (name.compare("medata") == 0)
1036 {
1037 // exception data in big endian hex
1038 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1039 }
1040 else if (name.compare("thread") == 0)
1041 {
1042 // thread in big endian hex
1043 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1044 }
1045 else if (name.compare("name") == 0)
1046 {
1047 thread_name.swap (value);
1048 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001049 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001050 {
1051 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1052 }
1053 }
1054 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1055
1056 if (thread_sp)
1057 {
1058 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1059
1060 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1061 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001062 if (exc_type != 0)
1063 {
Greg Clayton643ee732010-08-04 01:40:35 +00001064 const size_t exc_data_count = exc_data.size();
1065
1066 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1067 exc_type,
1068 exc_data_count,
1069 exc_data_count >= 1 ? exc_data[0] : 0,
1070 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001071 }
1072 else if (signo)
1073 {
Greg Clayton643ee732010-08-04 01:40:35 +00001074 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001075 }
1076 else
1077 {
Greg Clayton643ee732010-08-04 01:40:35 +00001078 StopInfoSP invalid_stop_info_sp;
1079 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001080 }
1081 }
1082 return eStateStopped;
1083 }
1084 break;
1085
1086 case 'W':
1087 // process exited
1088 return eStateExited;
1089
1090 default:
1091 break;
1092 }
1093 return eStateInvalid;
1094}
1095
1096void
1097ProcessGDBRemote::RefreshStateAfterStop ()
1098{
Jim Ingham7508e732010-08-09 23:31:02 +00001099 // FIXME - add a variable to tell that we're in the middle of attaching if we
1100 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001101 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001102// if (!GetTarget().GetArchitecture().IsValid())
1103// {
1104// Module *exe_module = GetTarget().GetExecutableModule().get();
1105// if (exe_module)
1106// m_arch_spec = exe_module->GetArchitecture();
1107// }
1108
Chris Lattner24943d22010-06-08 16:52:24 +00001109 // Let all threads recover from stopping and do any clean up based
1110 // on the previous thread state (if any).
1111 m_thread_list.RefreshStateAfterStop();
1112
1113 // Discover new threads:
1114 UpdateThreadListIfNeeded ();
1115}
1116
1117Error
1118ProcessGDBRemote::DoHalt ()
1119{
1120 Error error;
1121 if (m_gdb_comm.IsRunning())
1122 {
1123 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001124 Mutex::Locker locker;
1125 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 }
1133 return error;
1134}
1135
1136Error
1137ProcessGDBRemote::WillDetach ()
1138{
1139 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001140
Greg Clayton4fb400f2010-09-27 21:07:38 +00001141 if (m_gdb_comm.IsRunning())
1142 {
1143 bool timed_out = false;
1144 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001145 PausePrivateStateThread();
1146 m_thread_list.DiscardThreadPlans();
1147 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001148 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1149 {
1150 if (timed_out)
1151 error.SetErrorString("timed out sending interrupt packet");
1152 else
1153 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001154 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001155 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001156 TimeValue timeout_time;
1157 timeout_time = TimeValue::Now();
1158 timeout_time.OffsetWithSeconds(2);
1159
1160 EventSP event_sp;
1161 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1162 if (state != eStateStopped)
1163 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001164 }
Chris Lattner24943d22010-06-08 16:52:24 +00001165 return error;
1166}
1167
Greg Clayton4fb400f2010-09-27 21:07:38 +00001168Error
1169ProcessGDBRemote::DoDetach()
1170{
1171 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001172 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001173 if (log)
1174 log->Printf ("ProcessGDBRemote::DoDetach()");
1175
1176 DisableAllBreakpointSites ();
1177
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001178 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001179
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001180 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1181 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001182 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001183 if (response_size)
1184 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1185 else
1186 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001187 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001188 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001189 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001190
Greg Clayton4fb400f2010-09-27 21:07:38 +00001191 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001192 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001193
1194 SetPrivateState (eStateDetached);
1195 ResumePrivateStateThread();
1196
1197 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001198 return error;
1199}
Chris Lattner24943d22010-06-08 16:52:24 +00001200
1201Error
1202ProcessGDBRemote::DoDestroy ()
1203{
1204 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001205 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001206 if (log)
1207 log->Printf ("ProcessGDBRemote::DoDestroy()");
1208
1209 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001210 Mutex::Locker locker;
1211 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001212 DisableAllBreakpointSites ();
1213 SetExitStatus(-1, "process killed");
1214
1215 StringExtractorGDBRemote response;
1216 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1217 {
Caroline Tice926060e2010-10-29 21:48:37 +00001218 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001219 if (log)
1220 {
1221 if (response.IsOKPacket())
1222 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1223 else
1224 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1225 }
1226 }
1227
1228 StopAsyncThread ();
1229 m_gdb_comm.StopReadThread();
1230 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001231 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001232 return error;
1233}
1234
1235ByteOrder
1236ProcessGDBRemote::GetByteOrder () const
1237{
1238 return m_byte_order;
1239}
1240
1241//------------------------------------------------------------------
1242// Process Queries
1243//------------------------------------------------------------------
1244
1245bool
1246ProcessGDBRemote::IsAlive ()
1247{
1248 return m_gdb_comm.IsConnected();
1249}
1250
1251addr_t
1252ProcessGDBRemote::GetImageInfoAddress()
1253{
1254 if (!m_gdb_comm.IsRunning())
1255 {
1256 StringExtractorGDBRemote response;
1257 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1258 {
1259 if (response.IsNormalPacket())
1260 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1261 }
1262 }
1263 return LLDB_INVALID_ADDRESS;
1264}
1265
1266DynamicLoader *
1267ProcessGDBRemote::GetDynamicLoader()
1268{
1269 return m_dynamic_loader_ap.get();
1270}
1271
1272//------------------------------------------------------------------
1273// Process Memory
1274//------------------------------------------------------------------
1275size_t
1276ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1277{
1278 if (size > m_max_memory_size)
1279 {
1280 // Keep memory read sizes down to a sane limit. This function will be
1281 // called multiple times in order to complete the task by
1282 // lldb_private::Process so it is ok to do this.
1283 size = m_max_memory_size;
1284 }
1285
1286 char packet[64];
1287 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1288 assert (packet_len + 1 < sizeof(packet));
1289 StringExtractorGDBRemote response;
1290 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1291 {
1292 if (response.IsNormalPacket())
1293 {
1294 error.Clear();
1295 return response.GetHexBytes(buf, size, '\xdd');
1296 }
1297 else if (response.IsErrorPacket())
1298 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1299 else if (response.IsUnsupportedPacket())
1300 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1301 else
1302 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1303 }
1304 else
1305 {
1306 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1307 }
1308 return 0;
1309}
1310
1311size_t
1312ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1313{
1314 StreamString packet;
1315 packet.Printf("M%llx,%zx:", addr, size);
1316 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1317 StringExtractorGDBRemote response;
1318 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1319 {
1320 if (response.IsOKPacket())
1321 {
1322 error.Clear();
1323 return size;
1324 }
1325 else if (response.IsErrorPacket())
1326 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1327 else if (response.IsUnsupportedPacket())
1328 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1329 else
1330 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1331 }
1332 else
1333 {
1334 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1335 }
1336 return 0;
1337}
1338
1339lldb::addr_t
1340ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1341{
1342 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1343 if (allocated_addr == LLDB_INVALID_ADDRESS)
1344 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1345 else
1346 error.Clear();
1347 return allocated_addr;
1348}
1349
1350Error
1351ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1352{
1353 Error error;
1354 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1355 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1356 return error;
1357}
1358
1359
1360//------------------------------------------------------------------
1361// Process STDIO
1362//------------------------------------------------------------------
1363
1364size_t
1365ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1366{
1367 Mutex::Locker locker(m_stdio_mutex);
1368 size_t bytes_available = m_stdout_data.size();
1369 if (bytes_available > 0)
1370 {
1371 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1372 if (bytes_available > buf_size)
1373 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001374 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001375 m_stdout_data.erase(0, buf_size);
1376 bytes_available = buf_size;
1377 }
1378 else
1379 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001380 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001381 m_stdout_data.clear();
1382
1383 //ResetEventBits(eBroadcastBitSTDOUT);
1384 }
1385 }
1386 return bytes_available;
1387}
1388
1389size_t
1390ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1391{
1392 // Can we get STDERR through the remote protocol?
1393 return 0;
1394}
1395
1396size_t
1397ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1398{
1399 if (m_stdio_communication.IsConnected())
1400 {
1401 ConnectionStatus status;
1402 m_stdio_communication.Write(src, src_len, status, NULL);
1403 }
1404 return 0;
1405}
1406
1407Error
1408ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1409{
1410 Error error;
1411 assert (bp_site != NULL);
1412
Greg Claytone005f2c2010-11-06 01:53:30 +00001413 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001414 user_id_t site_id = bp_site->GetID();
1415 const addr_t addr = bp_site->GetLoadAddress();
1416 if (log)
1417 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1418
1419 if (bp_site->IsEnabled())
1420 {
1421 if (log)
1422 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1423 return error;
1424 }
1425 else
1426 {
1427 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1428
1429 if (bp_site->HardwarePreferred())
1430 {
1431 // Try and set hardware breakpoint, and if that fails, fall through
1432 // and set a software breakpoint?
1433 }
1434
1435 if (m_z0_supported)
1436 {
1437 char packet[64];
1438 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1439 assert (packet_len + 1 < sizeof(packet));
1440 StringExtractorGDBRemote response;
1441 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1442 {
1443 if (response.IsUnsupportedPacket())
1444 {
1445 // Disable z packet support and try again
1446 m_z0_supported = 0;
1447 return EnableBreakpoint (bp_site);
1448 }
1449 else if (response.IsOKPacket())
1450 {
1451 bp_site->SetEnabled(true);
1452 bp_site->SetType (BreakpointSite::eExternal);
1453 return error;
1454 }
1455 else
1456 {
1457 uint8_t error_byte = response.GetError();
1458 if (error_byte)
1459 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1460 }
1461 }
1462 }
1463 else
1464 {
1465 return EnableSoftwareBreakpoint (bp_site);
1466 }
1467 }
1468
1469 if (log)
1470 {
1471 const char *err_string = error.AsCString();
1472 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1473 bp_site->GetLoadAddress(),
1474 err_string ? err_string : "NULL");
1475 }
1476 // We shouldn't reach here on a successful breakpoint enable...
1477 if (error.Success())
1478 error.SetErrorToGenericError();
1479 return error;
1480}
1481
1482Error
1483ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1484{
1485 Error error;
1486 assert (bp_site != NULL);
1487 addr_t addr = bp_site->GetLoadAddress();
1488 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001489 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001490 if (log)
1491 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1492
1493 if (bp_site->IsEnabled())
1494 {
1495 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1496
1497 if (bp_site->IsHardware())
1498 {
1499 // TODO: disable hardware breakpoint...
1500 }
1501 else
1502 {
1503 if (m_z0_supported)
1504 {
1505 char packet[64];
1506 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1507 assert (packet_len + 1 < sizeof(packet));
1508 StringExtractorGDBRemote response;
1509 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1510 {
1511 if (response.IsUnsupportedPacket())
1512 {
1513 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1514 }
1515 else if (response.IsOKPacket())
1516 {
1517 if (log)
1518 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1519 bp_site->SetEnabled(false);
1520 return error;
1521 }
1522 else
1523 {
1524 uint8_t error_byte = response.GetError();
1525 if (error_byte)
1526 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1527 }
1528 }
1529 }
1530 else
1531 {
1532 return DisableSoftwareBreakpoint (bp_site);
1533 }
1534 }
1535 }
1536 else
1537 {
1538 if (log)
1539 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1540 return error;
1541 }
1542
1543 if (error.Success())
1544 error.SetErrorToGenericError();
1545 return error;
1546}
1547
1548Error
1549ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1550{
1551 Error error;
1552 if (wp)
1553 {
1554 user_id_t watchID = wp->GetID();
1555 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001556 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001557 if (log)
1558 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1559 if (wp->IsEnabled())
1560 {
1561 if (log)
1562 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1563 return error;
1564 }
1565 else
1566 {
1567 // Pass down an appropriate z/Z packet...
1568 error.SetErrorString("watchpoints not supported");
1569 }
1570 }
1571 else
1572 {
1573 error.SetErrorString("Watchpoint location argument was NULL.");
1574 }
1575 if (error.Success())
1576 error.SetErrorToGenericError();
1577 return error;
1578}
1579
1580Error
1581ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1582{
1583 Error error;
1584 if (wp)
1585 {
1586 user_id_t watchID = wp->GetID();
1587
Greg Claytone005f2c2010-11-06 01:53:30 +00001588 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001589
1590 addr_t addr = wp->GetLoadAddress();
1591 if (log)
1592 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1593
1594 if (wp->IsHardware())
1595 {
1596 // Pass down an appropriate z/Z packet...
1597 error.SetErrorString("watchpoints not supported");
1598 }
1599 // TODO: clear software watchpoints if we implement them
1600 }
1601 else
1602 {
1603 error.SetErrorString("Watchpoint location argument was NULL.");
1604 }
1605 if (error.Success())
1606 error.SetErrorToGenericError();
1607 return error;
1608}
1609
1610void
1611ProcessGDBRemote::Clear()
1612{
1613 m_flags = 0;
1614 m_thread_list.Clear();
1615 {
1616 Mutex::Locker locker(m_stdio_mutex);
1617 m_stdout_data.clear();
1618 }
1619 DestoryLibUnwindAddressSpace();
1620}
1621
1622Error
1623ProcessGDBRemote::DoSignal (int signo)
1624{
1625 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001626 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001627 if (log)
1628 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1629
1630 if (!m_gdb_comm.SendAsyncSignal (signo))
1631 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1632 return error;
1633}
1634
Caroline Tice861efb32010-11-16 05:07:41 +00001635//void
1636//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1637//{
1638// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1639// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1640//}
Chris Lattner24943d22010-06-08 16:52:24 +00001641
Caroline Tice861efb32010-11-16 05:07:41 +00001642//void
1643//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1644//{
1645// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1646// Mutex::Locker locker(m_stdio_mutex);
1647// m_stdout_data.append(s, len);
1648//
1649// // FIXME: Make a real data object for this and put it out.
1650// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1651//}
Chris Lattner24943d22010-06-08 16:52:24 +00001652
1653
1654Error
1655ProcessGDBRemote::StartDebugserverProcess
1656(
1657 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1658 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1659 char const *inferior_envp[], // Environment to pass along to the inferior program
1660 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001661 bool launch_process, // Set to true if we are going to be launching a the process
1662 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 +00001663 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1664 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Clayton23cf0c72010-11-08 04:29:11 +00001665 bool disable_aslr, // Disable ASLR
Chris Lattner24943d22010-06-08 16:52:24 +00001666 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1667)
1668{
1669 Error error;
1670 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1671 {
1672 // If we locate debugserver, keep that located version around
1673 static FileSpec g_debugserver_file_spec;
1674
1675 FileSpec debugserver_file_spec;
1676 char debugserver_path[PATH_MAX];
1677
1678 // Always check to see if we have an environment override for the path
1679 // to the debugserver to use and use it if we do.
1680 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1681 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001682 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001683 else
1684 debugserver_file_spec = g_debugserver_file_spec;
1685 bool debugserver_exists = debugserver_file_spec.Exists();
1686 if (!debugserver_exists)
1687 {
1688 // The debugserver binary is in the LLDB.framework/Resources
1689 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001690 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001691 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001692 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001693 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001694 if (debugserver_exists)
1695 {
1696 g_debugserver_file_spec = debugserver_file_spec;
1697 }
1698 else
1699 {
1700 g_debugserver_file_spec.Clear();
1701 debugserver_file_spec.Clear();
1702 }
Chris Lattner24943d22010-06-08 16:52:24 +00001703 }
1704 }
1705
1706 if (debugserver_exists)
1707 {
1708 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1709
1710 m_stdio_communication.Clear();
1711 posix_spawnattr_t attr;
1712
Greg Claytone005f2c2010-11-06 01:53:30 +00001713 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001714
1715 Error local_err; // Errors that don't affect the spawning.
1716 if (log)
1717 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1718 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1719 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001720 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001721 if (error.Fail())
1722 return error;;
1723
1724#if !defined (__arm__)
1725
Greg Clayton24b48ff2010-10-17 22:03:32 +00001726 // We don't need to do this for ARM, and we really shouldn't now
1727 // that we have multiple CPU subtypes and no posix_spawnattr call
1728 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001729 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001730 {
Greg Claytoncf015052010-06-11 03:25:34 +00001731 cpu_type_t cpu = inferior_arch.GetCPUType();
1732 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1733 {
1734 size_t ocount = 0;
1735 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1736 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001737 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 +00001738
Greg Claytoncf015052010-06-11 03:25:34 +00001739 if (error.Fail() != 0 || ocount != 1)
1740 return error;
1741 }
Chris Lattner24943d22010-06-08 16:52:24 +00001742 }
1743
1744#endif
1745
1746 Args debugserver_args;
1747 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001748
Chris Lattner24943d22010-06-08 16:52:24 +00001749 lldb_utility::PseudoTerminal pty;
Greg Clayton23cf0c72010-11-08 04:29:11 +00001750 if (launch_process && stdio_path == NULL && m_local_debugserver)
Chris Lattner24943d22010-06-08 16:52:24 +00001751 {
Chris Lattner24943d22010-06-08 16:52:24 +00001752 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001753 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001754 }
1755
1756 // Start args with "debugserver /file/path -r --"
1757 debugserver_args.AppendArgument(debugserver_path);
1758 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001759 // use native registers, not the GDB registers
1760 debugserver_args.AppendArgument("--native-regs");
1761 // make debugserver run in its own session so signals generated by
1762 // special terminal key sequences (^C) don't affect debugserver
1763 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001764
Greg Clayton452bf612010-08-31 18:35:14 +00001765 if (disable_aslr)
1766 debugserver_args.AppendArguments("--disable-aslr");
1767
Chris Lattner24943d22010-06-08 16:52:24 +00001768 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001769 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001770 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001771 debugserver_args.AppendArgument("--stdio-path");
1772 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001773 }
1774
1775 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1776 if (env_debugserver_log_file)
1777 {
1778 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1779 debugserver_args.AppendArgument(arg_cstr);
1780 }
1781
1782 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1783 if (env_debugserver_log_flags)
1784 {
1785 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1786 debugserver_args.AppendArgument(arg_cstr);
1787 }
1788// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1789// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1790
1791 // Now append the program arguments
1792 if (launch_process)
1793 {
1794 if (inferior_argv)
1795 {
1796 // Terminate the debugserver args so we can now append the inferior args
1797 debugserver_args.AppendArgument("--");
1798
1799 for (int i = 0; inferior_argv[i] != NULL; ++i)
1800 debugserver_args.AppendArgument (inferior_argv[i]);
1801 }
1802 else
1803 {
1804 // Will send environment entries with the 'QEnvironment:' packet
1805 // Will send arguments with the 'A' packet
1806 }
1807 }
1808 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1809 {
1810 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1811 debugserver_args.AppendArgument (arg_cstr);
1812 }
1813 else if (attach_name && attach_name[0])
1814 {
1815 if (wait_for_launch)
1816 debugserver_args.AppendArgument ("--waitfor");
1817 else
1818 debugserver_args.AppendArgument ("--attach");
1819 debugserver_args.AppendArgument (attach_name);
1820 }
1821
1822 Error file_actions_err;
1823 posix_spawn_file_actions_t file_actions;
1824#if DONT_CLOSE_DEBUGSERVER_STDIO
1825 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1826#else
1827 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1828 if (file_actions_err.Success())
1829 {
1830 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1831 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1832 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1833 }
1834#endif
1835
1836 if (log)
1837 {
1838 StreamString strm;
1839 debugserver_args.Dump (&strm);
1840 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1841 }
1842
1843 error.SetError(::posix_spawnp (&m_debugserver_pid,
1844 debugserver_path,
1845 file_actions_err.Success() ? &file_actions : NULL,
1846 &attr,
1847 debugserver_args.GetArgumentVector(),
1848 (char * const*)inferior_envp),
1849 eErrorTypePOSIX);
1850
Greg Claytone9d0df42010-07-02 01:29:13 +00001851
1852 ::posix_spawnattr_destroy (&attr);
1853
Chris Lattner24943d22010-06-08 16:52:24 +00001854 if (file_actions_err.Success())
1855 ::posix_spawn_file_actions_destroy (&file_actions);
1856
1857 // We have seen some cases where posix_spawnp was returning a valid
1858 // looking pid even when an error was returned, so clear it out
1859 if (error.Fail())
1860 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1861
1862 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001863 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 +00001864
Caroline Tice91a1dab2010-11-05 22:37:44 +00001865 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1866 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001867 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001868 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001869 }
Chris Lattner24943d22010-06-08 16:52:24 +00001870 }
1871 else
1872 {
1873 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1874 }
1875
1876 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1877 StartAsyncThread ();
1878 }
1879 return error;
1880}
1881
1882bool
1883ProcessGDBRemote::MonitorDebugserverProcess
1884(
1885 void *callback_baton,
1886 lldb::pid_t debugserver_pid,
1887 int signo, // Zero for no signal
1888 int exit_status // Exit value of process if signal is zero
1889)
1890{
1891 // We pass in the ProcessGDBRemote inferior process it and name it
1892 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1893 // pointer value itself, thus we need the double cast...
1894
1895 // "debugserver_pid" argument passed in is the process ID for
1896 // debugserver that we are tracking...
1897
Greg Clayton75ccf502010-08-21 02:22:51 +00001898 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1899
1900 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001901 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001902 // Sleep for a half a second to make sure our inferior process has
1903 // time to set its exit status before we set it incorrectly when
1904 // both the debugserver and the inferior process shut down.
1905 usleep (500000);
1906 // If our process hasn't yet exited, debugserver might have died.
1907 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001908 const StateType state = process->GetState();
1909
1910 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1911 state != eStateInvalid &&
1912 state != eStateUnloaded &&
1913 state != eStateExited &&
1914 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001915 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001916 char error_str[1024];
1917 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001918 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001919 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1920 if (signal_cstr)
1921 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001922 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001923 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001924 }
1925 else
1926 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001927 ::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 +00001928 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001929
1930 process->SetExitStatus (-1, error_str);
1931 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001932 // Debugserver has exited we need to let our ProcessGDBRemote
1933 // know that it no longer has a debugserver instance
1934 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1935 // We are returning true to this function below, so we can
1936 // forget about the monitor handle.
1937 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001938 }
1939 return true;
1940}
1941
1942void
1943ProcessGDBRemote::KillDebugserverProcess ()
1944{
1945 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1946 {
1947 ::kill (m_debugserver_pid, SIGINT);
1948 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1949 }
1950}
1951
1952void
1953ProcessGDBRemote::Initialize()
1954{
1955 static bool g_initialized = false;
1956
1957 if (g_initialized == false)
1958 {
1959 g_initialized = true;
1960 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1961 GetPluginDescriptionStatic(),
1962 CreateInstance);
1963
1964 Log::Callbacks log_callbacks = {
1965 ProcessGDBRemoteLog::DisableLog,
1966 ProcessGDBRemoteLog::EnableLog,
1967 ProcessGDBRemoteLog::ListLogCategories
1968 };
1969
1970 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1971 }
1972}
1973
1974bool
1975ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1976{
1977 if (m_curr_tid == tid)
1978 return true;
1979
1980 char packet[32];
1981 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1982 assert (packet_len + 1 < sizeof(packet));
1983 StringExtractorGDBRemote response;
1984 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1985 {
1986 if (response.IsOKPacket())
1987 {
1988 m_curr_tid = tid;
1989 return true;
1990 }
1991 }
1992 return false;
1993}
1994
1995bool
1996ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
1997{
1998 if (m_curr_tid_run == tid)
1999 return true;
2000
2001 char packet[32];
2002 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2003 assert (packet_len + 1 < sizeof(packet));
2004 StringExtractorGDBRemote response;
2005 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2006 {
2007 if (response.IsOKPacket())
2008 {
2009 m_curr_tid_run = tid;
2010 return true;
2011 }
2012 }
2013 return false;
2014}
2015
2016void
2017ProcessGDBRemote::ResetGDBRemoteState ()
2018{
2019 // Reset and GDB remote state
2020 m_curr_tid = LLDB_INVALID_THREAD_ID;
2021 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2022 m_z0_supported = 1;
2023}
2024
2025
2026bool
2027ProcessGDBRemote::StartAsyncThread ()
2028{
2029 ResetGDBRemoteState ();
2030
Greg Claytone005f2c2010-11-06 01:53:30 +00002031 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002032
2033 if (log)
2034 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2035
2036 // Create a thread that watches our internal state and controls which
2037 // events make it to clients (into the DCProcess event queue).
2038 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2039 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2040}
2041
2042void
2043ProcessGDBRemote::StopAsyncThread ()
2044{
Greg Claytone005f2c2010-11-06 01:53:30 +00002045 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002046
2047 if (log)
2048 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2049
2050 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2051
2052 // Stop the stdio thread
2053 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2054 {
2055 Host::ThreadJoin (m_async_thread, NULL, NULL);
2056 }
2057}
2058
2059
2060void *
2061ProcessGDBRemote::AsyncThread (void *arg)
2062{
2063 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2064
Greg Claytone005f2c2010-11-06 01:53:30 +00002065 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002066 if (log)
2067 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2068
2069 Listener listener ("ProcessGDBRemote::AsyncThread");
2070 EventSP event_sp;
2071 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2072 eBroadcastBitAsyncThreadShouldExit;
2073
2074 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2075 {
2076 bool done = false;
2077 while (!done)
2078 {
Caroline Tice926060e2010-10-29 21:48:37 +00002079 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002080 if (log)
2081 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2082 if (listener.WaitForEvent (NULL, event_sp))
2083 {
2084 const uint32_t event_type = event_sp->GetType();
2085 switch (event_type)
2086 {
2087 case eBroadcastBitAsyncContinue:
2088 {
2089 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2090
2091 if (continue_packet)
2092 {
2093 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2094 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002095 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002096 if (log)
2097 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2098
2099 process->SetPrivateState(eStateRunning);
2100 StringExtractorGDBRemote response;
2101 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2102
2103 switch (stop_state)
2104 {
2105 case eStateStopped:
2106 case eStateCrashed:
2107 case eStateSuspended:
2108 process->m_last_stop_packet = response;
2109 process->m_last_stop_packet.SetFilePos (0);
2110 process->SetPrivateState (stop_state);
2111 break;
2112
2113 case eStateExited:
2114 process->m_last_stop_packet = response;
2115 process->m_last_stop_packet.SetFilePos (0);
2116 response.SetFilePos(1);
2117 process->SetExitStatus(response.GetHexU8(), NULL);
2118 done = true;
2119 break;
2120
2121 case eStateInvalid:
2122 break;
2123
2124 default:
2125 process->SetPrivateState (stop_state);
2126 break;
2127 }
2128 }
2129 }
2130 break;
2131
2132 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002133 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002134 if (log)
2135 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2136 done = true;
2137 break;
2138
2139 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002140 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002141 if (log)
2142 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2143 done = true;
2144 break;
2145 }
2146 }
2147 else
2148 {
Caroline Tice926060e2010-10-29 21:48:37 +00002149 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002150 if (log)
2151 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2152 done = true;
2153 }
2154 }
2155 }
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) thread exiting...", __FUNCTION__, arg, process->GetID());
2160
2161 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2162 return NULL;
2163}
2164
2165lldb_private::unw_addr_space_t
2166ProcessGDBRemote::GetLibUnwindAddressSpace ()
2167{
2168 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002169
2170 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2171 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002172 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002173 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002174 target_type = UNW_TARGET_X86_64;
2175
2176 if (m_libunwind_addr_space)
2177 {
2178 if (m_libunwind_target_type != target_type)
2179 DestoryLibUnwindAddressSpace();
2180 else
2181 return m_libunwind_addr_space;
2182 }
2183 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2184 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2185 if (m_libunwind_addr_space)
2186 m_libunwind_target_type = target_type;
2187 else
2188 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2189 return m_libunwind_addr_space;
2190}
2191
2192void
2193ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2194{
2195 if (m_libunwind_addr_space)
2196 {
2197 unw_destroy_addr_space (m_libunwind_addr_space);
2198 m_libunwind_addr_space = NULL;
2199 }
2200 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2201}
2202
2203
2204const char *
2205ProcessGDBRemote::GetDispatchQueueNameForThread
2206(
2207 addr_t thread_dispatch_qaddr,
2208 std::string &dispatch_queue_name
2209)
2210{
2211 dispatch_queue_name.clear();
2212 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2213 {
2214 // Cache the dispatch_queue_offsets_addr value so we don't always have
2215 // to look it up
2216 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2217 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002218 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2219 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002220 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002221 if (module_sp)
2222 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2223
2224 if (dispatch_queue_offsets_symbol == NULL)
2225 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002226 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002227 if (module_sp)
2228 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2229 }
Chris Lattner24943d22010-06-08 16:52:24 +00002230 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002231 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002232
2233 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2234 return NULL;
2235 }
2236
2237 uint8_t memory_buffer[8];
2238 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2239
2240 // Excerpt from src/queue_private.h
2241 struct dispatch_queue_offsets_s
2242 {
2243 uint16_t dqo_version;
2244 uint16_t dqo_label;
2245 uint16_t dqo_label_size;
2246 } dispatch_queue_offsets;
2247
2248
2249 Error error;
2250 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2251 {
2252 uint32_t data_offset = 0;
2253 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2254 {
2255 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2256 {
2257 data_offset = 0;
2258 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2259 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2260 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2261 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2262 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2263 dispatch_queue_name.erase (bytes_read);
2264 }
2265 }
2266 }
2267 }
2268 if (dispatch_queue_name.empty())
2269 return NULL;
2270 return dispatch_queue_name.c_str();
2271}
2272
Jim Ingham7508e732010-08-09 23:31:02 +00002273uint32_t
2274ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2275{
2276 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2277 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2278 if (m_local_debugserver)
2279 {
2280 return Host::ListProcessesMatchingName (name, matches, pids);
2281 }
2282 else
2283 {
2284 // FIXME: Implement talking to the remote debugserver.
2285 return 0;
2286 }
2287
2288}