blob: 5496a02343ad63b25f364785b3f4c9e8c070de94 [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;
883 if (m_gdb_comm.WaitForIsRunning (timedout_sec))
884 {
885 error.SetErrorString("Resume timed out.");
886 }
887 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000888}
889
890size_t
891ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
892{
893 const uint8_t *trap_opcode = NULL;
894 uint32_t trap_opcode_size = 0;
895
896 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
897 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
898 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
899 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
900
Jim Ingham7508e732010-08-09 23:31:02 +0000901 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000902 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000903 {
Greg Claytoncf015052010-06-11 03:25:34 +0000904 case ArchSpec::eCPU_i386:
905 case ArchSpec::eCPU_x86_64:
906 trap_opcode = g_i386_breakpoint_opcode;
907 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
908 break;
909
910 case ArchSpec::eCPU_arm:
911 // TODO: fill this in for ARM. We need to dig up the symbol for
912 // the address in the breakpoint locaiton and figure out if it is
913 // an ARM or Thumb breakpoint.
914 trap_opcode = g_arm_breakpoint_opcode;
915 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
916 break;
917
918 case ArchSpec::eCPU_ppc:
919 case ArchSpec::eCPU_ppc64:
920 trap_opcode = g_ppc_breakpoint_opcode;
921 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
922 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000923
Greg Claytoncf015052010-06-11 03:25:34 +0000924 default:
925 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
926 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000927 }
928
929 if (trap_opcode && trap_opcode_size)
930 {
931 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
932 return trap_opcode_size;
933 }
934 return 0;
935}
936
937uint32_t
938ProcessGDBRemote::UpdateThreadListIfNeeded ()
939{
940 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000941 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000942 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000943 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
944
Greg Clayton5205f0b2010-09-03 17:10:42 +0000945 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000946 const uint32_t stop_id = GetStopID();
947 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
948 {
949 // Update the thread list's stop id immediately so we don't recurse into this function.
950 ThreadList curr_thread_list (this);
951 curr_thread_list.SetStopID(stop_id);
952
953 Error err;
954 StringExtractorGDBRemote response;
955 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
956 response.IsNormalPacket();
957 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
958 {
959 char ch = response.GetChar();
960 if (ch == 'l')
961 break;
962 if (ch == 'm')
963 {
964 do
965 {
966 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
967
968 if (tid != LLDB_INVALID_THREAD_ID)
969 {
970 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
971 if (thread_sp)
972 thread_sp->GetRegisterContext()->Invalidate();
973 else
974 thread_sp.reset (new ThreadGDBRemote (*this, tid));
975 curr_thread_list.AddThread(thread_sp);
976 }
977
978 ch = response.GetChar();
979 } while (ch == ',');
980 }
981 }
982
983 m_thread_list = curr_thread_list;
984
985 SetThreadStopInfo (m_last_stop_packet);
986 }
987 return GetThreadList().GetSize(false);
988}
989
990
991StateType
992ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
993{
994 const char stop_type = stop_packet.GetChar();
995 switch (stop_type)
996 {
997 case 'T':
998 case 'S':
999 {
1000 // Stop with signal and thread info
1001 const uint8_t signo = stop_packet.GetHexU8();
1002 std::string name;
1003 std::string value;
1004 std::string thread_name;
1005 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001006 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001007 uint32_t tid = LLDB_INVALID_THREAD_ID;
1008 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1009 uint32_t exc_data_count = 0;
1010 while (stop_packet.GetNameColonValue(name, value))
1011 {
1012 if (name.compare("metype") == 0)
1013 {
1014 // exception type in big endian hex
1015 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1016 }
1017 else if (name.compare("mecount") == 0)
1018 {
1019 // exception count in big endian hex
1020 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1021 }
1022 else if (name.compare("medata") == 0)
1023 {
1024 // exception data in big endian hex
1025 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1026 }
1027 else if (name.compare("thread") == 0)
1028 {
1029 // thread in big endian hex
1030 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1031 }
1032 else if (name.compare("name") == 0)
1033 {
1034 thread_name.swap (value);
1035 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001036 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001037 {
1038 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1039 }
1040 }
1041 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1042
1043 if (thread_sp)
1044 {
1045 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1046
1047 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1048 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001049 if (exc_type != 0)
1050 {
Greg Clayton643ee732010-08-04 01:40:35 +00001051 const size_t exc_data_count = exc_data.size();
1052
1053 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1054 exc_type,
1055 exc_data_count,
1056 exc_data_count >= 1 ? exc_data[0] : 0,
1057 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001058 }
1059 else if (signo)
1060 {
Greg Clayton643ee732010-08-04 01:40:35 +00001061 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001062 }
1063 else
1064 {
Greg Clayton643ee732010-08-04 01:40:35 +00001065 StopInfoSP invalid_stop_info_sp;
1066 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001067 }
1068 }
1069 return eStateStopped;
1070 }
1071 break;
1072
1073 case 'W':
1074 // process exited
1075 return eStateExited;
1076
1077 default:
1078 break;
1079 }
1080 return eStateInvalid;
1081}
1082
1083void
1084ProcessGDBRemote::RefreshStateAfterStop ()
1085{
Jim Ingham7508e732010-08-09 23:31:02 +00001086 // FIXME - add a variable to tell that we're in the middle of attaching if we
1087 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001088 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001089// if (!GetTarget().GetArchitecture().IsValid())
1090// {
1091// Module *exe_module = GetTarget().GetExecutableModule().get();
1092// if (exe_module)
1093// m_arch_spec = exe_module->GetArchitecture();
1094// }
1095
Chris Lattner24943d22010-06-08 16:52:24 +00001096 // Let all threads recover from stopping and do any clean up based
1097 // on the previous thread state (if any).
1098 m_thread_list.RefreshStateAfterStop();
1099
1100 // Discover new threads:
1101 UpdateThreadListIfNeeded ();
1102}
1103
1104Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001105ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001106{
1107 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001108
Chris Lattner24943d22010-06-08 16:52:24 +00001109 if (m_gdb_comm.IsRunning())
1110 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001111 caused_stop = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001112 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001113 Mutex::Locker locker;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001114
Greg Clayton20d338f2010-11-18 05:57:03 +00001115 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001116 {
1117 if (timed_out)
1118 error.SetErrorString("timed out sending interrupt packet");
1119 else
1120 error.SetErrorString("unknown error sending interrupt packet");
1121 }
1122 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001123 else
1124 {
1125 caused_stop = false;
1126 }
1127
Chris Lattner24943d22010-06-08 16:52:24 +00001128 return error;
1129}
1130
1131Error
1132ProcessGDBRemote::WillDetach ()
1133{
1134 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001135
Greg Clayton4fb400f2010-09-27 21:07:38 +00001136 if (m_gdb_comm.IsRunning())
1137 {
1138 bool timed_out = false;
1139 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001140 PausePrivateStateThread();
1141 m_thread_list.DiscardThreadPlans();
1142 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001143 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1144 {
1145 if (timed_out)
1146 error.SetErrorString("timed out sending interrupt packet");
1147 else
1148 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001149 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001150 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001151 TimeValue timeout_time;
1152 timeout_time = TimeValue::Now();
1153 timeout_time.OffsetWithSeconds(2);
1154
1155 EventSP event_sp;
1156 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1157 if (state != eStateStopped)
1158 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001159 }
Chris Lattner24943d22010-06-08 16:52:24 +00001160 return error;
1161}
1162
Greg Clayton4fb400f2010-09-27 21:07:38 +00001163Error
1164ProcessGDBRemote::DoDetach()
1165{
1166 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001167 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001168 if (log)
1169 log->Printf ("ProcessGDBRemote::DoDetach()");
1170
1171 DisableAllBreakpointSites ();
1172
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001173 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001174
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001175 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1176 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001177 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001178 if (response_size)
1179 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1180 else
1181 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001182 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001183 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001184 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001185
Greg Clayton4fb400f2010-09-27 21:07:38 +00001186 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001187 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001188
1189 SetPrivateState (eStateDetached);
1190 ResumePrivateStateThread();
1191
1192 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001193 return error;
1194}
Chris Lattner24943d22010-06-08 16:52:24 +00001195
1196Error
1197ProcessGDBRemote::DoDestroy ()
1198{
1199 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001200 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001201 if (log)
1202 log->Printf ("ProcessGDBRemote::DoDestroy()");
1203
1204 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001205 Mutex::Locker locker;
1206 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001207 DisableAllBreakpointSites ();
1208 SetExitStatus(-1, "process killed");
1209
1210 StringExtractorGDBRemote response;
1211 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1212 {
Caroline Tice926060e2010-10-29 21:48:37 +00001213 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001214 if (log)
1215 {
1216 if (response.IsOKPacket())
1217 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1218 else
1219 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1220 }
1221 }
1222
1223 StopAsyncThread ();
1224 m_gdb_comm.StopReadThread();
1225 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001226 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001227 return error;
1228}
1229
Chris Lattner24943d22010-06-08 16:52:24 +00001230//------------------------------------------------------------------
1231// Process Queries
1232//------------------------------------------------------------------
1233
1234bool
1235ProcessGDBRemote::IsAlive ()
1236{
1237 return m_gdb_comm.IsConnected();
1238}
1239
1240addr_t
1241ProcessGDBRemote::GetImageInfoAddress()
1242{
1243 if (!m_gdb_comm.IsRunning())
1244 {
1245 StringExtractorGDBRemote response;
1246 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1247 {
1248 if (response.IsNormalPacket())
1249 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1250 }
1251 }
1252 return LLDB_INVALID_ADDRESS;
1253}
1254
1255DynamicLoader *
1256ProcessGDBRemote::GetDynamicLoader()
1257{
1258 return m_dynamic_loader_ap.get();
1259}
1260
1261//------------------------------------------------------------------
1262// Process Memory
1263//------------------------------------------------------------------
1264size_t
1265ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1266{
1267 if (size > m_max_memory_size)
1268 {
1269 // Keep memory read sizes down to a sane limit. This function will be
1270 // called multiple times in order to complete the task by
1271 // lldb_private::Process so it is ok to do this.
1272 size = m_max_memory_size;
1273 }
1274
1275 char packet[64];
1276 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1277 assert (packet_len + 1 < sizeof(packet));
1278 StringExtractorGDBRemote response;
1279 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1280 {
1281 if (response.IsNormalPacket())
1282 {
1283 error.Clear();
1284 return response.GetHexBytes(buf, size, '\xdd');
1285 }
1286 else if (response.IsErrorPacket())
1287 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1288 else if (response.IsUnsupportedPacket())
1289 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1290 else
1291 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1292 }
1293 else
1294 {
1295 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1296 }
1297 return 0;
1298}
1299
1300size_t
1301ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1302{
1303 StreamString packet;
1304 packet.Printf("M%llx,%zx:", addr, size);
1305 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1306 StringExtractorGDBRemote response;
1307 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1308 {
1309 if (response.IsOKPacket())
1310 {
1311 error.Clear();
1312 return size;
1313 }
1314 else if (response.IsErrorPacket())
1315 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1316 else if (response.IsUnsupportedPacket())
1317 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1318 else
1319 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1320 }
1321 else
1322 {
1323 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1324 }
1325 return 0;
1326}
1327
1328lldb::addr_t
1329ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1330{
1331 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1332 if (allocated_addr == LLDB_INVALID_ADDRESS)
1333 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1334 else
1335 error.Clear();
1336 return allocated_addr;
1337}
1338
1339Error
1340ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1341{
1342 Error error;
1343 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1344 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1345 return error;
1346}
1347
1348
1349//------------------------------------------------------------------
1350// Process STDIO
1351//------------------------------------------------------------------
1352
1353size_t
1354ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1355{
1356 Mutex::Locker locker(m_stdio_mutex);
1357 size_t bytes_available = m_stdout_data.size();
1358 if (bytes_available > 0)
1359 {
1360 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1361 if (bytes_available > buf_size)
1362 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001363 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001364 m_stdout_data.erase(0, buf_size);
1365 bytes_available = buf_size;
1366 }
1367 else
1368 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001369 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001370 m_stdout_data.clear();
1371
1372 //ResetEventBits(eBroadcastBitSTDOUT);
1373 }
1374 }
1375 return bytes_available;
1376}
1377
1378size_t
1379ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1380{
1381 // Can we get STDERR through the remote protocol?
1382 return 0;
1383}
1384
1385size_t
1386ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1387{
1388 if (m_stdio_communication.IsConnected())
1389 {
1390 ConnectionStatus status;
1391 m_stdio_communication.Write(src, src_len, status, NULL);
1392 }
1393 return 0;
1394}
1395
1396Error
1397ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1398{
1399 Error error;
1400 assert (bp_site != NULL);
1401
Greg Claytone005f2c2010-11-06 01:53:30 +00001402 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001403 user_id_t site_id = bp_site->GetID();
1404 const addr_t addr = bp_site->GetLoadAddress();
1405 if (log)
1406 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1407
1408 if (bp_site->IsEnabled())
1409 {
1410 if (log)
1411 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1412 return error;
1413 }
1414 else
1415 {
1416 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1417
1418 if (bp_site->HardwarePreferred())
1419 {
1420 // Try and set hardware breakpoint, and if that fails, fall through
1421 // and set a software breakpoint?
1422 }
1423
1424 if (m_z0_supported)
1425 {
1426 char packet[64];
1427 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1428 assert (packet_len + 1 < sizeof(packet));
1429 StringExtractorGDBRemote response;
1430 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1431 {
1432 if (response.IsUnsupportedPacket())
1433 {
1434 // Disable z packet support and try again
1435 m_z0_supported = 0;
1436 return EnableBreakpoint (bp_site);
1437 }
1438 else if (response.IsOKPacket())
1439 {
1440 bp_site->SetEnabled(true);
1441 bp_site->SetType (BreakpointSite::eExternal);
1442 return error;
1443 }
1444 else
1445 {
1446 uint8_t error_byte = response.GetError();
1447 if (error_byte)
1448 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1449 }
1450 }
1451 }
1452 else
1453 {
1454 return EnableSoftwareBreakpoint (bp_site);
1455 }
1456 }
1457
1458 if (log)
1459 {
1460 const char *err_string = error.AsCString();
1461 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1462 bp_site->GetLoadAddress(),
1463 err_string ? err_string : "NULL");
1464 }
1465 // We shouldn't reach here on a successful breakpoint enable...
1466 if (error.Success())
1467 error.SetErrorToGenericError();
1468 return error;
1469}
1470
1471Error
1472ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1473{
1474 Error error;
1475 assert (bp_site != NULL);
1476 addr_t addr = bp_site->GetLoadAddress();
1477 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001478 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001479 if (log)
1480 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1481
1482 if (bp_site->IsEnabled())
1483 {
1484 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1485
1486 if (bp_site->IsHardware())
1487 {
1488 // TODO: disable hardware breakpoint...
1489 }
1490 else
1491 {
1492 if (m_z0_supported)
1493 {
1494 char packet[64];
1495 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1496 assert (packet_len + 1 < sizeof(packet));
1497 StringExtractorGDBRemote response;
1498 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1499 {
1500 if (response.IsUnsupportedPacket())
1501 {
1502 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1503 }
1504 else if (response.IsOKPacket())
1505 {
1506 if (log)
1507 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1508 bp_site->SetEnabled(false);
1509 return error;
1510 }
1511 else
1512 {
1513 uint8_t error_byte = response.GetError();
1514 if (error_byte)
1515 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1516 }
1517 }
1518 }
1519 else
1520 {
1521 return DisableSoftwareBreakpoint (bp_site);
1522 }
1523 }
1524 }
1525 else
1526 {
1527 if (log)
1528 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1529 return error;
1530 }
1531
1532 if (error.Success())
1533 error.SetErrorToGenericError();
1534 return error;
1535}
1536
1537Error
1538ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1539{
1540 Error error;
1541 if (wp)
1542 {
1543 user_id_t watchID = wp->GetID();
1544 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001545 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001546 if (log)
1547 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1548 if (wp->IsEnabled())
1549 {
1550 if (log)
1551 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1552 return error;
1553 }
1554 else
1555 {
1556 // Pass down an appropriate z/Z packet...
1557 error.SetErrorString("watchpoints not supported");
1558 }
1559 }
1560 else
1561 {
1562 error.SetErrorString("Watchpoint location argument was NULL.");
1563 }
1564 if (error.Success())
1565 error.SetErrorToGenericError();
1566 return error;
1567}
1568
1569Error
1570ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1571{
1572 Error error;
1573 if (wp)
1574 {
1575 user_id_t watchID = wp->GetID();
1576
Greg Claytone005f2c2010-11-06 01:53:30 +00001577 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001578
1579 addr_t addr = wp->GetLoadAddress();
1580 if (log)
1581 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1582
1583 if (wp->IsHardware())
1584 {
1585 // Pass down an appropriate z/Z packet...
1586 error.SetErrorString("watchpoints not supported");
1587 }
1588 // TODO: clear software watchpoints if we implement them
1589 }
1590 else
1591 {
1592 error.SetErrorString("Watchpoint location argument was NULL.");
1593 }
1594 if (error.Success())
1595 error.SetErrorToGenericError();
1596 return error;
1597}
1598
1599void
1600ProcessGDBRemote::Clear()
1601{
1602 m_flags = 0;
1603 m_thread_list.Clear();
1604 {
1605 Mutex::Locker locker(m_stdio_mutex);
1606 m_stdout_data.clear();
1607 }
1608 DestoryLibUnwindAddressSpace();
1609}
1610
1611Error
1612ProcessGDBRemote::DoSignal (int signo)
1613{
1614 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001615 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001616 if (log)
1617 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1618
1619 if (!m_gdb_comm.SendAsyncSignal (signo))
1620 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1621 return error;
1622}
1623
Caroline Tice861efb32010-11-16 05:07:41 +00001624//void
1625//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1626//{
1627// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1628// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1629//}
Chris Lattner24943d22010-06-08 16:52:24 +00001630
Caroline Tice861efb32010-11-16 05:07:41 +00001631//void
1632//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1633//{
1634// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1635// Mutex::Locker locker(m_stdio_mutex);
1636// m_stdout_data.append(s, len);
1637//
1638// // FIXME: Make a real data object for this and put it out.
1639// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1640//}
Chris Lattner24943d22010-06-08 16:52:24 +00001641
1642
1643Error
1644ProcessGDBRemote::StartDebugserverProcess
1645(
1646 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1647 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1648 char const *inferior_envp[], // Environment to pass along to the inferior program
1649 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001650 bool launch_process, // Set to true if we are going to be launching a the process
1651 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 +00001652 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1653 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Clayton23cf0c72010-11-08 04:29:11 +00001654 bool disable_aslr, // Disable ASLR
Chris Lattner24943d22010-06-08 16:52:24 +00001655 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1656)
1657{
1658 Error error;
1659 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1660 {
1661 // If we locate debugserver, keep that located version around
1662 static FileSpec g_debugserver_file_spec;
1663
1664 FileSpec debugserver_file_spec;
1665 char debugserver_path[PATH_MAX];
1666
1667 // Always check to see if we have an environment override for the path
1668 // to the debugserver to use and use it if we do.
1669 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1670 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001671 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001672 else
1673 debugserver_file_spec = g_debugserver_file_spec;
1674 bool debugserver_exists = debugserver_file_spec.Exists();
1675 if (!debugserver_exists)
1676 {
1677 // The debugserver binary is in the LLDB.framework/Resources
1678 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001679 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001680 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001681 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001682 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001683 if (debugserver_exists)
1684 {
1685 g_debugserver_file_spec = debugserver_file_spec;
1686 }
1687 else
1688 {
1689 g_debugserver_file_spec.Clear();
1690 debugserver_file_spec.Clear();
1691 }
Chris Lattner24943d22010-06-08 16:52:24 +00001692 }
1693 }
1694
1695 if (debugserver_exists)
1696 {
1697 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1698
1699 m_stdio_communication.Clear();
1700 posix_spawnattr_t attr;
1701
Greg Claytone005f2c2010-11-06 01:53:30 +00001702 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001703
1704 Error local_err; // Errors that don't affect the spawning.
1705 if (log)
1706 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1707 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1708 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001709 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001710 if (error.Fail())
1711 return error;;
1712
1713#if !defined (__arm__)
1714
Greg Clayton24b48ff2010-10-17 22:03:32 +00001715 // We don't need to do this for ARM, and we really shouldn't now
1716 // that we have multiple CPU subtypes and no posix_spawnattr call
1717 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001718 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001719 {
Greg Claytoncf015052010-06-11 03:25:34 +00001720 cpu_type_t cpu = inferior_arch.GetCPUType();
1721 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1722 {
1723 size_t ocount = 0;
1724 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1725 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001726 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 +00001727
Greg Claytoncf015052010-06-11 03:25:34 +00001728 if (error.Fail() != 0 || ocount != 1)
1729 return error;
1730 }
Chris Lattner24943d22010-06-08 16:52:24 +00001731 }
1732
1733#endif
1734
1735 Args debugserver_args;
1736 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001737
Chris Lattner24943d22010-06-08 16:52:24 +00001738 lldb_utility::PseudoTerminal pty;
Greg Clayton23cf0c72010-11-08 04:29:11 +00001739 if (launch_process && stdio_path == NULL && m_local_debugserver)
Chris Lattner24943d22010-06-08 16:52:24 +00001740 {
Chris Lattner24943d22010-06-08 16:52:24 +00001741 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001742 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001743 }
1744
1745 // Start args with "debugserver /file/path -r --"
1746 debugserver_args.AppendArgument(debugserver_path);
1747 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001748 // use native registers, not the GDB registers
1749 debugserver_args.AppendArgument("--native-regs");
1750 // make debugserver run in its own session so signals generated by
1751 // special terminal key sequences (^C) don't affect debugserver
1752 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001753
Greg Clayton452bf612010-08-31 18:35:14 +00001754 if (disable_aslr)
1755 debugserver_args.AppendArguments("--disable-aslr");
1756
Chris Lattner24943d22010-06-08 16:52:24 +00001757 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001758 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001759 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001760 debugserver_args.AppendArgument("--stdio-path");
1761 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001762 }
1763
1764 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1765 if (env_debugserver_log_file)
1766 {
1767 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1768 debugserver_args.AppendArgument(arg_cstr);
1769 }
1770
1771 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1772 if (env_debugserver_log_flags)
1773 {
1774 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1775 debugserver_args.AppendArgument(arg_cstr);
1776 }
1777// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1778// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1779
1780 // Now append the program arguments
1781 if (launch_process)
1782 {
1783 if (inferior_argv)
1784 {
1785 // Terminate the debugserver args so we can now append the inferior args
1786 debugserver_args.AppendArgument("--");
1787
1788 for (int i = 0; inferior_argv[i] != NULL; ++i)
1789 debugserver_args.AppendArgument (inferior_argv[i]);
1790 }
1791 else
1792 {
1793 // Will send environment entries with the 'QEnvironment:' packet
1794 // Will send arguments with the 'A' packet
1795 }
1796 }
1797 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1798 {
1799 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1800 debugserver_args.AppendArgument (arg_cstr);
1801 }
1802 else if (attach_name && attach_name[0])
1803 {
1804 if (wait_for_launch)
1805 debugserver_args.AppendArgument ("--waitfor");
1806 else
1807 debugserver_args.AppendArgument ("--attach");
1808 debugserver_args.AppendArgument (attach_name);
1809 }
1810
1811 Error file_actions_err;
1812 posix_spawn_file_actions_t file_actions;
1813#if DONT_CLOSE_DEBUGSERVER_STDIO
1814 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1815#else
1816 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1817 if (file_actions_err.Success())
1818 {
1819 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1820 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1821 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1822 }
1823#endif
1824
1825 if (log)
1826 {
1827 StreamString strm;
1828 debugserver_args.Dump (&strm);
1829 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1830 }
1831
1832 error.SetError(::posix_spawnp (&m_debugserver_pid,
1833 debugserver_path,
1834 file_actions_err.Success() ? &file_actions : NULL,
1835 &attr,
1836 debugserver_args.GetArgumentVector(),
1837 (char * const*)inferior_envp),
1838 eErrorTypePOSIX);
1839
Greg Claytone9d0df42010-07-02 01:29:13 +00001840
1841 ::posix_spawnattr_destroy (&attr);
1842
Chris Lattner24943d22010-06-08 16:52:24 +00001843 if (file_actions_err.Success())
1844 ::posix_spawn_file_actions_destroy (&file_actions);
1845
1846 // We have seen some cases where posix_spawnp was returning a valid
1847 // looking pid even when an error was returned, so clear it out
1848 if (error.Fail())
1849 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1850
1851 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001852 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 +00001853
Caroline Tice91a1dab2010-11-05 22:37:44 +00001854 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1855 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001856 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001857 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001858 }
Chris Lattner24943d22010-06-08 16:52:24 +00001859 }
1860 else
1861 {
1862 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1863 }
1864
1865 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1866 StartAsyncThread ();
1867 }
1868 return error;
1869}
1870
1871bool
1872ProcessGDBRemote::MonitorDebugserverProcess
1873(
1874 void *callback_baton,
1875 lldb::pid_t debugserver_pid,
1876 int signo, // Zero for no signal
1877 int exit_status // Exit value of process if signal is zero
1878)
1879{
1880 // We pass in the ProcessGDBRemote inferior process it and name it
1881 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1882 // pointer value itself, thus we need the double cast...
1883
1884 // "debugserver_pid" argument passed in is the process ID for
1885 // debugserver that we are tracking...
1886
Greg Clayton75ccf502010-08-21 02:22:51 +00001887 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1888
1889 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001890 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001891 // Sleep for a half a second to make sure our inferior process has
1892 // time to set its exit status before we set it incorrectly when
1893 // both the debugserver and the inferior process shut down.
1894 usleep (500000);
1895 // If our process hasn't yet exited, debugserver might have died.
1896 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001897 const StateType state = process->GetState();
1898
1899 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1900 state != eStateInvalid &&
1901 state != eStateUnloaded &&
1902 state != eStateExited &&
1903 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001904 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001905 char error_str[1024];
1906 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001907 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001908 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1909 if (signal_cstr)
1910 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001911 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001912 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001913 }
1914 else
1915 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001916 ::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 +00001917 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001918
1919 process->SetExitStatus (-1, error_str);
1920 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001921 // Debugserver has exited we need to let our ProcessGDBRemote
1922 // know that it no longer has a debugserver instance
1923 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1924 // We are returning true to this function below, so we can
1925 // forget about the monitor handle.
1926 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001927 }
1928 return true;
1929}
1930
1931void
1932ProcessGDBRemote::KillDebugserverProcess ()
1933{
1934 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1935 {
1936 ::kill (m_debugserver_pid, SIGINT);
1937 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1938 }
1939}
1940
1941void
1942ProcessGDBRemote::Initialize()
1943{
1944 static bool g_initialized = false;
1945
1946 if (g_initialized == false)
1947 {
1948 g_initialized = true;
1949 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1950 GetPluginDescriptionStatic(),
1951 CreateInstance);
1952
1953 Log::Callbacks log_callbacks = {
1954 ProcessGDBRemoteLog::DisableLog,
1955 ProcessGDBRemoteLog::EnableLog,
1956 ProcessGDBRemoteLog::ListLogCategories
1957 };
1958
1959 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1960 }
1961}
1962
1963bool
1964ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1965{
1966 if (m_curr_tid == tid)
1967 return true;
1968
1969 char packet[32];
1970 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1971 assert (packet_len + 1 < sizeof(packet));
1972 StringExtractorGDBRemote response;
1973 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1974 {
1975 if (response.IsOKPacket())
1976 {
1977 m_curr_tid = tid;
1978 return true;
1979 }
1980 }
1981 return false;
1982}
1983
1984bool
1985ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
1986{
1987 if (m_curr_tid_run == tid)
1988 return true;
1989
1990 char packet[32];
1991 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1992 assert (packet_len + 1 < sizeof(packet));
1993 StringExtractorGDBRemote response;
1994 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1995 {
1996 if (response.IsOKPacket())
1997 {
1998 m_curr_tid_run = tid;
1999 return true;
2000 }
2001 }
2002 return false;
2003}
2004
2005void
2006ProcessGDBRemote::ResetGDBRemoteState ()
2007{
2008 // Reset and GDB remote state
2009 m_curr_tid = LLDB_INVALID_THREAD_ID;
2010 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2011 m_z0_supported = 1;
2012}
2013
2014
2015bool
2016ProcessGDBRemote::StartAsyncThread ()
2017{
2018 ResetGDBRemoteState ();
2019
Greg Claytone005f2c2010-11-06 01:53:30 +00002020 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002021
2022 if (log)
2023 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2024
2025 // Create a thread that watches our internal state and controls which
2026 // events make it to clients (into the DCProcess event queue).
2027 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2028 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2029}
2030
2031void
2032ProcessGDBRemote::StopAsyncThread ()
2033{
Greg Claytone005f2c2010-11-06 01:53:30 +00002034 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002035
2036 if (log)
2037 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2038
2039 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2040
2041 // Stop the stdio thread
2042 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2043 {
2044 Host::ThreadJoin (m_async_thread, NULL, NULL);
2045 }
2046}
2047
2048
2049void *
2050ProcessGDBRemote::AsyncThread (void *arg)
2051{
2052 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2053
Greg Claytone005f2c2010-11-06 01:53:30 +00002054 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002055 if (log)
2056 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2057
2058 Listener listener ("ProcessGDBRemote::AsyncThread");
2059 EventSP event_sp;
2060 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2061 eBroadcastBitAsyncThreadShouldExit;
2062
2063 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2064 {
2065 bool done = false;
2066 while (!done)
2067 {
Caroline Tice926060e2010-10-29 21:48:37 +00002068 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002069 if (log)
2070 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2071 if (listener.WaitForEvent (NULL, event_sp))
2072 {
2073 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002074 if (log)
2075 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2076
Chris Lattner24943d22010-06-08 16:52:24 +00002077 switch (event_type)
2078 {
2079 case eBroadcastBitAsyncContinue:
2080 {
2081 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2082
2083 if (continue_packet)
2084 {
2085 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2086 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002087 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002088 if (log)
2089 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2090
2091 process->SetPrivateState(eStateRunning);
2092 StringExtractorGDBRemote response;
2093 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2094
2095 switch (stop_state)
2096 {
2097 case eStateStopped:
2098 case eStateCrashed:
2099 case eStateSuspended:
2100 process->m_last_stop_packet = response;
2101 process->m_last_stop_packet.SetFilePos (0);
2102 process->SetPrivateState (stop_state);
2103 break;
2104
2105 case eStateExited:
2106 process->m_last_stop_packet = response;
2107 process->m_last_stop_packet.SetFilePos (0);
2108 response.SetFilePos(1);
2109 process->SetExitStatus(response.GetHexU8(), NULL);
2110 done = true;
2111 break;
2112
2113 case eStateInvalid:
2114 break;
2115
2116 default:
2117 process->SetPrivateState (stop_state);
2118 break;
2119 }
2120 }
2121 }
2122 break;
2123
2124 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002125 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002126 if (log)
2127 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2128 done = true;
2129 break;
2130
2131 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002132 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002133 if (log)
2134 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2135 done = true;
2136 break;
2137 }
2138 }
2139 else
2140 {
Caroline Tice926060e2010-10-29 21:48:37 +00002141 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002142 if (log)
2143 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2144 done = true;
2145 }
2146 }
2147 }
2148
Caroline Tice926060e2010-10-29 21:48:37 +00002149 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002150 if (log)
2151 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2152
2153 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2154 return NULL;
2155}
2156
2157lldb_private::unw_addr_space_t
2158ProcessGDBRemote::GetLibUnwindAddressSpace ()
2159{
2160 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002161
2162 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2163 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002164 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002165 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002166 target_type = UNW_TARGET_X86_64;
2167
2168 if (m_libunwind_addr_space)
2169 {
2170 if (m_libunwind_target_type != target_type)
2171 DestoryLibUnwindAddressSpace();
2172 else
2173 return m_libunwind_addr_space;
2174 }
2175 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2176 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2177 if (m_libunwind_addr_space)
2178 m_libunwind_target_type = target_type;
2179 else
2180 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2181 return m_libunwind_addr_space;
2182}
2183
2184void
2185ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2186{
2187 if (m_libunwind_addr_space)
2188 {
2189 unw_destroy_addr_space (m_libunwind_addr_space);
2190 m_libunwind_addr_space = NULL;
2191 }
2192 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2193}
2194
2195
2196const char *
2197ProcessGDBRemote::GetDispatchQueueNameForThread
2198(
2199 addr_t thread_dispatch_qaddr,
2200 std::string &dispatch_queue_name
2201)
2202{
2203 dispatch_queue_name.clear();
2204 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2205 {
2206 // Cache the dispatch_queue_offsets_addr value so we don't always have
2207 // to look it up
2208 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2209 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002210 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2211 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002212 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002213 if (module_sp)
2214 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2215
2216 if (dispatch_queue_offsets_symbol == NULL)
2217 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002218 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002219 if (module_sp)
2220 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2221 }
Chris Lattner24943d22010-06-08 16:52:24 +00002222 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002223 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002224
2225 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2226 return NULL;
2227 }
2228
2229 uint8_t memory_buffer[8];
2230 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2231
2232 // Excerpt from src/queue_private.h
2233 struct dispatch_queue_offsets_s
2234 {
2235 uint16_t dqo_version;
2236 uint16_t dqo_label;
2237 uint16_t dqo_label_size;
2238 } dispatch_queue_offsets;
2239
2240
2241 Error error;
2242 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2243 {
2244 uint32_t data_offset = 0;
2245 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2246 {
2247 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2248 {
2249 data_offset = 0;
2250 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2251 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2252 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2253 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2254 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2255 dispatch_queue_name.erase (bytes_read);
2256 }
2257 }
2258 }
2259 }
2260 if (dispatch_queue_name.empty())
2261 return NULL;
2262 return dispatch_queue_name.c_str();
2263}
2264
Jim Ingham7508e732010-08-09 23:31:02 +00002265uint32_t
2266ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2267{
2268 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2269 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2270 if (m_local_debugserver)
2271 {
2272 return Host::ListProcessesMatchingName (name, matches, pids);
2273 }
2274 else
2275 {
2276 // FIXME: Implement talking to the remote debugserver.
2277 return 0;
2278 }
2279
2280}