blob: 083ef95a1f6ff8587c9d16a1161d4b303ae5f3a9 [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()");
Greg Claytonb749a262010-12-03 06:02:24 +0000881
882 Listener listener ("gdb-remote.resume-packet-sent");
883 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
884 {
885 EventSP event_sp;
886 TimeValue timeout;
887 timeout = TimeValue::Now();
888 timeout.OffsetWithSeconds (5);
889 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
890
891 if (listener.WaitForEvent (&timeout, event_sp) == false)
892 error.SetErrorString("Resume timed out.");
893 }
894
Jim Ingham3ae449a2010-11-17 02:32:00 +0000895 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000896}
897
898size_t
899ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
900{
901 const uint8_t *trap_opcode = NULL;
902 uint32_t trap_opcode_size = 0;
903
904 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
905 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
906 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
907 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
908
Jim Ingham7508e732010-08-09 23:31:02 +0000909 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000910 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000911 {
Greg Claytoncf015052010-06-11 03:25:34 +0000912 case ArchSpec::eCPU_i386:
913 case ArchSpec::eCPU_x86_64:
914 trap_opcode = g_i386_breakpoint_opcode;
915 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
916 break;
917
918 case ArchSpec::eCPU_arm:
919 // TODO: fill this in for ARM. We need to dig up the symbol for
920 // the address in the breakpoint locaiton and figure out if it is
921 // an ARM or Thumb breakpoint.
922 trap_opcode = g_arm_breakpoint_opcode;
923 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
924 break;
925
926 case ArchSpec::eCPU_ppc:
927 case ArchSpec::eCPU_ppc64:
928 trap_opcode = g_ppc_breakpoint_opcode;
929 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
930 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000931
Greg Claytoncf015052010-06-11 03:25:34 +0000932 default:
933 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
934 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000935 }
936
937 if (trap_opcode && trap_opcode_size)
938 {
939 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
940 return trap_opcode_size;
941 }
942 return 0;
943}
944
945uint32_t
946ProcessGDBRemote::UpdateThreadListIfNeeded ()
947{
948 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000949 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000950 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000951 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
952
Greg Clayton5205f0b2010-09-03 17:10:42 +0000953 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000954 const uint32_t stop_id = GetStopID();
955 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
956 {
957 // Update the thread list's stop id immediately so we don't recurse into this function.
958 ThreadList curr_thread_list (this);
959 curr_thread_list.SetStopID(stop_id);
960
961 Error err;
962 StringExtractorGDBRemote response;
963 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
964 response.IsNormalPacket();
965 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
966 {
967 char ch = response.GetChar();
968 if (ch == 'l')
969 break;
970 if (ch == 'm')
971 {
972 do
973 {
974 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
975
976 if (tid != LLDB_INVALID_THREAD_ID)
977 {
978 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
979 if (thread_sp)
980 thread_sp->GetRegisterContext()->Invalidate();
981 else
982 thread_sp.reset (new ThreadGDBRemote (*this, tid));
983 curr_thread_list.AddThread(thread_sp);
984 }
985
986 ch = response.GetChar();
987 } while (ch == ',');
988 }
989 }
990
991 m_thread_list = curr_thread_list;
992
993 SetThreadStopInfo (m_last_stop_packet);
994 }
995 return GetThreadList().GetSize(false);
996}
997
998
999StateType
1000ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1001{
1002 const char stop_type = stop_packet.GetChar();
1003 switch (stop_type)
1004 {
1005 case 'T':
1006 case 'S':
1007 {
1008 // Stop with signal and thread info
1009 const uint8_t signo = stop_packet.GetHexU8();
1010 std::string name;
1011 std::string value;
1012 std::string thread_name;
1013 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001014 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001015 uint32_t tid = LLDB_INVALID_THREAD_ID;
1016 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1017 uint32_t exc_data_count = 0;
1018 while (stop_packet.GetNameColonValue(name, value))
1019 {
1020 if (name.compare("metype") == 0)
1021 {
1022 // exception type in big endian hex
1023 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1024 }
1025 else if (name.compare("mecount") == 0)
1026 {
1027 // exception count in big endian hex
1028 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1029 }
1030 else if (name.compare("medata") == 0)
1031 {
1032 // exception data in big endian hex
1033 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1034 }
1035 else if (name.compare("thread") == 0)
1036 {
1037 // thread in big endian hex
1038 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1039 }
1040 else if (name.compare("name") == 0)
1041 {
1042 thread_name.swap (value);
1043 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001044 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001045 {
1046 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1047 }
1048 }
1049 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1050
1051 if (thread_sp)
1052 {
1053 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1054
1055 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1056 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001057 if (exc_type != 0)
1058 {
Greg Clayton643ee732010-08-04 01:40:35 +00001059 const size_t exc_data_count = exc_data.size();
1060
1061 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1062 exc_type,
1063 exc_data_count,
1064 exc_data_count >= 1 ? exc_data[0] : 0,
1065 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001066 }
1067 else if (signo)
1068 {
Greg Clayton643ee732010-08-04 01:40:35 +00001069 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001070 }
1071 else
1072 {
Greg Clayton643ee732010-08-04 01:40:35 +00001073 StopInfoSP invalid_stop_info_sp;
1074 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001075 }
1076 }
1077 return eStateStopped;
1078 }
1079 break;
1080
1081 case 'W':
1082 // process exited
1083 return eStateExited;
1084
1085 default:
1086 break;
1087 }
1088 return eStateInvalid;
1089}
1090
1091void
1092ProcessGDBRemote::RefreshStateAfterStop ()
1093{
Jim Ingham7508e732010-08-09 23:31:02 +00001094 // FIXME - add a variable to tell that we're in the middle of attaching if we
1095 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001096 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001097// if (!GetTarget().GetArchitecture().IsValid())
1098// {
1099// Module *exe_module = GetTarget().GetExecutableModule().get();
1100// if (exe_module)
1101// m_arch_spec = exe_module->GetArchitecture();
1102// }
1103
Chris Lattner24943d22010-06-08 16:52:24 +00001104 // Let all threads recover from stopping and do any clean up based
1105 // on the previous thread state (if any).
1106 m_thread_list.RefreshStateAfterStop();
1107
1108 // Discover new threads:
1109 UpdateThreadListIfNeeded ();
1110}
1111
1112Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001113ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001114{
1115 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001116
Chris Lattner24943d22010-06-08 16:52:24 +00001117 if (m_gdb_comm.IsRunning())
1118 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001119 caused_stop = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001120 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001121 Mutex::Locker locker;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001122
Greg Clayton20d338f2010-11-18 05:57:03 +00001123 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001124 {
1125 if (timed_out)
1126 error.SetErrorString("timed out sending interrupt packet");
1127 else
1128 error.SetErrorString("unknown error sending interrupt packet");
1129 }
1130 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001131 else
1132 {
1133 caused_stop = false;
1134 }
1135
Chris Lattner24943d22010-06-08 16:52:24 +00001136 return error;
1137}
1138
1139Error
1140ProcessGDBRemote::WillDetach ()
1141{
1142 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001143
Greg Clayton4fb400f2010-09-27 21:07:38 +00001144 if (m_gdb_comm.IsRunning())
1145 {
1146 bool timed_out = false;
1147 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001148 PausePrivateStateThread();
1149 m_thread_list.DiscardThreadPlans();
1150 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001151 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1152 {
1153 if (timed_out)
1154 error.SetErrorString("timed out sending interrupt packet");
1155 else
1156 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001157 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001158 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001159 TimeValue timeout_time;
1160 timeout_time = TimeValue::Now();
1161 timeout_time.OffsetWithSeconds(2);
1162
1163 EventSP event_sp;
1164 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1165 if (state != eStateStopped)
1166 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001167 }
Chris Lattner24943d22010-06-08 16:52:24 +00001168 return error;
1169}
1170
Greg Clayton4fb400f2010-09-27 21:07:38 +00001171Error
1172ProcessGDBRemote::DoDetach()
1173{
1174 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001175 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001176 if (log)
1177 log->Printf ("ProcessGDBRemote::DoDetach()");
1178
1179 DisableAllBreakpointSites ();
1180
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001181 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001182
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001183 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1184 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001185 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001186 if (response_size)
1187 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1188 else
1189 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001190 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001191 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001192 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001193
Greg Clayton4fb400f2010-09-27 21:07:38 +00001194 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001195 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001196
1197 SetPrivateState (eStateDetached);
1198 ResumePrivateStateThread();
1199
1200 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001201 return error;
1202}
Chris Lattner24943d22010-06-08 16:52:24 +00001203
1204Error
1205ProcessGDBRemote::DoDestroy ()
1206{
1207 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001208 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001209 if (log)
1210 log->Printf ("ProcessGDBRemote::DoDestroy()");
1211
1212 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001213 Mutex::Locker locker;
1214 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001215 DisableAllBreakpointSites ();
1216 SetExitStatus(-1, "process killed");
1217
1218 StringExtractorGDBRemote response;
Greg Claytonb749a262010-12-03 06:02:24 +00001219 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 1, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001220 {
Caroline Tice926060e2010-10-29 21:48:37 +00001221 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001222 if (log)
1223 {
1224 if (response.IsOKPacket())
1225 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1226 else
1227 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1228 }
1229 }
1230
1231 StopAsyncThread ();
1232 m_gdb_comm.StopReadThread();
1233 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001234 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001235 return error;
1236}
1237
Chris Lattner24943d22010-06-08 16:52:24 +00001238//------------------------------------------------------------------
1239// Process Queries
1240//------------------------------------------------------------------
1241
1242bool
1243ProcessGDBRemote::IsAlive ()
1244{
1245 return m_gdb_comm.IsConnected();
1246}
1247
1248addr_t
1249ProcessGDBRemote::GetImageInfoAddress()
1250{
1251 if (!m_gdb_comm.IsRunning())
1252 {
1253 StringExtractorGDBRemote response;
1254 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1255 {
1256 if (response.IsNormalPacket())
1257 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1258 }
1259 }
1260 return LLDB_INVALID_ADDRESS;
1261}
1262
1263DynamicLoader *
1264ProcessGDBRemote::GetDynamicLoader()
1265{
1266 return m_dynamic_loader_ap.get();
1267}
1268
1269//------------------------------------------------------------------
1270// Process Memory
1271//------------------------------------------------------------------
1272size_t
1273ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1274{
1275 if (size > m_max_memory_size)
1276 {
1277 // Keep memory read sizes down to a sane limit. This function will be
1278 // called multiple times in order to complete the task by
1279 // lldb_private::Process so it is ok to do this.
1280 size = m_max_memory_size;
1281 }
1282
1283 char packet[64];
1284 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1285 assert (packet_len + 1 < sizeof(packet));
1286 StringExtractorGDBRemote response;
1287 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1288 {
1289 if (response.IsNormalPacket())
1290 {
1291 error.Clear();
1292 return response.GetHexBytes(buf, size, '\xdd');
1293 }
1294 else if (response.IsErrorPacket())
1295 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1296 else if (response.IsUnsupportedPacket())
1297 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1298 else
1299 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1300 }
1301 else
1302 {
1303 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1304 }
1305 return 0;
1306}
1307
1308size_t
1309ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1310{
1311 StreamString packet;
1312 packet.Printf("M%llx,%zx:", addr, size);
1313 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1314 StringExtractorGDBRemote response;
1315 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1316 {
1317 if (response.IsOKPacket())
1318 {
1319 error.Clear();
1320 return size;
1321 }
1322 else if (response.IsErrorPacket())
1323 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1324 else if (response.IsUnsupportedPacket())
1325 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1326 else
1327 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1328 }
1329 else
1330 {
1331 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1332 }
1333 return 0;
1334}
1335
1336lldb::addr_t
1337ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1338{
1339 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1340 if (allocated_addr == LLDB_INVALID_ADDRESS)
1341 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1342 else
1343 error.Clear();
1344 return allocated_addr;
1345}
1346
1347Error
1348ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1349{
1350 Error error;
1351 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1352 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1353 return error;
1354}
1355
1356
1357//------------------------------------------------------------------
1358// Process STDIO
1359//------------------------------------------------------------------
1360
1361size_t
1362ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1363{
1364 Mutex::Locker locker(m_stdio_mutex);
1365 size_t bytes_available = m_stdout_data.size();
1366 if (bytes_available > 0)
1367 {
1368 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1369 if (bytes_available > buf_size)
1370 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001371 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001372 m_stdout_data.erase(0, buf_size);
1373 bytes_available = buf_size;
1374 }
1375 else
1376 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001377 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001378 m_stdout_data.clear();
1379
1380 //ResetEventBits(eBroadcastBitSTDOUT);
1381 }
1382 }
1383 return bytes_available;
1384}
1385
1386size_t
1387ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1388{
1389 // Can we get STDERR through the remote protocol?
1390 return 0;
1391}
1392
1393size_t
1394ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1395{
1396 if (m_stdio_communication.IsConnected())
1397 {
1398 ConnectionStatus status;
1399 m_stdio_communication.Write(src, src_len, status, NULL);
1400 }
1401 return 0;
1402}
1403
1404Error
1405ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1406{
1407 Error error;
1408 assert (bp_site != NULL);
1409
Greg Claytone005f2c2010-11-06 01:53:30 +00001410 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001411 user_id_t site_id = bp_site->GetID();
1412 const addr_t addr = bp_site->GetLoadAddress();
1413 if (log)
1414 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1415
1416 if (bp_site->IsEnabled())
1417 {
1418 if (log)
1419 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1420 return error;
1421 }
1422 else
1423 {
1424 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1425
1426 if (bp_site->HardwarePreferred())
1427 {
1428 // Try and set hardware breakpoint, and if that fails, fall through
1429 // and set a software breakpoint?
1430 }
1431
1432 if (m_z0_supported)
1433 {
1434 char packet[64];
1435 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1436 assert (packet_len + 1 < sizeof(packet));
1437 StringExtractorGDBRemote response;
1438 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1439 {
1440 if (response.IsUnsupportedPacket())
1441 {
1442 // Disable z packet support and try again
1443 m_z0_supported = 0;
1444 return EnableBreakpoint (bp_site);
1445 }
1446 else if (response.IsOKPacket())
1447 {
1448 bp_site->SetEnabled(true);
1449 bp_site->SetType (BreakpointSite::eExternal);
1450 return error;
1451 }
1452 else
1453 {
1454 uint8_t error_byte = response.GetError();
1455 if (error_byte)
1456 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1457 }
1458 }
1459 }
1460 else
1461 {
1462 return EnableSoftwareBreakpoint (bp_site);
1463 }
1464 }
1465
1466 if (log)
1467 {
1468 const char *err_string = error.AsCString();
1469 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1470 bp_site->GetLoadAddress(),
1471 err_string ? err_string : "NULL");
1472 }
1473 // We shouldn't reach here on a successful breakpoint enable...
1474 if (error.Success())
1475 error.SetErrorToGenericError();
1476 return error;
1477}
1478
1479Error
1480ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1481{
1482 Error error;
1483 assert (bp_site != NULL);
1484 addr_t addr = bp_site->GetLoadAddress();
1485 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001486 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001487 if (log)
1488 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1489
1490 if (bp_site->IsEnabled())
1491 {
1492 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1493
1494 if (bp_site->IsHardware())
1495 {
1496 // TODO: disable hardware breakpoint...
1497 }
1498 else
1499 {
1500 if (m_z0_supported)
1501 {
1502 char packet[64];
1503 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1504 assert (packet_len + 1 < sizeof(packet));
1505 StringExtractorGDBRemote response;
1506 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1507 {
1508 if (response.IsUnsupportedPacket())
1509 {
1510 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1511 }
1512 else if (response.IsOKPacket())
1513 {
1514 if (log)
1515 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1516 bp_site->SetEnabled(false);
1517 return error;
1518 }
1519 else
1520 {
1521 uint8_t error_byte = response.GetError();
1522 if (error_byte)
1523 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1524 }
1525 }
1526 }
1527 else
1528 {
1529 return DisableSoftwareBreakpoint (bp_site);
1530 }
1531 }
1532 }
1533 else
1534 {
1535 if (log)
1536 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1537 return error;
1538 }
1539
1540 if (error.Success())
1541 error.SetErrorToGenericError();
1542 return error;
1543}
1544
1545Error
1546ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1547{
1548 Error error;
1549 if (wp)
1550 {
1551 user_id_t watchID = wp->GetID();
1552 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001553 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001554 if (log)
1555 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1556 if (wp->IsEnabled())
1557 {
1558 if (log)
1559 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1560 return error;
1561 }
1562 else
1563 {
1564 // Pass down an appropriate z/Z packet...
1565 error.SetErrorString("watchpoints not supported");
1566 }
1567 }
1568 else
1569 {
1570 error.SetErrorString("Watchpoint location argument was NULL.");
1571 }
1572 if (error.Success())
1573 error.SetErrorToGenericError();
1574 return error;
1575}
1576
1577Error
1578ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1579{
1580 Error error;
1581 if (wp)
1582 {
1583 user_id_t watchID = wp->GetID();
1584
Greg Claytone005f2c2010-11-06 01:53:30 +00001585 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001586
1587 addr_t addr = wp->GetLoadAddress();
1588 if (log)
1589 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1590
1591 if (wp->IsHardware())
1592 {
1593 // Pass down an appropriate z/Z packet...
1594 error.SetErrorString("watchpoints not supported");
1595 }
1596 // TODO: clear software watchpoints if we implement them
1597 }
1598 else
1599 {
1600 error.SetErrorString("Watchpoint location argument was NULL.");
1601 }
1602 if (error.Success())
1603 error.SetErrorToGenericError();
1604 return error;
1605}
1606
1607void
1608ProcessGDBRemote::Clear()
1609{
1610 m_flags = 0;
1611 m_thread_list.Clear();
1612 {
1613 Mutex::Locker locker(m_stdio_mutex);
1614 m_stdout_data.clear();
1615 }
1616 DestoryLibUnwindAddressSpace();
1617}
1618
1619Error
1620ProcessGDBRemote::DoSignal (int signo)
1621{
1622 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001623 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001624 if (log)
1625 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1626
1627 if (!m_gdb_comm.SendAsyncSignal (signo))
1628 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1629 return error;
1630}
1631
Caroline Tice861efb32010-11-16 05:07:41 +00001632//void
1633//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1634//{
1635// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1636// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1637//}
Chris Lattner24943d22010-06-08 16:52:24 +00001638
Caroline Tice861efb32010-11-16 05:07:41 +00001639//void
1640//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1641//{
1642// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1643// Mutex::Locker locker(m_stdio_mutex);
1644// m_stdout_data.append(s, len);
1645//
1646// // FIXME: Make a real data object for this and put it out.
1647// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1648//}
Chris Lattner24943d22010-06-08 16:52:24 +00001649
1650
1651Error
1652ProcessGDBRemote::StartDebugserverProcess
1653(
1654 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1655 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1656 char const *inferior_envp[], // Environment to pass along to the inferior program
1657 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001658 bool launch_process, // Set to true if we are going to be launching a the process
1659 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 +00001660 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1661 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Clayton23cf0c72010-11-08 04:29:11 +00001662 bool disable_aslr, // Disable ASLR
Chris Lattner24943d22010-06-08 16:52:24 +00001663 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1664)
1665{
1666 Error error;
1667 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1668 {
1669 // If we locate debugserver, keep that located version around
1670 static FileSpec g_debugserver_file_spec;
1671
1672 FileSpec debugserver_file_spec;
1673 char debugserver_path[PATH_MAX];
1674
1675 // Always check to see if we have an environment override for the path
1676 // to the debugserver to use and use it if we do.
1677 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1678 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001679 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001680 else
1681 debugserver_file_spec = g_debugserver_file_spec;
1682 bool debugserver_exists = debugserver_file_spec.Exists();
1683 if (!debugserver_exists)
1684 {
1685 // The debugserver binary is in the LLDB.framework/Resources
1686 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001687 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001688 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001689 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001690 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001691 if (debugserver_exists)
1692 {
1693 g_debugserver_file_spec = debugserver_file_spec;
1694 }
1695 else
1696 {
1697 g_debugserver_file_spec.Clear();
1698 debugserver_file_spec.Clear();
1699 }
Chris Lattner24943d22010-06-08 16:52:24 +00001700 }
1701 }
1702
1703 if (debugserver_exists)
1704 {
1705 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1706
1707 m_stdio_communication.Clear();
1708 posix_spawnattr_t attr;
1709
Greg Claytone005f2c2010-11-06 01:53:30 +00001710 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001711
1712 Error local_err; // Errors that don't affect the spawning.
1713 if (log)
1714 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1715 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1716 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001717 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001718 if (error.Fail())
1719 return error;;
1720
1721#if !defined (__arm__)
1722
Greg Clayton24b48ff2010-10-17 22:03:32 +00001723 // We don't need to do this for ARM, and we really shouldn't now
1724 // that we have multiple CPU subtypes and no posix_spawnattr call
1725 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001726 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001727 {
Greg Claytoncf015052010-06-11 03:25:34 +00001728 cpu_type_t cpu = inferior_arch.GetCPUType();
1729 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1730 {
1731 size_t ocount = 0;
1732 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1733 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001734 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 +00001735
Greg Claytoncf015052010-06-11 03:25:34 +00001736 if (error.Fail() != 0 || ocount != 1)
1737 return error;
1738 }
Chris Lattner24943d22010-06-08 16:52:24 +00001739 }
1740
1741#endif
1742
1743 Args debugserver_args;
1744 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001745
Chris Lattner24943d22010-06-08 16:52:24 +00001746 lldb_utility::PseudoTerminal pty;
Greg Clayton23cf0c72010-11-08 04:29:11 +00001747 if (launch_process && stdio_path == NULL && m_local_debugserver)
Chris Lattner24943d22010-06-08 16:52:24 +00001748 {
Chris Lattner24943d22010-06-08 16:52:24 +00001749 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001750 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001751 }
1752
1753 // Start args with "debugserver /file/path -r --"
1754 debugserver_args.AppendArgument(debugserver_path);
1755 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001756 // use native registers, not the GDB registers
1757 debugserver_args.AppendArgument("--native-regs");
1758 // make debugserver run in its own session so signals generated by
1759 // special terminal key sequences (^C) don't affect debugserver
1760 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001761
Greg Clayton452bf612010-08-31 18:35:14 +00001762 if (disable_aslr)
1763 debugserver_args.AppendArguments("--disable-aslr");
1764
Chris Lattner24943d22010-06-08 16:52:24 +00001765 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001766 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001767 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001768 debugserver_args.AppendArgument("--stdio-path");
1769 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001770 }
1771
1772 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1773 if (env_debugserver_log_file)
1774 {
1775 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1776 debugserver_args.AppendArgument(arg_cstr);
1777 }
1778
1779 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1780 if (env_debugserver_log_flags)
1781 {
1782 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1783 debugserver_args.AppendArgument(arg_cstr);
1784 }
1785// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1786// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1787
1788 // Now append the program arguments
1789 if (launch_process)
1790 {
1791 if (inferior_argv)
1792 {
1793 // Terminate the debugserver args so we can now append the inferior args
1794 debugserver_args.AppendArgument("--");
1795
1796 for (int i = 0; inferior_argv[i] != NULL; ++i)
1797 debugserver_args.AppendArgument (inferior_argv[i]);
1798 }
1799 else
1800 {
1801 // Will send environment entries with the 'QEnvironment:' packet
1802 // Will send arguments with the 'A' packet
1803 }
1804 }
1805 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1806 {
1807 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1808 debugserver_args.AppendArgument (arg_cstr);
1809 }
1810 else if (attach_name && attach_name[0])
1811 {
1812 if (wait_for_launch)
1813 debugserver_args.AppendArgument ("--waitfor");
1814 else
1815 debugserver_args.AppendArgument ("--attach");
1816 debugserver_args.AppendArgument (attach_name);
1817 }
1818
1819 Error file_actions_err;
1820 posix_spawn_file_actions_t file_actions;
1821#if DONT_CLOSE_DEBUGSERVER_STDIO
1822 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1823#else
1824 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1825 if (file_actions_err.Success())
1826 {
1827 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1828 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1829 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1830 }
1831#endif
1832
1833 if (log)
1834 {
1835 StreamString strm;
1836 debugserver_args.Dump (&strm);
1837 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1838 }
1839
1840 error.SetError(::posix_spawnp (&m_debugserver_pid,
1841 debugserver_path,
1842 file_actions_err.Success() ? &file_actions : NULL,
1843 &attr,
1844 debugserver_args.GetArgumentVector(),
1845 (char * const*)inferior_envp),
1846 eErrorTypePOSIX);
1847
Greg Claytone9d0df42010-07-02 01:29:13 +00001848
1849 ::posix_spawnattr_destroy (&attr);
1850
Chris Lattner24943d22010-06-08 16:52:24 +00001851 if (file_actions_err.Success())
1852 ::posix_spawn_file_actions_destroy (&file_actions);
1853
1854 // We have seen some cases where posix_spawnp was returning a valid
1855 // looking pid even when an error was returned, so clear it out
1856 if (error.Fail())
1857 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1858
1859 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001860 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 +00001861
Caroline Tice91a1dab2010-11-05 22:37:44 +00001862 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1863 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001864 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001865 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001866 }
Chris Lattner24943d22010-06-08 16:52:24 +00001867 }
1868 else
1869 {
1870 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1871 }
1872
1873 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1874 StartAsyncThread ();
1875 }
1876 return error;
1877}
1878
1879bool
1880ProcessGDBRemote::MonitorDebugserverProcess
1881(
1882 void *callback_baton,
1883 lldb::pid_t debugserver_pid,
1884 int signo, // Zero for no signal
1885 int exit_status // Exit value of process if signal is zero
1886)
1887{
1888 // We pass in the ProcessGDBRemote inferior process it and name it
1889 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1890 // pointer value itself, thus we need the double cast...
1891
1892 // "debugserver_pid" argument passed in is the process ID for
1893 // debugserver that we are tracking...
1894
Greg Clayton75ccf502010-08-21 02:22:51 +00001895 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1896
1897 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001898 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001899 // Sleep for a half a second to make sure our inferior process has
1900 // time to set its exit status before we set it incorrectly when
1901 // both the debugserver and the inferior process shut down.
1902 usleep (500000);
1903 // If our process hasn't yet exited, debugserver might have died.
1904 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001905 const StateType state = process->GetState();
1906
1907 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1908 state != eStateInvalid &&
1909 state != eStateUnloaded &&
1910 state != eStateExited &&
1911 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001912 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001913 char error_str[1024];
1914 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001915 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001916 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1917 if (signal_cstr)
1918 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001919 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001920 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001921 }
1922 else
1923 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001924 ::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 +00001925 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001926
1927 process->SetExitStatus (-1, error_str);
1928 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001929 // Debugserver has exited we need to let our ProcessGDBRemote
1930 // know that it no longer has a debugserver instance
1931 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1932 // We are returning true to this function below, so we can
1933 // forget about the monitor handle.
1934 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001935 }
1936 return true;
1937}
1938
1939void
1940ProcessGDBRemote::KillDebugserverProcess ()
1941{
1942 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1943 {
1944 ::kill (m_debugserver_pid, SIGINT);
1945 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1946 }
1947}
1948
1949void
1950ProcessGDBRemote::Initialize()
1951{
1952 static bool g_initialized = false;
1953
1954 if (g_initialized == false)
1955 {
1956 g_initialized = true;
1957 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1958 GetPluginDescriptionStatic(),
1959 CreateInstance);
1960
1961 Log::Callbacks log_callbacks = {
1962 ProcessGDBRemoteLog::DisableLog,
1963 ProcessGDBRemoteLog::EnableLog,
1964 ProcessGDBRemoteLog::ListLogCategories
1965 };
1966
1967 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1968 }
1969}
1970
1971bool
1972ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1973{
1974 if (m_curr_tid == tid)
1975 return true;
1976
1977 char packet[32];
1978 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1979 assert (packet_len + 1 < sizeof(packet));
1980 StringExtractorGDBRemote response;
1981 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1982 {
1983 if (response.IsOKPacket())
1984 {
1985 m_curr_tid = tid;
1986 return true;
1987 }
1988 }
1989 return false;
1990}
1991
1992bool
1993ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
1994{
1995 if (m_curr_tid_run == tid)
1996 return true;
1997
1998 char packet[32];
1999 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2000 assert (packet_len + 1 < sizeof(packet));
2001 StringExtractorGDBRemote response;
2002 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2003 {
2004 if (response.IsOKPacket())
2005 {
2006 m_curr_tid_run = tid;
2007 return true;
2008 }
2009 }
2010 return false;
2011}
2012
2013void
2014ProcessGDBRemote::ResetGDBRemoteState ()
2015{
2016 // Reset and GDB remote state
2017 m_curr_tid = LLDB_INVALID_THREAD_ID;
2018 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2019 m_z0_supported = 1;
2020}
2021
2022
2023bool
2024ProcessGDBRemote::StartAsyncThread ()
2025{
2026 ResetGDBRemoteState ();
2027
Greg Claytone005f2c2010-11-06 01:53:30 +00002028 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002029
2030 if (log)
2031 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2032
2033 // Create a thread that watches our internal state and controls which
2034 // events make it to clients (into the DCProcess event queue).
2035 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2036 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2037}
2038
2039void
2040ProcessGDBRemote::StopAsyncThread ()
2041{
Greg Claytone005f2c2010-11-06 01:53:30 +00002042 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002043
2044 if (log)
2045 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2046
2047 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2048
2049 // Stop the stdio thread
2050 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2051 {
2052 Host::ThreadJoin (m_async_thread, NULL, NULL);
2053 }
2054}
2055
2056
2057void *
2058ProcessGDBRemote::AsyncThread (void *arg)
2059{
2060 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2061
Greg Claytone005f2c2010-11-06 01:53:30 +00002062 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002063 if (log)
2064 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2065
2066 Listener listener ("ProcessGDBRemote::AsyncThread");
2067 EventSP event_sp;
2068 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2069 eBroadcastBitAsyncThreadShouldExit;
2070
2071 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2072 {
2073 bool done = false;
2074 while (!done)
2075 {
Caroline Tice926060e2010-10-29 21:48:37 +00002076 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002077 if (log)
2078 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2079 if (listener.WaitForEvent (NULL, event_sp))
2080 {
2081 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002082 if (log)
2083 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2084
Chris Lattner24943d22010-06-08 16:52:24 +00002085 switch (event_type)
2086 {
2087 case eBroadcastBitAsyncContinue:
2088 {
2089 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2090
2091 if (continue_packet)
2092 {
2093 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2094 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002095 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002096 if (log)
2097 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2098
2099 process->SetPrivateState(eStateRunning);
2100 StringExtractorGDBRemote response;
2101 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2102
2103 switch (stop_state)
2104 {
2105 case eStateStopped:
2106 case eStateCrashed:
2107 case eStateSuspended:
2108 process->m_last_stop_packet = response;
2109 process->m_last_stop_packet.SetFilePos (0);
2110 process->SetPrivateState (stop_state);
2111 break;
2112
2113 case eStateExited:
2114 process->m_last_stop_packet = response;
2115 process->m_last_stop_packet.SetFilePos (0);
2116 response.SetFilePos(1);
2117 process->SetExitStatus(response.GetHexU8(), NULL);
2118 done = true;
2119 break;
2120
2121 case eStateInvalid:
2122 break;
2123
2124 default:
2125 process->SetPrivateState (stop_state);
2126 break;
2127 }
2128 }
2129 }
2130 break;
2131
2132 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002133 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002134 if (log)
2135 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2136 done = true;
2137 break;
2138
2139 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002140 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002141 if (log)
2142 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2143 done = true;
2144 break;
2145 }
2146 }
2147 else
2148 {
Caroline Tice926060e2010-10-29 21:48:37 +00002149 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002150 if (log)
2151 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2152 done = true;
2153 }
2154 }
2155 }
2156
Caroline Tice926060e2010-10-29 21:48:37 +00002157 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002158 if (log)
2159 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2160
2161 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2162 return NULL;
2163}
2164
2165lldb_private::unw_addr_space_t
2166ProcessGDBRemote::GetLibUnwindAddressSpace ()
2167{
2168 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002169
2170 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2171 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002172 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002173 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002174 target_type = UNW_TARGET_X86_64;
2175
2176 if (m_libunwind_addr_space)
2177 {
2178 if (m_libunwind_target_type != target_type)
2179 DestoryLibUnwindAddressSpace();
2180 else
2181 return m_libunwind_addr_space;
2182 }
2183 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2184 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2185 if (m_libunwind_addr_space)
2186 m_libunwind_target_type = target_type;
2187 else
2188 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2189 return m_libunwind_addr_space;
2190}
2191
2192void
2193ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2194{
2195 if (m_libunwind_addr_space)
2196 {
2197 unw_destroy_addr_space (m_libunwind_addr_space);
2198 m_libunwind_addr_space = NULL;
2199 }
2200 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2201}
2202
2203
2204const char *
2205ProcessGDBRemote::GetDispatchQueueNameForThread
2206(
2207 addr_t thread_dispatch_qaddr,
2208 std::string &dispatch_queue_name
2209)
2210{
2211 dispatch_queue_name.clear();
2212 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2213 {
2214 // Cache the dispatch_queue_offsets_addr value so we don't always have
2215 // to look it up
2216 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2217 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002218 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2219 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002220 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002221 if (module_sp)
2222 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2223
2224 if (dispatch_queue_offsets_symbol == NULL)
2225 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002226 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002227 if (module_sp)
2228 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2229 }
Chris Lattner24943d22010-06-08 16:52:24 +00002230 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002231 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002232
2233 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2234 return NULL;
2235 }
2236
2237 uint8_t memory_buffer[8];
2238 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2239
2240 // Excerpt from src/queue_private.h
2241 struct dispatch_queue_offsets_s
2242 {
2243 uint16_t dqo_version;
2244 uint16_t dqo_label;
2245 uint16_t dqo_label_size;
2246 } dispatch_queue_offsets;
2247
2248
2249 Error error;
2250 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2251 {
2252 uint32_t data_offset = 0;
2253 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2254 {
2255 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2256 {
2257 data_offset = 0;
2258 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2259 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2260 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2261 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2262 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2263 dispatch_queue_name.erase (bytes_read);
2264 }
2265 }
2266 }
2267 }
2268 if (dispatch_queue_name.empty())
2269 return NULL;
2270 return dispatch_queue_name.c_str();
2271}
2272
Jim Ingham7508e732010-08-09 23:31:02 +00002273uint32_t
2274ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2275{
2276 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2277 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2278 if (m_local_debugserver)
2279 {
2280 return Host::ListProcessesMatchingName (name, matches, pids);
2281 }
2282 else
2283 {
2284 // FIXME: Implement talking to the remote debugserver.
2285 return 0;
2286 }
2287
2288}