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