blob: e7a879bd5a5709857a5de4729136d3bb0299dc8d [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Chris Lattner24943d22010-06-08 16:52:24 +000013#include <sys/types.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <sys/stat.h>
Chris Lattner24943d22010-06-08 16:52:24 +000015
16// C++ Includes
17#include <algorithm>
18#include <map>
19
20// Other libraries and framework includes
21
22#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000023#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/ArchSpec.h"
25#include "lldb/Core/Debugger.h"
26#include "lldb/Core/ConnectionFileDescriptor.h"
27#include "lldb/Core/FileSpec.h"
28#include "lldb/Core/InputReader.h"
29#include "lldb/Core/Module.h"
30#include "lldb/Core/PluginManager.h"
31#include "lldb/Core/State.h"
32#include "lldb/Core/StreamString.h"
33#include "lldb/Core/Timer.h"
34#include "lldb/Host/TimeValue.h"
35#include "lldb/Symbol/ObjectFile.h"
36#include "lldb/Target/DynamicLoader.h"
37#include "lldb/Target/Target.h"
38#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000039#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
41// Project includes
42#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000043#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "GDBRemoteRegisterContext.h"
45#include "ProcessGDBRemote.h"
46#include "ProcessGDBRemoteLog.h"
47#include "ThreadGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000048#include "MacOSXLibunwindCallbacks.h"
Greg Clayton643ee732010-08-04 01:40:35 +000049#include "StopInfoMachException.h"
50
Chris Lattner24943d22010-06-08 16:52:24 +000051
Chris Lattner24943d22010-06-08 16:52:24 +000052
53#define DEBUGSERVER_BASENAME "debugserver"
54using namespace lldb;
55using namespace lldb_private;
56
57static inline uint16_t
58get_random_port ()
59{
60 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u;
61}
62
63
64const char *
65ProcessGDBRemote::GetPluginNameStatic()
66{
67 return "process.gdb-remote";
68}
69
70const char *
71ProcessGDBRemote::GetPluginDescriptionStatic()
72{
73 return "GDB Remote protocol based debugging plug-in.";
74}
75
76void
77ProcessGDBRemote::Terminate()
78{
79 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
80}
81
82
83Process*
84ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
85{
86 return new ProcessGDBRemote (target, listener);
87}
88
89bool
90ProcessGDBRemote::CanDebug(Target &target)
91{
92 // For now we are just making sure the file exists for a given module
93 ModuleSP exe_module_sp(target.GetExecutableModule());
94 if (exe_module_sp.get())
95 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +000096 // However, if there is no executable module, we return true since we might be preparing to attach.
97 return true;
Chris Lattner24943d22010-06-08 16:52:24 +000098}
99
100//----------------------------------------------------------------------
101// ProcessGDBRemote constructor
102//----------------------------------------------------------------------
103ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
104 Process (target, listener),
105 m_dynamic_loader_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000106 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000107 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000108 m_gdb_comm(),
109 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000110 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000111 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000112 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000113 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
114 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000115 m_curr_tid (LLDB_INVALID_THREAD_ID),
116 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000117 m_z0_supported (1),
118 m_continue_packet(),
119 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000120 m_packet_timeout (1),
121 m_max_memory_size (512),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_libunwind_target_type (UNW_TARGET_UNSPECIFIED),
123 m_libunwind_addr_space (NULL),
Jim Ingham7508e732010-08-09 23:31:02 +0000124 m_waiting_for_attach (false),
125 m_local_debugserver (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000126{
127}
128
129//----------------------------------------------------------------------
130// Destructor
131//----------------------------------------------------------------------
132ProcessGDBRemote::~ProcessGDBRemote()
133{
Greg Clayton75ccf502010-08-21 02:22:51 +0000134 if (m_debugserver_thread != LLDB_INVALID_HOST_THREAD)
135 {
136 Host::ThreadCancel (m_debugserver_thread, NULL);
137 thread_result_t thread_result;
138 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
139 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
140 }
Chris Lattner24943d22010-06-08 16:52:24 +0000141 // m_mach_process.UnregisterNotificationCallbacks (this);
142 Clear();
143}
144
145//----------------------------------------------------------------------
146// PluginInterface
147//----------------------------------------------------------------------
148const char *
149ProcessGDBRemote::GetPluginName()
150{
151 return "Process debugging plug-in that uses the GDB remote protocol";
152}
153
154const char *
155ProcessGDBRemote::GetShortPluginName()
156{
157 return GetPluginNameStatic();
158}
159
160uint32_t
161ProcessGDBRemote::GetPluginVersion()
162{
163 return 1;
164}
165
166void
167ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
168{
169 strm->Printf("TODO: fill this in\n");
170}
171
172Error
173ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
174{
175 Error error;
176 error.SetErrorString("No plug-in commands are currently supported.");
177 return error;
178}
179
180Log *
181ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
182{
183 return NULL;
184}
185
186void
187ProcessGDBRemote::BuildDynamicRegisterInfo ()
188{
189 char register_info_command[64];
190 m_register_info.Clear();
191 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
192 uint32_t reg_offset = 0;
193 uint32_t reg_num = 0;
194 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
195 {
196 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
197 StringExtractorGDBRemote response;
198 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
199 {
200 packet_type = response.GetType();
201 if (packet_type == StringExtractorGDBRemote::eResponse)
202 {
203 std::string name;
204 std::string value;
205 ConstString reg_name;
206 ConstString alt_name;
207 ConstString set_name;
208 RegisterInfo reg_info = { NULL, // Name
209 NULL, // Alt name
210 0, // byte size
211 reg_offset, // offset
212 eEncodingUint, // encoding
213 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000214 {
215 LLDB_INVALID_REGNUM, // GCC reg num
216 LLDB_INVALID_REGNUM, // DWARF reg num
217 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000218 reg_num, // GDB reg num
219 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000220 }
221 };
222
223 while (response.GetNameColonValue(name, value))
224 {
225 if (name.compare("name") == 0)
226 {
227 reg_name.SetCString(value.c_str());
228 }
229 else if (name.compare("alt-name") == 0)
230 {
231 alt_name.SetCString(value.c_str());
232 }
233 else if (name.compare("bitsize") == 0)
234 {
235 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
236 }
237 else if (name.compare("offset") == 0)
238 {
239 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000240 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000241 {
242 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000243 }
244 }
245 else if (name.compare("encoding") == 0)
246 {
247 if (value.compare("uint") == 0)
248 reg_info.encoding = eEncodingUint;
249 else if (value.compare("sint") == 0)
250 reg_info.encoding = eEncodingSint;
251 else if (value.compare("ieee754") == 0)
252 reg_info.encoding = eEncodingIEEE754;
253 else if (value.compare("vector") == 0)
254 reg_info.encoding = eEncodingVector;
255 }
256 else if (name.compare("format") == 0)
257 {
258 if (value.compare("binary") == 0)
259 reg_info.format = eFormatBinary;
260 else if (value.compare("decimal") == 0)
261 reg_info.format = eFormatDecimal;
262 else if (value.compare("hex") == 0)
263 reg_info.format = eFormatHex;
264 else if (value.compare("float") == 0)
265 reg_info.format = eFormatFloat;
266 else if (value.compare("vector-sint8") == 0)
267 reg_info.format = eFormatVectorOfSInt8;
268 else if (value.compare("vector-uint8") == 0)
269 reg_info.format = eFormatVectorOfUInt8;
270 else if (value.compare("vector-sint16") == 0)
271 reg_info.format = eFormatVectorOfSInt16;
272 else if (value.compare("vector-uint16") == 0)
273 reg_info.format = eFormatVectorOfUInt16;
274 else if (value.compare("vector-sint32") == 0)
275 reg_info.format = eFormatVectorOfSInt32;
276 else if (value.compare("vector-uint32") == 0)
277 reg_info.format = eFormatVectorOfUInt32;
278 else if (value.compare("vector-float32") == 0)
279 reg_info.format = eFormatVectorOfFloat32;
280 else if (value.compare("vector-uint128") == 0)
281 reg_info.format = eFormatVectorOfUInt128;
282 }
283 else if (name.compare("set") == 0)
284 {
285 set_name.SetCString(value.c_str());
286 }
287 else if (name.compare("gcc") == 0)
288 {
289 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
290 }
291 else if (name.compare("dwarf") == 0)
292 {
293 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
294 }
295 else if (name.compare("generic") == 0)
296 {
297 if (value.compare("pc") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
299 else if (value.compare("sp") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
301 else if (value.compare("fp") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
303 else if (value.compare("ra") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
305 else if (value.compare("flags") == 0)
306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
307 }
308 }
309
Jason Molenda53d96862010-06-11 23:44:18 +0000310 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000311 assert (reg_info.byte_size != 0);
312 reg_offset += reg_info.byte_size;
313 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
314 }
315 }
316 else
317 {
318 packet_type = StringExtractorGDBRemote::eError;
319 }
320 }
321
322 if (reg_num == 0)
323 {
324 // We didn't get anything. See if we are debugging ARM and fill with
325 // a hard coded register set until we can get an updated debugserver
326 // down on the devices.
327 ArchSpec arm_arch ("arm");
328 if (GetTarget().GetArchitecture() == arm_arch)
329 m_register_info.HardcodeARMRegisters();
330 }
331 m_register_info.Finalize ();
332}
333
334Error
335ProcessGDBRemote::WillLaunch (Module* module)
336{
337 return WillLaunchOrAttach ();
338}
339
340Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000341ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000342{
343 return WillLaunchOrAttach ();
344}
345
346Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000347ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000348{
349 return WillLaunchOrAttach ();
350}
351
352Error
353ProcessGDBRemote::WillLaunchOrAttach ()
354{
355 Error error;
356 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
357 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
358
359 if (m_dynamic_loader_ap.get() == NULL)
360 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
361 m_stdio_communication.Clear ();
362
363 return error;
364}
365
366//----------------------------------------------------------------------
367// Process Control
368//----------------------------------------------------------------------
369Error
370ProcessGDBRemote::DoLaunch
371(
372 Module* module,
373 char const *argv[],
374 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000375 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000376 const char *stdin_path,
377 const char *stdout_path,
378 const char *stderr_path
379)
380{
Greg Clayton4b407112010-09-30 21:49:03 +0000381 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000382 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
383 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
384 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000385
386 ObjectFile * object_file = module->GetObjectFile();
387 if (object_file)
388 {
389 ArchSpec inferior_arch(module->GetArchitecture());
390 char host_port[128];
391 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
392
Greg Clayton23cf0c72010-11-08 04:29:11 +0000393 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000394 bool start_debugserver_with_inferior_args = false;
395 if (start_debugserver_with_inferior_args)
396 {
397 // We want to launch debugserver with the inferior program and its
398 // arguments on the command line. We should only do this if we
399 // the GDB server we are talking to doesn't support the 'A' packet.
400 error = StartDebugserverProcess (host_port,
401 argv,
402 envp,
403 NULL, //stdin_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000404 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000405 LLDB_INVALID_PROCESS_ID,
406 NULL, false,
Benjamin Kramer2653be92010-09-03 18:20:07 +0000407 (launch_flags & eLaunchFlagDisableASLR) != 0,
Chris Lattner24943d22010-06-08 16:52:24 +0000408 inferior_arch);
409 if (error.Fail())
410 return error;
411
412 error = ConnectToDebugserver (host_port);
413 if (error.Success())
414 {
415 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
416 }
417 }
418 else
419 {
420 error = StartDebugserverProcess (host_port,
421 NULL,
422 NULL,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000423 NULL, //stdin_path
424 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000425 LLDB_INVALID_PROCESS_ID,
426 NULL, false,
Benjamin Kramer2653be92010-09-03 18:20:07 +0000427 (launch_flags & eLaunchFlagDisableASLR) != 0,
Chris Lattner24943d22010-06-08 16:52:24 +0000428 inferior_arch);
429 if (error.Fail())
430 return error;
431
432 error = ConnectToDebugserver (host_port);
433 if (error.Success())
434 {
435 // Send the environment and the program + arguments after we connect
436 if (envp)
437 {
438 const char *env_entry;
439 for (int i=0; (env_entry = envp[i]); ++i)
440 {
441 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
442 break;
443 }
444 }
445
Greg Clayton960d6a42010-08-03 00:35:52 +0000446 // FIXME: convert this to use the new set/show variables when they are available
447#if 0
448 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
449 {
450 const uint32_t attach_debugserver_secs = 10;
451 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
452 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
453 {
454 printf ("%i\n", attach_debugserver_secs - i);
455 sleep (1);
456 }
457 }
458#endif
459
Chris Lattner24943d22010-06-08 16:52:24 +0000460 const uint32_t arg_timeout_seconds = 10;
461 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
462 if (arg_packet_err == 0)
463 {
464 std::string error_str;
465 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
466 {
467 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
468 }
469 else
470 {
471 error.SetErrorString (error_str.c_str());
472 }
473 }
474 else
475 {
476 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
477 }
478
479 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
480 }
481 }
482
483 if (GetID() == LLDB_INVALID_PROCESS_ID)
484 {
485 KillDebugserverProcess ();
486 return error;
487 }
488
489 StringExtractorGDBRemote response;
490 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
491 SetPrivateState (SetThreadStopInfo (response));
492
493 }
494 else
495 {
496 // Set our user ID to an invalid process ID.
497 SetID(LLDB_INVALID_PROCESS_ID);
498 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
499 }
Chris Lattner24943d22010-06-08 16:52:24 +0000500 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000501
Chris Lattner24943d22010-06-08 16:52:24 +0000502}
503
504
505Error
506ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
507{
508 Error error;
509 // Sleep and wait a bit for debugserver to start to listen...
510 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
511 if (conn_ap.get())
512 {
513 std::string connect_url("connect://");
514 connect_url.append (host_port);
515 const uint32_t max_retry_count = 50;
516 uint32_t retry_count = 0;
517 while (!m_gdb_comm.IsConnected())
518 {
519 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
520 {
521 m_gdb_comm.SetConnection (conn_ap.release());
522 break;
523 }
524 retry_count++;
525
526 if (retry_count >= max_retry_count)
527 break;
528
529 usleep (100000);
530 }
531 }
532
533 if (!m_gdb_comm.IsConnected())
534 {
535 if (error.Success())
536 error.SetErrorString("not connected to remote gdb server");
537 return error;
538 }
539
540 m_gdb_comm.SetAckMode (true);
541 if (m_gdb_comm.StartReadThread(&error))
542 {
543 // Send an initial ack
544 m_gdb_comm.SendAck('+');
545
546 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000547 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
548 this,
549 m_debugserver_pid,
550 false);
551
Chris Lattner24943d22010-06-08 16:52:24 +0000552 StringExtractorGDBRemote response;
553 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
554 {
555 if (response.IsOKPacket())
556 m_gdb_comm.SetAckMode (false);
557 }
Chris Lattner24943d22010-06-08 16:52:24 +0000558 }
559 return error;
560}
561
562void
563ProcessGDBRemote::DidLaunchOrAttach ()
564{
565 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
566 if (GetID() == LLDB_INVALID_PROCESS_ID)
567 {
568 m_dynamic_loader_ap.reset();
569 }
570 else
571 {
572 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
573
Greg Clayton20d338f2010-11-18 05:57:03 +0000574 BuildDynamicRegisterInfo ();
575
576 m_byte_order = m_gdb_comm.GetByteOrder();
577
578 Module * exe_module = GetTarget().GetExecutableModule().get();
Chris Lattner24943d22010-06-08 16:52:24 +0000579 assert(exe_module);
580
Chris Lattner24943d22010-06-08 16:52:24 +0000581 ObjectFile *exe_objfile = exe_module->GetObjectFile();
582 assert(exe_objfile);
583
Chris Lattner24943d22010-06-08 16:52:24 +0000584 StreamString strm;
585
586 ArchSpec inferior_arch;
587 // See if the GDB server supports the qHostInfo information
588 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
589 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Clayton20d338f2010-11-18 05:57:03 +0000590 ArchSpec arch_spec (GetTarget().GetArchitecture());
Chris Lattner24943d22010-06-08 16:52:24 +0000591
Jim Ingham7508e732010-08-09 23:31:02 +0000592 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000593 {
594 // For ARM we can't trust the arch of the process as it could
595 // have an armv6 object file, but be running on armv7 kernel.
596 inferior_arch = m_gdb_comm.GetHostArchitecture();
597 }
598
599 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000600 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000601
602 if (vendor == NULL)
603 vendor = Host::GetVendorString().AsCString("apple");
604
605 if (os_type == NULL)
606 os_type = Host::GetOSString().AsCString("darwin");
607
608 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
609
610 std::transform (strm.GetString().begin(),
611 strm.GetString().end(),
612 strm.GetString().begin(),
613 ::tolower);
614
615 m_target_triple.SetCString(strm.GetString().c_str());
616 }
617}
618
619void
620ProcessGDBRemote::DidLaunch ()
621{
622 DidLaunchOrAttach ();
623 if (m_dynamic_loader_ap.get())
624 m_dynamic_loader_ap->DidLaunch();
625}
626
627Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000628ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000629{
630 Error error;
631 // Clear out and clean up from any current state
632 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000633 ArchSpec arch_spec = GetTarget().GetArchitecture();
634
Greg Claytone005f2c2010-11-06 01:53:30 +0000635 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000636
637
Chris Lattner24943d22010-06-08 16:52:24 +0000638 if (attach_pid != LLDB_INVALID_PROCESS_ID)
639 {
Chris Lattner24943d22010-06-08 16:52:24 +0000640 char host_port[128];
641 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000642 error = StartDebugserverProcess (host_port, // debugserver_url
643 NULL, // inferior_argv
644 NULL, // inferior_envp
645 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000646 false, // launch_process == false (we are attaching)
647 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
648 NULL, // Don't send any attach by process name option to debugserver
649 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Greg Clayton452bf612010-08-31 18:35:14 +0000650 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000651 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000652
653 if (error.Fail())
654 {
655 const char *error_string = error.AsCString();
656 if (error_string == NULL)
657 error_string = "unable to launch " DEBUGSERVER_BASENAME;
658
659 SetExitStatus (-1, error_string);
660 }
661 else
662 {
663 error = ConnectToDebugserver (host_port);
664 if (error.Success())
665 {
666 char packet[64];
667 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
668 StringExtractorGDBRemote response;
669 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
670 packet,
671 packet_len,
672 response);
673 switch (stop_state)
674 {
675 case eStateStopped:
676 case eStateCrashed:
677 case eStateSuspended:
678 SetID (attach_pid);
679 m_last_stop_packet = response;
680 m_last_stop_packet.SetFilePos (0);
681 SetPrivateState (stop_state);
682 break;
683
684 case eStateExited:
685 m_last_stop_packet = response;
686 m_last_stop_packet.SetFilePos (0);
687 response.SetFilePos(1);
688 SetExitStatus(response.GetHexU8(), NULL);
689 break;
690
691 default:
692 SetExitStatus(-1, "unable to attach to process");
693 break;
694 }
695
696 }
697 }
698 }
699
700 lldb::pid_t pid = GetID();
701 if (pid == LLDB_INVALID_PROCESS_ID)
702 {
703 KillDebugserverProcess();
704 }
705 return error;
706}
707
708size_t
709ProcessGDBRemote::AttachInputReaderCallback
710(
711 void *baton,
712 InputReader *reader,
713 lldb::InputReaderAction notification,
714 const char *bytes,
715 size_t bytes_len
716)
717{
718 if (notification == eInputReaderGotToken)
719 {
720 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
721 if (gdb_process->m_waiting_for_attach)
722 gdb_process->m_waiting_for_attach = false;
723 reader->SetIsDone(true);
724 return 1;
725 }
726 return 0;
727}
728
729Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000730ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000731{
732 Error error;
733 // Clear out and clean up from any current state
734 Clear();
735 // HACK: require arch be set correctly at the target level until we can
736 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000737
Greg Claytone005f2c2010-11-06 01:53:30 +0000738 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000739 if (process_name && process_name[0])
740 {
Chris Lattner24943d22010-06-08 16:52:24 +0000741 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000742 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000743 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000744 error = StartDebugserverProcess (host_port, // debugserver_url
745 NULL, // inferior_argv
746 NULL, // inferior_envp
747 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000748 false, // launch_process == false (we are attaching)
749 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
750 NULL, // Don't send any attach by process name option to debugserver
751 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Greg Clayton452bf612010-08-31 18:35:14 +0000752 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000753 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000754 if (error.Fail())
755 {
756 const char *error_string = error.AsCString();
757 if (error_string == NULL)
758 error_string = "unable to launch " DEBUGSERVER_BASENAME;
759
760 SetExitStatus (-1, error_string);
761 }
762 else
763 {
764 error = ConnectToDebugserver (host_port);
765 if (error.Success())
766 {
767 StreamString packet;
768
Chris Lattner24943d22010-06-08 16:52:24 +0000769 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000770 packet.PutCString("vAttachWait");
771 else
772 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000773 packet.PutChar(';');
774 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
775 StringExtractorGDBRemote response;
776 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
777 packet.GetData(),
778 packet.GetSize(),
779 response);
780 switch (stop_state)
781 {
782 case eStateStopped:
783 case eStateCrashed:
784 case eStateSuspended:
785 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
786 m_last_stop_packet = response;
787 m_last_stop_packet.SetFilePos (0);
788 SetPrivateState (stop_state);
789 break;
790
791 case eStateExited:
792 m_last_stop_packet = response;
793 m_last_stop_packet.SetFilePos (0);
794 response.SetFilePos(1);
795 SetExitStatus(response.GetHexU8(), NULL);
796 break;
797
798 default:
799 SetExitStatus(-1, "unable to attach to process");
800 break;
801 }
802 }
803 }
804 }
805
806 lldb::pid_t pid = GetID();
807 if (pid == LLDB_INVALID_PROCESS_ID)
808 {
809 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000810
811 if (error.Success())
812 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000813 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000814
Chris Lattner24943d22010-06-08 16:52:24 +0000815 return error;
816}
817
818//
819// if (wait_for_launch)
820// {
821// InputReaderSP reader_sp (new InputReader());
822// StreamString instructions;
823// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
824// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
825// this, // baton
826// eInputReaderGranularityByte,
827// NULL, // End token
828// false);
829//
830// StringExtractorGDBRemote response;
831// m_waiting_for_attach = true;
832// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
833// while (m_waiting_for_attach)
834// {
835// // Wait for one second for the stop reply packet
836// if (m_gdb_comm.WaitForPacket(response, 1))
837// {
838// // Got some sort of packet, see if it is the stop reply packet?
839// char ch = response.GetChar(0);
840// if (ch == 'T')
841// {
842// m_waiting_for_attach = false;
843// }
844// }
845// else
846// {
847// // Put a period character every second
848// fputc('.', reader_out_fh);
849// }
850// }
851// }
852// }
853// return GetID();
854//}
855
856void
857ProcessGDBRemote::DidAttach ()
858{
Chris Lattner24943d22010-06-08 16:52:24 +0000859 if (m_dynamic_loader_ap.get())
860 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000861 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000862}
863
864Error
865ProcessGDBRemote::WillResume ()
866{
867 m_continue_packet.Clear();
868 // Start the continue packet we will use to run the target. Each thread
869 // will append what it is supposed to be doing to this packet when the
870 // ThreadList::WillResume() is called. If a thread it supposed
871 // to stay stopped, then don't append anything to this string.
872 m_continue_packet.Printf("vCont");
873 return Error();
874}
875
876Error
877ProcessGDBRemote::DoResume ()
878{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000879 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000880 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
881 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
Jim Ingham3ae449a2010-11-17 02:32:00 +0000882 const uint32_t timedout_sec = 1;
Greg Claytonc0da6152010-12-03 00:27:48 +0000883 if (m_gdb_comm.WaitForIsRunning (timedout_sec) == false)
Jim Ingham3ae449a2010-11-17 02:32:00 +0000884 error.SetErrorString("Resume timed out.");
Jim Ingham3ae449a2010-11-17 02:32:00 +0000885 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000886}
887
888size_t
889ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
890{
891 const uint8_t *trap_opcode = NULL;
892 uint32_t trap_opcode_size = 0;
893
894 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
895 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
896 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
897 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
898
Jim Ingham7508e732010-08-09 23:31:02 +0000899 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000900 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000901 {
Greg Claytoncf015052010-06-11 03:25:34 +0000902 case ArchSpec::eCPU_i386:
903 case ArchSpec::eCPU_x86_64:
904 trap_opcode = g_i386_breakpoint_opcode;
905 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
906 break;
907
908 case ArchSpec::eCPU_arm:
909 // TODO: fill this in for ARM. We need to dig up the symbol for
910 // the address in the breakpoint locaiton and figure out if it is
911 // an ARM or Thumb breakpoint.
912 trap_opcode = g_arm_breakpoint_opcode;
913 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
914 break;
915
916 case ArchSpec::eCPU_ppc:
917 case ArchSpec::eCPU_ppc64:
918 trap_opcode = g_ppc_breakpoint_opcode;
919 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
920 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000921
Greg Claytoncf015052010-06-11 03:25:34 +0000922 default:
923 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
924 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000925 }
926
927 if (trap_opcode && trap_opcode_size)
928 {
929 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
930 return trap_opcode_size;
931 }
932 return 0;
933}
934
935uint32_t
936ProcessGDBRemote::UpdateThreadListIfNeeded ()
937{
938 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000939 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000940 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000941 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
942
Greg Clayton5205f0b2010-09-03 17:10:42 +0000943 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000944 const uint32_t stop_id = GetStopID();
945 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
946 {
947 // Update the thread list's stop id immediately so we don't recurse into this function.
948 ThreadList curr_thread_list (this);
949 curr_thread_list.SetStopID(stop_id);
950
951 Error err;
952 StringExtractorGDBRemote response;
953 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
954 response.IsNormalPacket();
955 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
956 {
957 char ch = response.GetChar();
958 if (ch == 'l')
959 break;
960 if (ch == 'm')
961 {
962 do
963 {
964 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
965
966 if (tid != LLDB_INVALID_THREAD_ID)
967 {
968 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
969 if (thread_sp)
970 thread_sp->GetRegisterContext()->Invalidate();
971 else
972 thread_sp.reset (new ThreadGDBRemote (*this, tid));
973 curr_thread_list.AddThread(thread_sp);
974 }
975
976 ch = response.GetChar();
977 } while (ch == ',');
978 }
979 }
980
981 m_thread_list = curr_thread_list;
982
983 SetThreadStopInfo (m_last_stop_packet);
984 }
985 return GetThreadList().GetSize(false);
986}
987
988
989StateType
990ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
991{
992 const char stop_type = stop_packet.GetChar();
993 switch (stop_type)
994 {
995 case 'T':
996 case 'S':
997 {
998 // Stop with signal and thread info
999 const uint8_t signo = stop_packet.GetHexU8();
1000 std::string name;
1001 std::string value;
1002 std::string thread_name;
1003 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001004 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001005 uint32_t tid = LLDB_INVALID_THREAD_ID;
1006 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1007 uint32_t exc_data_count = 0;
1008 while (stop_packet.GetNameColonValue(name, value))
1009 {
1010 if (name.compare("metype") == 0)
1011 {
1012 // exception type in big endian hex
1013 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1014 }
1015 else if (name.compare("mecount") == 0)
1016 {
1017 // exception count in big endian hex
1018 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1019 }
1020 else if (name.compare("medata") == 0)
1021 {
1022 // exception data in big endian hex
1023 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1024 }
1025 else if (name.compare("thread") == 0)
1026 {
1027 // thread in big endian hex
1028 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1029 }
1030 else if (name.compare("name") == 0)
1031 {
1032 thread_name.swap (value);
1033 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001034 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001035 {
1036 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1037 }
1038 }
1039 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1040
1041 if (thread_sp)
1042 {
1043 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1044
1045 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1046 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001047 if (exc_type != 0)
1048 {
Greg Clayton643ee732010-08-04 01:40:35 +00001049 const size_t exc_data_count = exc_data.size();
1050
1051 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1052 exc_type,
1053 exc_data_count,
1054 exc_data_count >= 1 ? exc_data[0] : 0,
1055 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001056 }
1057 else if (signo)
1058 {
Greg Clayton643ee732010-08-04 01:40:35 +00001059 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001060 }
1061 else
1062 {
Greg Clayton643ee732010-08-04 01:40:35 +00001063 StopInfoSP invalid_stop_info_sp;
1064 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001065 }
1066 }
1067 return eStateStopped;
1068 }
1069 break;
1070
1071 case 'W':
1072 // process exited
1073 return eStateExited;
1074
1075 default:
1076 break;
1077 }
1078 return eStateInvalid;
1079}
1080
1081void
1082ProcessGDBRemote::RefreshStateAfterStop ()
1083{
Jim Ingham7508e732010-08-09 23:31:02 +00001084 // FIXME - add a variable to tell that we're in the middle of attaching if we
1085 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001086 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001087// if (!GetTarget().GetArchitecture().IsValid())
1088// {
1089// Module *exe_module = GetTarget().GetExecutableModule().get();
1090// if (exe_module)
1091// m_arch_spec = exe_module->GetArchitecture();
1092// }
1093
Chris Lattner24943d22010-06-08 16:52:24 +00001094 // Let all threads recover from stopping and do any clean up based
1095 // on the previous thread state (if any).
1096 m_thread_list.RefreshStateAfterStop();
1097
1098 // Discover new threads:
1099 UpdateThreadListIfNeeded ();
1100}
1101
1102Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001103ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001104{
1105 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001106
Chris Lattner24943d22010-06-08 16:52:24 +00001107 if (m_gdb_comm.IsRunning())
1108 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001109 caused_stop = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001110 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001111 Mutex::Locker locker;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001112
Greg Clayton20d338f2010-11-18 05:57:03 +00001113 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001114 {
1115 if (timed_out)
1116 error.SetErrorString("timed out sending interrupt packet");
1117 else
1118 error.SetErrorString("unknown error sending interrupt packet");
1119 }
1120 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001121 else
1122 {
1123 caused_stop = false;
1124 }
1125
Chris Lattner24943d22010-06-08 16:52:24 +00001126 return error;
1127}
1128
1129Error
1130ProcessGDBRemote::WillDetach ()
1131{
1132 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001133
Greg Clayton4fb400f2010-09-27 21:07:38 +00001134 if (m_gdb_comm.IsRunning())
1135 {
1136 bool timed_out = false;
1137 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001138 PausePrivateStateThread();
1139 m_thread_list.DiscardThreadPlans();
1140 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001141 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1142 {
1143 if (timed_out)
1144 error.SetErrorString("timed out sending interrupt packet");
1145 else
1146 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001147 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001148 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001149 TimeValue timeout_time;
1150 timeout_time = TimeValue::Now();
1151 timeout_time.OffsetWithSeconds(2);
1152
1153 EventSP event_sp;
1154 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1155 if (state != eStateStopped)
1156 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001157 }
Chris Lattner24943d22010-06-08 16:52:24 +00001158 return error;
1159}
1160
Greg Clayton4fb400f2010-09-27 21:07:38 +00001161Error
1162ProcessGDBRemote::DoDetach()
1163{
1164 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001165 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001166 if (log)
1167 log->Printf ("ProcessGDBRemote::DoDetach()");
1168
1169 DisableAllBreakpointSites ();
1170
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001171 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001172
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001173 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1174 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001175 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001176 if (response_size)
1177 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1178 else
1179 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001180 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001181 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001182 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001183
Greg Clayton4fb400f2010-09-27 21:07:38 +00001184 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001185 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001186
1187 SetPrivateState (eStateDetached);
1188 ResumePrivateStateThread();
1189
1190 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001191 return error;
1192}
Chris Lattner24943d22010-06-08 16:52:24 +00001193
1194Error
1195ProcessGDBRemote::DoDestroy ()
1196{
1197 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001198 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001199 if (log)
1200 log->Printf ("ProcessGDBRemote::DoDestroy()");
1201
1202 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001203 Mutex::Locker locker;
1204 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001205 DisableAllBreakpointSites ();
1206 SetExitStatus(-1, "process killed");
1207
1208 StringExtractorGDBRemote response;
1209 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1210 {
Caroline Tice926060e2010-10-29 21:48:37 +00001211 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001212 if (log)
1213 {
1214 if (response.IsOKPacket())
1215 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1216 else
1217 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1218 }
1219 }
1220
1221 StopAsyncThread ();
1222 m_gdb_comm.StopReadThread();
1223 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001224 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001225 return error;
1226}
1227
Chris Lattner24943d22010-06-08 16:52:24 +00001228//------------------------------------------------------------------
1229// Process Queries
1230//------------------------------------------------------------------
1231
1232bool
1233ProcessGDBRemote::IsAlive ()
1234{
1235 return m_gdb_comm.IsConnected();
1236}
1237
1238addr_t
1239ProcessGDBRemote::GetImageInfoAddress()
1240{
1241 if (!m_gdb_comm.IsRunning())
1242 {
1243 StringExtractorGDBRemote response;
1244 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1245 {
1246 if (response.IsNormalPacket())
1247 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1248 }
1249 }
1250 return LLDB_INVALID_ADDRESS;
1251}
1252
1253DynamicLoader *
1254ProcessGDBRemote::GetDynamicLoader()
1255{
1256 return m_dynamic_loader_ap.get();
1257}
1258
1259//------------------------------------------------------------------
1260// Process Memory
1261//------------------------------------------------------------------
1262size_t
1263ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1264{
1265 if (size > m_max_memory_size)
1266 {
1267 // Keep memory read sizes down to a sane limit. This function will be
1268 // called multiple times in order to complete the task by
1269 // lldb_private::Process so it is ok to do this.
1270 size = m_max_memory_size;
1271 }
1272
1273 char packet[64];
1274 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1275 assert (packet_len + 1 < sizeof(packet));
1276 StringExtractorGDBRemote response;
1277 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1278 {
1279 if (response.IsNormalPacket())
1280 {
1281 error.Clear();
1282 return response.GetHexBytes(buf, size, '\xdd');
1283 }
1284 else if (response.IsErrorPacket())
1285 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1286 else if (response.IsUnsupportedPacket())
1287 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1288 else
1289 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1290 }
1291 else
1292 {
1293 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1294 }
1295 return 0;
1296}
1297
1298size_t
1299ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1300{
1301 StreamString packet;
1302 packet.Printf("M%llx,%zx:", addr, size);
1303 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1304 StringExtractorGDBRemote response;
1305 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1306 {
1307 if (response.IsOKPacket())
1308 {
1309 error.Clear();
1310 return size;
1311 }
1312 else if (response.IsErrorPacket())
1313 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1314 else if (response.IsUnsupportedPacket())
1315 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1316 else
1317 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1318 }
1319 else
1320 {
1321 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1322 }
1323 return 0;
1324}
1325
1326lldb::addr_t
1327ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1328{
1329 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1330 if (allocated_addr == LLDB_INVALID_ADDRESS)
1331 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1332 else
1333 error.Clear();
1334 return allocated_addr;
1335}
1336
1337Error
1338ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1339{
1340 Error error;
1341 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1342 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1343 return error;
1344}
1345
1346
1347//------------------------------------------------------------------
1348// Process STDIO
1349//------------------------------------------------------------------
1350
1351size_t
1352ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1353{
1354 Mutex::Locker locker(m_stdio_mutex);
1355 size_t bytes_available = m_stdout_data.size();
1356 if (bytes_available > 0)
1357 {
1358 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1359 if (bytes_available > buf_size)
1360 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001361 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001362 m_stdout_data.erase(0, buf_size);
1363 bytes_available = buf_size;
1364 }
1365 else
1366 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001367 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001368 m_stdout_data.clear();
1369
1370 //ResetEventBits(eBroadcastBitSTDOUT);
1371 }
1372 }
1373 return bytes_available;
1374}
1375
1376size_t
1377ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1378{
1379 // Can we get STDERR through the remote protocol?
1380 return 0;
1381}
1382
1383size_t
1384ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1385{
1386 if (m_stdio_communication.IsConnected())
1387 {
1388 ConnectionStatus status;
1389 m_stdio_communication.Write(src, src_len, status, NULL);
1390 }
1391 return 0;
1392}
1393
1394Error
1395ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1396{
1397 Error error;
1398 assert (bp_site != NULL);
1399
Greg Claytone005f2c2010-11-06 01:53:30 +00001400 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001401 user_id_t site_id = bp_site->GetID();
1402 const addr_t addr = bp_site->GetLoadAddress();
1403 if (log)
1404 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1405
1406 if (bp_site->IsEnabled())
1407 {
1408 if (log)
1409 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1410 return error;
1411 }
1412 else
1413 {
1414 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1415
1416 if (bp_site->HardwarePreferred())
1417 {
1418 // Try and set hardware breakpoint, and if that fails, fall through
1419 // and set a software breakpoint?
1420 }
1421
1422 if (m_z0_supported)
1423 {
1424 char packet[64];
1425 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1426 assert (packet_len + 1 < sizeof(packet));
1427 StringExtractorGDBRemote response;
1428 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1429 {
1430 if (response.IsUnsupportedPacket())
1431 {
1432 // Disable z packet support and try again
1433 m_z0_supported = 0;
1434 return EnableBreakpoint (bp_site);
1435 }
1436 else if (response.IsOKPacket())
1437 {
1438 bp_site->SetEnabled(true);
1439 bp_site->SetType (BreakpointSite::eExternal);
1440 return error;
1441 }
1442 else
1443 {
1444 uint8_t error_byte = response.GetError();
1445 if (error_byte)
1446 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1447 }
1448 }
1449 }
1450 else
1451 {
1452 return EnableSoftwareBreakpoint (bp_site);
1453 }
1454 }
1455
1456 if (log)
1457 {
1458 const char *err_string = error.AsCString();
1459 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1460 bp_site->GetLoadAddress(),
1461 err_string ? err_string : "NULL");
1462 }
1463 // We shouldn't reach here on a successful breakpoint enable...
1464 if (error.Success())
1465 error.SetErrorToGenericError();
1466 return error;
1467}
1468
1469Error
1470ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1471{
1472 Error error;
1473 assert (bp_site != NULL);
1474 addr_t addr = bp_site->GetLoadAddress();
1475 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001476 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001477 if (log)
1478 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1479
1480 if (bp_site->IsEnabled())
1481 {
1482 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1483
1484 if (bp_site->IsHardware())
1485 {
1486 // TODO: disable hardware breakpoint...
1487 }
1488 else
1489 {
1490 if (m_z0_supported)
1491 {
1492 char packet[64];
1493 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1494 assert (packet_len + 1 < sizeof(packet));
1495 StringExtractorGDBRemote response;
1496 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1497 {
1498 if (response.IsUnsupportedPacket())
1499 {
1500 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1501 }
1502 else if (response.IsOKPacket())
1503 {
1504 if (log)
1505 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1506 bp_site->SetEnabled(false);
1507 return error;
1508 }
1509 else
1510 {
1511 uint8_t error_byte = response.GetError();
1512 if (error_byte)
1513 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1514 }
1515 }
1516 }
1517 else
1518 {
1519 return DisableSoftwareBreakpoint (bp_site);
1520 }
1521 }
1522 }
1523 else
1524 {
1525 if (log)
1526 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1527 return error;
1528 }
1529
1530 if (error.Success())
1531 error.SetErrorToGenericError();
1532 return error;
1533}
1534
1535Error
1536ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1537{
1538 Error error;
1539 if (wp)
1540 {
1541 user_id_t watchID = wp->GetID();
1542 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001543 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001544 if (log)
1545 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1546 if (wp->IsEnabled())
1547 {
1548 if (log)
1549 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1550 return error;
1551 }
1552 else
1553 {
1554 // Pass down an appropriate z/Z packet...
1555 error.SetErrorString("watchpoints not supported");
1556 }
1557 }
1558 else
1559 {
1560 error.SetErrorString("Watchpoint location argument was NULL.");
1561 }
1562 if (error.Success())
1563 error.SetErrorToGenericError();
1564 return error;
1565}
1566
1567Error
1568ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1569{
1570 Error error;
1571 if (wp)
1572 {
1573 user_id_t watchID = wp->GetID();
1574
Greg Claytone005f2c2010-11-06 01:53:30 +00001575 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001576
1577 addr_t addr = wp->GetLoadAddress();
1578 if (log)
1579 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1580
1581 if (wp->IsHardware())
1582 {
1583 // Pass down an appropriate z/Z packet...
1584 error.SetErrorString("watchpoints not supported");
1585 }
1586 // TODO: clear software watchpoints if we implement them
1587 }
1588 else
1589 {
1590 error.SetErrorString("Watchpoint location argument was NULL.");
1591 }
1592 if (error.Success())
1593 error.SetErrorToGenericError();
1594 return error;
1595}
1596
1597void
1598ProcessGDBRemote::Clear()
1599{
1600 m_flags = 0;
1601 m_thread_list.Clear();
1602 {
1603 Mutex::Locker locker(m_stdio_mutex);
1604 m_stdout_data.clear();
1605 }
1606 DestoryLibUnwindAddressSpace();
1607}
1608
1609Error
1610ProcessGDBRemote::DoSignal (int signo)
1611{
1612 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001613 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001614 if (log)
1615 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1616
1617 if (!m_gdb_comm.SendAsyncSignal (signo))
1618 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1619 return error;
1620}
1621
Caroline Tice861efb32010-11-16 05:07:41 +00001622//void
1623//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1624//{
1625// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1626// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1627//}
Chris Lattner24943d22010-06-08 16:52:24 +00001628
Caroline Tice861efb32010-11-16 05:07:41 +00001629//void
1630//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1631//{
1632// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1633// Mutex::Locker locker(m_stdio_mutex);
1634// m_stdout_data.append(s, len);
1635//
1636// // FIXME: Make a real data object for this and put it out.
1637// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1638//}
Chris Lattner24943d22010-06-08 16:52:24 +00001639
1640
1641Error
1642ProcessGDBRemote::StartDebugserverProcess
1643(
1644 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1645 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1646 char const *inferior_envp[], // Environment to pass along to the inferior program
1647 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001648 bool launch_process, // Set to true if we are going to be launching a the process
1649 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 +00001650 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1651 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Clayton23cf0c72010-11-08 04:29:11 +00001652 bool disable_aslr, // Disable ASLR
Chris Lattner24943d22010-06-08 16:52:24 +00001653 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1654)
1655{
1656 Error error;
1657 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1658 {
1659 // If we locate debugserver, keep that located version around
1660 static FileSpec g_debugserver_file_spec;
1661
1662 FileSpec debugserver_file_spec;
1663 char debugserver_path[PATH_MAX];
1664
1665 // Always check to see if we have an environment override for the path
1666 // to the debugserver to use and use it if we do.
1667 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1668 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001669 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001670 else
1671 debugserver_file_spec = g_debugserver_file_spec;
1672 bool debugserver_exists = debugserver_file_spec.Exists();
1673 if (!debugserver_exists)
1674 {
1675 // The debugserver binary is in the LLDB.framework/Resources
1676 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001677 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001678 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001679 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001680 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001681 if (debugserver_exists)
1682 {
1683 g_debugserver_file_spec = debugserver_file_spec;
1684 }
1685 else
1686 {
1687 g_debugserver_file_spec.Clear();
1688 debugserver_file_spec.Clear();
1689 }
Chris Lattner24943d22010-06-08 16:52:24 +00001690 }
1691 }
1692
1693 if (debugserver_exists)
1694 {
1695 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1696
1697 m_stdio_communication.Clear();
1698 posix_spawnattr_t attr;
1699
Greg Claytone005f2c2010-11-06 01:53:30 +00001700 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001701
1702 Error local_err; // Errors that don't affect the spawning.
1703 if (log)
1704 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1705 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1706 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001707 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001708 if (error.Fail())
1709 return error;;
1710
1711#if !defined (__arm__)
1712
Greg Clayton24b48ff2010-10-17 22:03:32 +00001713 // We don't need to do this for ARM, and we really shouldn't now
1714 // that we have multiple CPU subtypes and no posix_spawnattr call
1715 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001716 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001717 {
Greg Claytoncf015052010-06-11 03:25:34 +00001718 cpu_type_t cpu = inferior_arch.GetCPUType();
1719 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1720 {
1721 size_t ocount = 0;
1722 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1723 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001724 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 +00001725
Greg Claytoncf015052010-06-11 03:25:34 +00001726 if (error.Fail() != 0 || ocount != 1)
1727 return error;
1728 }
Chris Lattner24943d22010-06-08 16:52:24 +00001729 }
1730
1731#endif
1732
1733 Args debugserver_args;
1734 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001735
Chris Lattner24943d22010-06-08 16:52:24 +00001736 lldb_utility::PseudoTerminal pty;
Greg Clayton23cf0c72010-11-08 04:29:11 +00001737 if (launch_process && stdio_path == NULL && m_local_debugserver)
Chris Lattner24943d22010-06-08 16:52:24 +00001738 {
Chris Lattner24943d22010-06-08 16:52:24 +00001739 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001740 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001741 }
1742
1743 // Start args with "debugserver /file/path -r --"
1744 debugserver_args.AppendArgument(debugserver_path);
1745 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001746 // use native registers, not the GDB registers
1747 debugserver_args.AppendArgument("--native-regs");
1748 // make debugserver run in its own session so signals generated by
1749 // special terminal key sequences (^C) don't affect debugserver
1750 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001751
Greg Clayton452bf612010-08-31 18:35:14 +00001752 if (disable_aslr)
1753 debugserver_args.AppendArguments("--disable-aslr");
1754
Chris Lattner24943d22010-06-08 16:52:24 +00001755 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001756 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001757 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001758 debugserver_args.AppendArgument("--stdio-path");
1759 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001760 }
1761
1762 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1763 if (env_debugserver_log_file)
1764 {
1765 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1766 debugserver_args.AppendArgument(arg_cstr);
1767 }
1768
1769 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1770 if (env_debugserver_log_flags)
1771 {
1772 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1773 debugserver_args.AppendArgument(arg_cstr);
1774 }
1775// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1776// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1777
1778 // Now append the program arguments
1779 if (launch_process)
1780 {
1781 if (inferior_argv)
1782 {
1783 // Terminate the debugserver args so we can now append the inferior args
1784 debugserver_args.AppendArgument("--");
1785
1786 for (int i = 0; inferior_argv[i] != NULL; ++i)
1787 debugserver_args.AppendArgument (inferior_argv[i]);
1788 }
1789 else
1790 {
1791 // Will send environment entries with the 'QEnvironment:' packet
1792 // Will send arguments with the 'A' packet
1793 }
1794 }
1795 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1796 {
1797 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1798 debugserver_args.AppendArgument (arg_cstr);
1799 }
1800 else if (attach_name && attach_name[0])
1801 {
1802 if (wait_for_launch)
1803 debugserver_args.AppendArgument ("--waitfor");
1804 else
1805 debugserver_args.AppendArgument ("--attach");
1806 debugserver_args.AppendArgument (attach_name);
1807 }
1808
1809 Error file_actions_err;
1810 posix_spawn_file_actions_t file_actions;
1811#if DONT_CLOSE_DEBUGSERVER_STDIO
1812 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1813#else
1814 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1815 if (file_actions_err.Success())
1816 {
1817 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1818 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1819 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1820 }
1821#endif
1822
1823 if (log)
1824 {
1825 StreamString strm;
1826 debugserver_args.Dump (&strm);
1827 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1828 }
1829
1830 error.SetError(::posix_spawnp (&m_debugserver_pid,
1831 debugserver_path,
1832 file_actions_err.Success() ? &file_actions : NULL,
1833 &attr,
1834 debugserver_args.GetArgumentVector(),
1835 (char * const*)inferior_envp),
1836 eErrorTypePOSIX);
1837
Greg Claytone9d0df42010-07-02 01:29:13 +00001838
1839 ::posix_spawnattr_destroy (&attr);
1840
Chris Lattner24943d22010-06-08 16:52:24 +00001841 if (file_actions_err.Success())
1842 ::posix_spawn_file_actions_destroy (&file_actions);
1843
1844 // We have seen some cases where posix_spawnp was returning a valid
1845 // looking pid even when an error was returned, so clear it out
1846 if (error.Fail())
1847 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1848
1849 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001850 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 +00001851
Caroline Tice91a1dab2010-11-05 22:37:44 +00001852 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1853 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001854 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001855 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001856 }
Chris Lattner24943d22010-06-08 16:52:24 +00001857 }
1858 else
1859 {
1860 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1861 }
1862
1863 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1864 StartAsyncThread ();
1865 }
1866 return error;
1867}
1868
1869bool
1870ProcessGDBRemote::MonitorDebugserverProcess
1871(
1872 void *callback_baton,
1873 lldb::pid_t debugserver_pid,
1874 int signo, // Zero for no signal
1875 int exit_status // Exit value of process if signal is zero
1876)
1877{
1878 // We pass in the ProcessGDBRemote inferior process it and name it
1879 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1880 // pointer value itself, thus we need the double cast...
1881
1882 // "debugserver_pid" argument passed in is the process ID for
1883 // debugserver that we are tracking...
1884
Greg Clayton75ccf502010-08-21 02:22:51 +00001885 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1886
1887 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001888 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001889 // Sleep for a half a second to make sure our inferior process has
1890 // time to set its exit status before we set it incorrectly when
1891 // both the debugserver and the inferior process shut down.
1892 usleep (500000);
1893 // If our process hasn't yet exited, debugserver might have died.
1894 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001895 const StateType state = process->GetState();
1896
1897 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1898 state != eStateInvalid &&
1899 state != eStateUnloaded &&
1900 state != eStateExited &&
1901 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001902 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001903 char error_str[1024];
1904 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001905 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001906 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1907 if (signal_cstr)
1908 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001909 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001910 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001911 }
1912 else
1913 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001914 ::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 +00001915 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001916
1917 process->SetExitStatus (-1, error_str);
1918 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001919 // Debugserver has exited we need to let our ProcessGDBRemote
1920 // know that it no longer has a debugserver instance
1921 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1922 // We are returning true to this function below, so we can
1923 // forget about the monitor handle.
1924 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001925 }
1926 return true;
1927}
1928
1929void
1930ProcessGDBRemote::KillDebugserverProcess ()
1931{
1932 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1933 {
1934 ::kill (m_debugserver_pid, SIGINT);
1935 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1936 }
1937}
1938
1939void
1940ProcessGDBRemote::Initialize()
1941{
1942 static bool g_initialized = false;
1943
1944 if (g_initialized == false)
1945 {
1946 g_initialized = true;
1947 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1948 GetPluginDescriptionStatic(),
1949 CreateInstance);
1950
1951 Log::Callbacks log_callbacks = {
1952 ProcessGDBRemoteLog::DisableLog,
1953 ProcessGDBRemoteLog::EnableLog,
1954 ProcessGDBRemoteLog::ListLogCategories
1955 };
1956
1957 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1958 }
1959}
1960
1961bool
1962ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1963{
1964 if (m_curr_tid == tid)
1965 return true;
1966
1967 char packet[32];
1968 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1969 assert (packet_len + 1 < sizeof(packet));
1970 StringExtractorGDBRemote response;
1971 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1972 {
1973 if (response.IsOKPacket())
1974 {
1975 m_curr_tid = tid;
1976 return true;
1977 }
1978 }
1979 return false;
1980}
1981
1982bool
1983ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
1984{
1985 if (m_curr_tid_run == tid)
1986 return true;
1987
1988 char packet[32];
1989 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1990 assert (packet_len + 1 < sizeof(packet));
1991 StringExtractorGDBRemote response;
1992 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1993 {
1994 if (response.IsOKPacket())
1995 {
1996 m_curr_tid_run = tid;
1997 return true;
1998 }
1999 }
2000 return false;
2001}
2002
2003void
2004ProcessGDBRemote::ResetGDBRemoteState ()
2005{
2006 // Reset and GDB remote state
2007 m_curr_tid = LLDB_INVALID_THREAD_ID;
2008 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2009 m_z0_supported = 1;
2010}
2011
2012
2013bool
2014ProcessGDBRemote::StartAsyncThread ()
2015{
2016 ResetGDBRemoteState ();
2017
Greg Claytone005f2c2010-11-06 01:53:30 +00002018 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002019
2020 if (log)
2021 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2022
2023 // Create a thread that watches our internal state and controls which
2024 // events make it to clients (into the DCProcess event queue).
2025 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2026 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2027}
2028
2029void
2030ProcessGDBRemote::StopAsyncThread ()
2031{
Greg Claytone005f2c2010-11-06 01:53:30 +00002032 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002033
2034 if (log)
2035 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2036
2037 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2038
2039 // Stop the stdio thread
2040 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2041 {
2042 Host::ThreadJoin (m_async_thread, NULL, NULL);
2043 }
2044}
2045
2046
2047void *
2048ProcessGDBRemote::AsyncThread (void *arg)
2049{
2050 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2051
Greg Claytone005f2c2010-11-06 01:53:30 +00002052 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002053 if (log)
2054 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2055
2056 Listener listener ("ProcessGDBRemote::AsyncThread");
2057 EventSP event_sp;
2058 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2059 eBroadcastBitAsyncThreadShouldExit;
2060
2061 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2062 {
2063 bool done = false;
2064 while (!done)
2065 {
Caroline Tice926060e2010-10-29 21:48:37 +00002066 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002067 if (log)
2068 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2069 if (listener.WaitForEvent (NULL, event_sp))
2070 {
2071 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002072 if (log)
2073 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2074
Chris Lattner24943d22010-06-08 16:52:24 +00002075 switch (event_type)
2076 {
2077 case eBroadcastBitAsyncContinue:
2078 {
2079 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2080
2081 if (continue_packet)
2082 {
2083 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2084 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002085 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002086 if (log)
2087 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2088
2089 process->SetPrivateState(eStateRunning);
2090 StringExtractorGDBRemote response;
2091 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2092
2093 switch (stop_state)
2094 {
2095 case eStateStopped:
2096 case eStateCrashed:
2097 case eStateSuspended:
2098 process->m_last_stop_packet = response;
2099 process->m_last_stop_packet.SetFilePos (0);
2100 process->SetPrivateState (stop_state);
2101 break;
2102
2103 case eStateExited:
2104 process->m_last_stop_packet = response;
2105 process->m_last_stop_packet.SetFilePos (0);
2106 response.SetFilePos(1);
2107 process->SetExitStatus(response.GetHexU8(), NULL);
2108 done = true;
2109 break;
2110
2111 case eStateInvalid:
2112 break;
2113
2114 default:
2115 process->SetPrivateState (stop_state);
2116 break;
2117 }
2118 }
2119 }
2120 break;
2121
2122 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002123 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002124 if (log)
2125 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2126 done = true;
2127 break;
2128
2129 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002130 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002131 if (log)
2132 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2133 done = true;
2134 break;
2135 }
2136 }
2137 else
2138 {
Caroline Tice926060e2010-10-29 21:48:37 +00002139 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002140 if (log)
2141 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2142 done = true;
2143 }
2144 }
2145 }
2146
Caroline Tice926060e2010-10-29 21:48:37 +00002147 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002148 if (log)
2149 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2150
2151 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2152 return NULL;
2153}
2154
2155lldb_private::unw_addr_space_t
2156ProcessGDBRemote::GetLibUnwindAddressSpace ()
2157{
2158 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002159
2160 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2161 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002162 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002163 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002164 target_type = UNW_TARGET_X86_64;
2165
2166 if (m_libunwind_addr_space)
2167 {
2168 if (m_libunwind_target_type != target_type)
2169 DestoryLibUnwindAddressSpace();
2170 else
2171 return m_libunwind_addr_space;
2172 }
2173 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2174 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2175 if (m_libunwind_addr_space)
2176 m_libunwind_target_type = target_type;
2177 else
2178 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2179 return m_libunwind_addr_space;
2180}
2181
2182void
2183ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2184{
2185 if (m_libunwind_addr_space)
2186 {
2187 unw_destroy_addr_space (m_libunwind_addr_space);
2188 m_libunwind_addr_space = NULL;
2189 }
2190 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2191}
2192
2193
2194const char *
2195ProcessGDBRemote::GetDispatchQueueNameForThread
2196(
2197 addr_t thread_dispatch_qaddr,
2198 std::string &dispatch_queue_name
2199)
2200{
2201 dispatch_queue_name.clear();
2202 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2203 {
2204 // Cache the dispatch_queue_offsets_addr value so we don't always have
2205 // to look it up
2206 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2207 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002208 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2209 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002210 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002211 if (module_sp)
2212 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2213
2214 if (dispatch_queue_offsets_symbol == NULL)
2215 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002216 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002217 if (module_sp)
2218 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2219 }
Chris Lattner24943d22010-06-08 16:52:24 +00002220 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002221 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002222
2223 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2224 return NULL;
2225 }
2226
2227 uint8_t memory_buffer[8];
2228 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2229
2230 // Excerpt from src/queue_private.h
2231 struct dispatch_queue_offsets_s
2232 {
2233 uint16_t dqo_version;
2234 uint16_t dqo_label;
2235 uint16_t dqo_label_size;
2236 } dispatch_queue_offsets;
2237
2238
2239 Error error;
2240 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2241 {
2242 uint32_t data_offset = 0;
2243 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2244 {
2245 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2246 {
2247 data_offset = 0;
2248 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2249 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2250 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2251 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2252 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2253 dispatch_queue_name.erase (bytes_read);
2254 }
2255 }
2256 }
2257 }
2258 if (dispatch_queue_name.empty())
2259 return NULL;
2260 return dispatch_queue_name.c_str();
2261}
2262
Jim Ingham7508e732010-08-09 23:31:02 +00002263uint32_t
2264ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2265{
2266 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2267 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2268 if (m_local_debugserver)
2269 {
2270 return Host::ListProcessesMatchingName (name, matches, pids);
2271 }
2272 else
2273 {
2274 // FIXME: Implement talking to the remote debugserver.
2275 return 0;
2276 }
2277
2278}