blob: fcbd523699fbb0e16d0d7ba857c37398102af886 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Chris Lattner24943d22010-06-08 16:52:24 +000013#include <sys/types.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <sys/stat.h>
Chris Lattner24943d22010-06-08 16:52:24 +000015
16// C++ Includes
17#include <algorithm>
18#include <map>
19
20// Other libraries and framework includes
21
22#include "lldb/Breakpoint/WatchpointLocation.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000023#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/ArchSpec.h"
25#include "lldb/Core/Debugger.h"
26#include "lldb/Core/ConnectionFileDescriptor.h"
27#include "lldb/Core/FileSpec.h"
28#include "lldb/Core/InputReader.h"
29#include "lldb/Core/Module.h"
30#include "lldb/Core/PluginManager.h"
31#include "lldb/Core/State.h"
32#include "lldb/Core/StreamString.h"
33#include "lldb/Core/Timer.h"
34#include "lldb/Host/TimeValue.h"
35#include "lldb/Symbol/ObjectFile.h"
36#include "lldb/Target/DynamicLoader.h"
37#include "lldb/Target/Target.h"
38#include "lldb/Target/TargetList.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000039#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
41// Project includes
42#include "lldb/Host/Host.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000043#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "GDBRemoteRegisterContext.h"
45#include "ProcessGDBRemote.h"
46#include "ProcessGDBRemoteLog.h"
47#include "ThreadGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000048#include "MacOSXLibunwindCallbacks.h"
Greg Clayton643ee732010-08-04 01:40:35 +000049#include "StopInfoMachException.h"
50
Chris Lattner24943d22010-06-08 16:52:24 +000051
Chris Lattner24943d22010-06-08 16:52:24 +000052
53#define DEBUGSERVER_BASENAME "debugserver"
54using namespace lldb;
55using namespace lldb_private;
56
57static inline uint16_t
58get_random_port ()
59{
60 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u;
61}
62
63
64const char *
65ProcessGDBRemote::GetPluginNameStatic()
66{
67 return "process.gdb-remote";
68}
69
70const char *
71ProcessGDBRemote::GetPluginDescriptionStatic()
72{
73 return "GDB Remote protocol based debugging plug-in.";
74}
75
76void
77ProcessGDBRemote::Terminate()
78{
79 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
80}
81
82
83Process*
84ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
85{
86 return new ProcessGDBRemote (target, listener);
87}
88
89bool
90ProcessGDBRemote::CanDebug(Target &target)
91{
92 // For now we are just making sure the file exists for a given module
93 ModuleSP exe_module_sp(target.GetExecutableModule());
94 if (exe_module_sp.get())
95 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +000096 // However, if there is no executable module, we return true since we might be preparing to attach.
97 return true;
Chris Lattner24943d22010-06-08 16:52:24 +000098}
99
100//----------------------------------------------------------------------
101// ProcessGDBRemote constructor
102//----------------------------------------------------------------------
103ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
104 Process (target, listener),
105 m_dynamic_loader_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000106 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000107 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000108 m_byte_order (eByteOrderHost),
Chris Lattner24943d22010-06-08 16:52:24 +0000109 m_gdb_comm(),
110 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000111 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000112 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000113 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000114 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
115 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000116 m_curr_tid (LLDB_INVALID_THREAD_ID),
117 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000118 m_z0_supported (1),
119 m_continue_packet(),
120 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000121 m_packet_timeout (1),
122 m_max_memory_size (512),
Chris Lattner24943d22010-06-08 16:52:24 +0000123 m_libunwind_target_type (UNW_TARGET_UNSPECIFIED),
124 m_libunwind_addr_space (NULL),
Jim Ingham7508e732010-08-09 23:31:02 +0000125 m_waiting_for_attach (false),
126 m_local_debugserver (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000127{
128}
129
130//----------------------------------------------------------------------
131// Destructor
132//----------------------------------------------------------------------
133ProcessGDBRemote::~ProcessGDBRemote()
134{
Greg Clayton75ccf502010-08-21 02:22:51 +0000135 if (m_debugserver_thread != LLDB_INVALID_HOST_THREAD)
136 {
137 Host::ThreadCancel (m_debugserver_thread, NULL);
138 thread_result_t thread_result;
139 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
140 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
141 }
Chris Lattner24943d22010-06-08 16:52:24 +0000142 // m_mach_process.UnregisterNotificationCallbacks (this);
143 Clear();
144}
145
146//----------------------------------------------------------------------
147// PluginInterface
148//----------------------------------------------------------------------
149const char *
150ProcessGDBRemote::GetPluginName()
151{
152 return "Process debugging plug-in that uses the GDB remote protocol";
153}
154
155const char *
156ProcessGDBRemote::GetShortPluginName()
157{
158 return GetPluginNameStatic();
159}
160
161uint32_t
162ProcessGDBRemote::GetPluginVersion()
163{
164 return 1;
165}
166
167void
168ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
169{
170 strm->Printf("TODO: fill this in\n");
171}
172
173Error
174ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
175{
176 Error error;
177 error.SetErrorString("No plug-in commands are currently supported.");
178 return error;
179}
180
181Log *
182ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
183{
184 return NULL;
185}
186
187void
188ProcessGDBRemote::BuildDynamicRegisterInfo ()
189{
190 char register_info_command[64];
191 m_register_info.Clear();
192 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
193 uint32_t reg_offset = 0;
194 uint32_t reg_num = 0;
195 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
196 {
197 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
198 StringExtractorGDBRemote response;
199 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
200 {
201 packet_type = response.GetType();
202 if (packet_type == StringExtractorGDBRemote::eResponse)
203 {
204 std::string name;
205 std::string value;
206 ConstString reg_name;
207 ConstString alt_name;
208 ConstString set_name;
209 RegisterInfo reg_info = { NULL, // Name
210 NULL, // Alt name
211 0, // byte size
212 reg_offset, // offset
213 eEncodingUint, // encoding
214 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000215 {
216 LLDB_INVALID_REGNUM, // GCC reg num
217 LLDB_INVALID_REGNUM, // DWARF reg num
218 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000219 reg_num, // GDB reg num
220 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000221 }
222 };
223
224 while (response.GetNameColonValue(name, value))
225 {
226 if (name.compare("name") == 0)
227 {
228 reg_name.SetCString(value.c_str());
229 }
230 else if (name.compare("alt-name") == 0)
231 {
232 alt_name.SetCString(value.c_str());
233 }
234 else if (name.compare("bitsize") == 0)
235 {
236 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
237 }
238 else if (name.compare("offset") == 0)
239 {
240 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000241 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000242 {
243 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000244 }
245 }
246 else if (name.compare("encoding") == 0)
247 {
248 if (value.compare("uint") == 0)
249 reg_info.encoding = eEncodingUint;
250 else if (value.compare("sint") == 0)
251 reg_info.encoding = eEncodingSint;
252 else if (value.compare("ieee754") == 0)
253 reg_info.encoding = eEncodingIEEE754;
254 else if (value.compare("vector") == 0)
255 reg_info.encoding = eEncodingVector;
256 }
257 else if (name.compare("format") == 0)
258 {
259 if (value.compare("binary") == 0)
260 reg_info.format = eFormatBinary;
261 else if (value.compare("decimal") == 0)
262 reg_info.format = eFormatDecimal;
263 else if (value.compare("hex") == 0)
264 reg_info.format = eFormatHex;
265 else if (value.compare("float") == 0)
266 reg_info.format = eFormatFloat;
267 else if (value.compare("vector-sint8") == 0)
268 reg_info.format = eFormatVectorOfSInt8;
269 else if (value.compare("vector-uint8") == 0)
270 reg_info.format = eFormatVectorOfUInt8;
271 else if (value.compare("vector-sint16") == 0)
272 reg_info.format = eFormatVectorOfSInt16;
273 else if (value.compare("vector-uint16") == 0)
274 reg_info.format = eFormatVectorOfUInt16;
275 else if (value.compare("vector-sint32") == 0)
276 reg_info.format = eFormatVectorOfSInt32;
277 else if (value.compare("vector-uint32") == 0)
278 reg_info.format = eFormatVectorOfUInt32;
279 else if (value.compare("vector-float32") == 0)
280 reg_info.format = eFormatVectorOfFloat32;
281 else if (value.compare("vector-uint128") == 0)
282 reg_info.format = eFormatVectorOfUInt128;
283 }
284 else if (name.compare("set") == 0)
285 {
286 set_name.SetCString(value.c_str());
287 }
288 else if (name.compare("gcc") == 0)
289 {
290 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
291 }
292 else if (name.compare("dwarf") == 0)
293 {
294 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
295 }
296 else if (name.compare("generic") == 0)
297 {
298 if (value.compare("pc") == 0)
299 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
300 else if (value.compare("sp") == 0)
301 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
302 else if (value.compare("fp") == 0)
303 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
304 else if (value.compare("ra") == 0)
305 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
306 else if (value.compare("flags") == 0)
307 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
308 }
309 }
310
Jason Molenda53d96862010-06-11 23:44:18 +0000311 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000312 assert (reg_info.byte_size != 0);
313 reg_offset += reg_info.byte_size;
314 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
315 }
316 }
317 else
318 {
319 packet_type = StringExtractorGDBRemote::eError;
320 }
321 }
322
323 if (reg_num == 0)
324 {
325 // We didn't get anything. See if we are debugging ARM and fill with
326 // a hard coded register set until we can get an updated debugserver
327 // down on the devices.
328 ArchSpec arm_arch ("arm");
329 if (GetTarget().GetArchitecture() == arm_arch)
330 m_register_info.HardcodeARMRegisters();
331 }
332 m_register_info.Finalize ();
333}
334
335Error
336ProcessGDBRemote::WillLaunch (Module* module)
337{
338 return WillLaunchOrAttach ();
339}
340
341Error
342ProcessGDBRemote::WillAttach (lldb::pid_t pid)
343{
344 return WillLaunchOrAttach ();
345}
346
347Error
348ProcessGDBRemote::WillAttach (const char *process_name, bool wait_for_launch)
349{
350 return WillLaunchOrAttach ();
351}
352
353Error
354ProcessGDBRemote::WillLaunchOrAttach ()
355{
356 Error error;
357 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
358 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
359
360 if (m_dynamic_loader_ap.get() == NULL)
361 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
362 m_stdio_communication.Clear ();
363
364 return error;
365}
366
367//----------------------------------------------------------------------
368// Process Control
369//----------------------------------------------------------------------
370Error
371ProcessGDBRemote::DoLaunch
372(
373 Module* module,
374 char const *argv[],
375 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000376 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000377 const char *stdin_path,
378 const char *stdout_path,
379 const char *stderr_path
380)
381{
Greg Clayton4b407112010-09-30 21:49:03 +0000382 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000383 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
384 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
385 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000386
387 ObjectFile * object_file = module->GetObjectFile();
388 if (object_file)
389 {
390 ArchSpec inferior_arch(module->GetArchitecture());
391 char host_port[128];
392 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
393
Greg Clayton23cf0c72010-11-08 04:29:11 +0000394 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000395 bool start_debugserver_with_inferior_args = false;
396 if (start_debugserver_with_inferior_args)
397 {
398 // We want to launch debugserver with the inferior program and its
399 // arguments on the command line. We should only do this if we
400 // the GDB server we are talking to doesn't support the 'A' packet.
401 error = StartDebugserverProcess (host_port,
402 argv,
403 envp,
404 NULL, //stdin_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000405 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000406 LLDB_INVALID_PROCESS_ID,
407 NULL, false,
Benjamin Kramer2653be92010-09-03 18:20:07 +0000408 (launch_flags & eLaunchFlagDisableASLR) != 0,
Chris Lattner24943d22010-06-08 16:52:24 +0000409 inferior_arch);
410 if (error.Fail())
411 return error;
412
413 error = ConnectToDebugserver (host_port);
414 if (error.Success())
415 {
416 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
417 }
418 }
419 else
420 {
421 error = StartDebugserverProcess (host_port,
422 NULL,
423 NULL,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000424 NULL, //stdin_path
425 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000426 LLDB_INVALID_PROCESS_ID,
427 NULL, false,
Benjamin Kramer2653be92010-09-03 18:20:07 +0000428 (launch_flags & eLaunchFlagDisableASLR) != 0,
Chris Lattner24943d22010-06-08 16:52:24 +0000429 inferior_arch);
430 if (error.Fail())
431 return error;
432
433 error = ConnectToDebugserver (host_port);
434 if (error.Success())
435 {
436 // Send the environment and the program + arguments after we connect
437 if (envp)
438 {
439 const char *env_entry;
440 for (int i=0; (env_entry = envp[i]); ++i)
441 {
442 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
443 break;
444 }
445 }
446
Greg Clayton960d6a42010-08-03 00:35:52 +0000447 // FIXME: convert this to use the new set/show variables when they are available
448#if 0
449 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
450 {
451 const uint32_t attach_debugserver_secs = 10;
452 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
453 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
454 {
455 printf ("%i\n", attach_debugserver_secs - i);
456 sleep (1);
457 }
458 }
459#endif
460
Chris Lattner24943d22010-06-08 16:52:24 +0000461 const uint32_t arg_timeout_seconds = 10;
462 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
463 if (arg_packet_err == 0)
464 {
465 std::string error_str;
466 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
467 {
468 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
469 }
470 else
471 {
472 error.SetErrorString (error_str.c_str());
473 }
474 }
475 else
476 {
477 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
478 }
479
480 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
481 }
482 }
483
484 if (GetID() == LLDB_INVALID_PROCESS_ID)
485 {
486 KillDebugserverProcess ();
487 return error;
488 }
489
490 StringExtractorGDBRemote response;
491 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
492 SetPrivateState (SetThreadStopInfo (response));
493
494 }
495 else
496 {
497 // Set our user ID to an invalid process ID.
498 SetID(LLDB_INVALID_PROCESS_ID);
499 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
500 }
Chris Lattner24943d22010-06-08 16:52:24 +0000501 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000502
Chris Lattner24943d22010-06-08 16:52:24 +0000503}
504
505
506Error
507ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
508{
509 Error error;
510 // Sleep and wait a bit for debugserver to start to listen...
511 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
512 if (conn_ap.get())
513 {
514 std::string connect_url("connect://");
515 connect_url.append (host_port);
516 const uint32_t max_retry_count = 50;
517 uint32_t retry_count = 0;
518 while (!m_gdb_comm.IsConnected())
519 {
520 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
521 {
522 m_gdb_comm.SetConnection (conn_ap.release());
523 break;
524 }
525 retry_count++;
526
527 if (retry_count >= max_retry_count)
528 break;
529
530 usleep (100000);
531 }
532 }
533
534 if (!m_gdb_comm.IsConnected())
535 {
536 if (error.Success())
537 error.SetErrorString("not connected to remote gdb server");
538 return error;
539 }
540
541 m_gdb_comm.SetAckMode (true);
542 if (m_gdb_comm.StartReadThread(&error))
543 {
544 // Send an initial ack
545 m_gdb_comm.SendAck('+');
546
547 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000548 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
549 this,
550 m_debugserver_pid,
551 false);
552
Chris Lattner24943d22010-06-08 16:52:24 +0000553 StringExtractorGDBRemote response;
554 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
555 {
556 if (response.IsOKPacket())
557 m_gdb_comm.SetAckMode (false);
558 }
559
560 BuildDynamicRegisterInfo ();
561 }
562 return error;
563}
564
565void
566ProcessGDBRemote::DidLaunchOrAttach ()
567{
568 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
569 if (GetID() == LLDB_INVALID_PROCESS_ID)
570 {
571 m_dynamic_loader_ap.reset();
572 }
573 else
574 {
575 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
576
Jim Ingham7508e732010-08-09 23:31:02 +0000577 Module * exe_module = GetTarget().GetExecutableModule ().get();
Chris Lattner24943d22010-06-08 16:52:24 +0000578 assert(exe_module);
579
Chris Lattner24943d22010-06-08 16:52:24 +0000580 ObjectFile *exe_objfile = exe_module->GetObjectFile();
581 assert(exe_objfile);
582
583 m_byte_order = exe_objfile->GetByteOrder();
584 assert (m_byte_order != eByteOrderInvalid);
585
586 StreamString strm;
587
588 ArchSpec inferior_arch;
589 // See if the GDB server supports the qHostInfo information
590 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
591 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Jim Ingham7508e732010-08-09 23:31:02 +0000592 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000593
Jim Ingham7508e732010-08-09 23:31:02 +0000594 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000595 {
596 // For ARM we can't trust the arch of the process as it could
597 // have an armv6 object file, but be running on armv7 kernel.
598 inferior_arch = m_gdb_comm.GetHostArchitecture();
599 }
600
601 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000602 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000603
604 if (vendor == NULL)
605 vendor = Host::GetVendorString().AsCString("apple");
606
607 if (os_type == NULL)
608 os_type = Host::GetOSString().AsCString("darwin");
609
610 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
611
612 std::transform (strm.GetString().begin(),
613 strm.GetString().end(),
614 strm.GetString().begin(),
615 ::tolower);
616
617 m_target_triple.SetCString(strm.GetString().c_str());
618 }
619}
620
621void
622ProcessGDBRemote::DidLaunch ()
623{
624 DidLaunchOrAttach ();
625 if (m_dynamic_loader_ap.get())
626 m_dynamic_loader_ap->DidLaunch();
627}
628
629Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000630ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000631{
632 Error error;
633 // Clear out and clean up from any current state
634 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000635 ArchSpec arch_spec = GetTarget().GetArchitecture();
636
Greg Claytone005f2c2010-11-06 01:53:30 +0000637 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000638
639
Chris Lattner24943d22010-06-08 16:52:24 +0000640 if (attach_pid != LLDB_INVALID_PROCESS_ID)
641 {
Chris Lattner24943d22010-06-08 16:52:24 +0000642 char host_port[128];
643 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000644 error = StartDebugserverProcess (host_port, // debugserver_url
645 NULL, // inferior_argv
646 NULL, // inferior_envp
647 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000648 false, // launch_process == false (we are attaching)
649 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
650 NULL, // Don't send any attach by process name option to debugserver
651 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Greg Clayton452bf612010-08-31 18:35:14 +0000652 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000653 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000654
655 if (error.Fail())
656 {
657 const char *error_string = error.AsCString();
658 if (error_string == NULL)
659 error_string = "unable to launch " DEBUGSERVER_BASENAME;
660
661 SetExitStatus (-1, error_string);
662 }
663 else
664 {
665 error = ConnectToDebugserver (host_port);
666 if (error.Success())
667 {
668 char packet[64];
669 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
670 StringExtractorGDBRemote response;
671 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
672 packet,
673 packet_len,
674 response);
675 switch (stop_state)
676 {
677 case eStateStopped:
678 case eStateCrashed:
679 case eStateSuspended:
680 SetID (attach_pid);
681 m_last_stop_packet = response;
682 m_last_stop_packet.SetFilePos (0);
683 SetPrivateState (stop_state);
684 break;
685
686 case eStateExited:
687 m_last_stop_packet = response;
688 m_last_stop_packet.SetFilePos (0);
689 response.SetFilePos(1);
690 SetExitStatus(response.GetHexU8(), NULL);
691 break;
692
693 default:
694 SetExitStatus(-1, "unable to attach to process");
695 break;
696 }
697
698 }
699 }
700 }
701
702 lldb::pid_t pid = GetID();
703 if (pid == LLDB_INVALID_PROCESS_ID)
704 {
705 KillDebugserverProcess();
706 }
707 return error;
708}
709
710size_t
711ProcessGDBRemote::AttachInputReaderCallback
712(
713 void *baton,
714 InputReader *reader,
715 lldb::InputReaderAction notification,
716 const char *bytes,
717 size_t bytes_len
718)
719{
720 if (notification == eInputReaderGotToken)
721 {
722 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
723 if (gdb_process->m_waiting_for_attach)
724 gdb_process->m_waiting_for_attach = false;
725 reader->SetIsDone(true);
726 return 1;
727 }
728 return 0;
729}
730
731Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000732ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000733{
734 Error error;
735 // Clear out and clean up from any current state
736 Clear();
737 // HACK: require arch be set correctly at the target level until we can
738 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000739
Greg Claytone005f2c2010-11-06 01:53:30 +0000740 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000741 if (process_name && process_name[0])
742 {
Chris Lattner24943d22010-06-08 16:52:24 +0000743 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000744 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000745 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000746 error = StartDebugserverProcess (host_port, // debugserver_url
747 NULL, // inferior_argv
748 NULL, // inferior_envp
749 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000750 false, // launch_process == false (we are attaching)
751 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
752 NULL, // Don't send any attach by process name option to debugserver
753 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Greg Clayton452bf612010-08-31 18:35:14 +0000754 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000755 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000756 if (error.Fail())
757 {
758 const char *error_string = error.AsCString();
759 if (error_string == NULL)
760 error_string = "unable to launch " DEBUGSERVER_BASENAME;
761
762 SetExitStatus (-1, error_string);
763 }
764 else
765 {
766 error = ConnectToDebugserver (host_port);
767 if (error.Success())
768 {
769 StreamString packet;
770
Chris Lattner24943d22010-06-08 16:52:24 +0000771 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000772 packet.PutCString("vAttachWait");
773 else
774 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000775 packet.PutChar(';');
776 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
777 StringExtractorGDBRemote response;
778 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
779 packet.GetData(),
780 packet.GetSize(),
781 response);
782 switch (stop_state)
783 {
784 case eStateStopped:
785 case eStateCrashed:
786 case eStateSuspended:
787 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
788 m_last_stop_packet = response;
789 m_last_stop_packet.SetFilePos (0);
790 SetPrivateState (stop_state);
791 break;
792
793 case eStateExited:
794 m_last_stop_packet = response;
795 m_last_stop_packet.SetFilePos (0);
796 response.SetFilePos(1);
797 SetExitStatus(response.GetHexU8(), NULL);
798 break;
799
800 default:
801 SetExitStatus(-1, "unable to attach to process");
802 break;
803 }
804 }
805 }
806 }
807
808 lldb::pid_t pid = GetID();
809 if (pid == LLDB_INVALID_PROCESS_ID)
810 {
811 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000812
813 if (error.Success())
814 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000815 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000816
Chris Lattner24943d22010-06-08 16:52:24 +0000817 return error;
818}
819
820//
821// if (wait_for_launch)
822// {
823// InputReaderSP reader_sp (new InputReader());
824// StreamString instructions;
825// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
826// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
827// this, // baton
828// eInputReaderGranularityByte,
829// NULL, // End token
830// false);
831//
832// StringExtractorGDBRemote response;
833// m_waiting_for_attach = true;
834// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
835// while (m_waiting_for_attach)
836// {
837// // Wait for one second for the stop reply packet
838// if (m_gdb_comm.WaitForPacket(response, 1))
839// {
840// // Got some sort of packet, see if it is the stop reply packet?
841// char ch = response.GetChar(0);
842// if (ch == 'T')
843// {
844// m_waiting_for_attach = false;
845// }
846// }
847// else
848// {
849// // Put a period character every second
850// fputc('.', reader_out_fh);
851// }
852// }
853// }
854// }
855// return GetID();
856//}
857
858void
859ProcessGDBRemote::DidAttach ()
860{
Jim Ingham7508e732010-08-09 23:31:02 +0000861 // If we haven't got an executable module yet, then we should make a dynamic loader, and
862 // see if it can find the executable module for us. If we do have an executable module,
863 // make sure it matches the process we've just attached to.
864
865 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
866 if (!m_dynamic_loader_ap.get())
867 {
868 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
869 }
870
Chris Lattner24943d22010-06-08 16:52:24 +0000871 if (m_dynamic_loader_ap.get())
872 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000873
874 Module * new_exe_module = GetTarget().GetExecutableModule().get();
875 if (new_exe_module == NULL)
876 {
877
878 }
879
880 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000881}
882
883Error
884ProcessGDBRemote::WillResume ()
885{
886 m_continue_packet.Clear();
887 // Start the continue packet we will use to run the target. Each thread
888 // will append what it is supposed to be doing to this packet when the
889 // ThreadList::WillResume() is called. If a thread it supposed
890 // to stay stopped, then don't append anything to this string.
891 m_continue_packet.Printf("vCont");
892 return Error();
893}
894
895Error
896ProcessGDBRemote::DoResume ()
897{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000898 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000899 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
900 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
Jim Ingham3ae449a2010-11-17 02:32:00 +0000901 const uint32_t timedout_sec = 1;
902 if (m_gdb_comm.WaitForIsRunning (timedout_sec))
903 {
904 error.SetErrorString("Resume timed out.");
905 }
906 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000907}
908
909size_t
910ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
911{
912 const uint8_t *trap_opcode = NULL;
913 uint32_t trap_opcode_size = 0;
914
915 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
916 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
917 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
918 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
919
Jim Ingham7508e732010-08-09 23:31:02 +0000920 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000921 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000922 {
Greg Claytoncf015052010-06-11 03:25:34 +0000923 case ArchSpec::eCPU_i386:
924 case ArchSpec::eCPU_x86_64:
925 trap_opcode = g_i386_breakpoint_opcode;
926 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
927 break;
928
929 case ArchSpec::eCPU_arm:
930 // TODO: fill this in for ARM. We need to dig up the symbol for
931 // the address in the breakpoint locaiton and figure out if it is
932 // an ARM or Thumb breakpoint.
933 trap_opcode = g_arm_breakpoint_opcode;
934 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
935 break;
936
937 case ArchSpec::eCPU_ppc:
938 case ArchSpec::eCPU_ppc64:
939 trap_opcode = g_ppc_breakpoint_opcode;
940 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
941 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000942
Greg Claytoncf015052010-06-11 03:25:34 +0000943 default:
944 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
945 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000946 }
947
948 if (trap_opcode && trap_opcode_size)
949 {
950 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
951 return trap_opcode_size;
952 }
953 return 0;
954}
955
956uint32_t
957ProcessGDBRemote::UpdateThreadListIfNeeded ()
958{
959 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000960 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000961 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000962 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
963
Greg Clayton5205f0b2010-09-03 17:10:42 +0000964 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000965 const uint32_t stop_id = GetStopID();
966 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
967 {
968 // Update the thread list's stop id immediately so we don't recurse into this function.
969 ThreadList curr_thread_list (this);
970 curr_thread_list.SetStopID(stop_id);
971
972 Error err;
973 StringExtractorGDBRemote response;
974 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
975 response.IsNormalPacket();
976 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
977 {
978 char ch = response.GetChar();
979 if (ch == 'l')
980 break;
981 if (ch == 'm')
982 {
983 do
984 {
985 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
986
987 if (tid != LLDB_INVALID_THREAD_ID)
988 {
989 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
990 if (thread_sp)
991 thread_sp->GetRegisterContext()->Invalidate();
992 else
993 thread_sp.reset (new ThreadGDBRemote (*this, tid));
994 curr_thread_list.AddThread(thread_sp);
995 }
996
997 ch = response.GetChar();
998 } while (ch == ',');
999 }
1000 }
1001
1002 m_thread_list = curr_thread_list;
1003
1004 SetThreadStopInfo (m_last_stop_packet);
1005 }
1006 return GetThreadList().GetSize(false);
1007}
1008
1009
1010StateType
1011ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1012{
1013 const char stop_type = stop_packet.GetChar();
1014 switch (stop_type)
1015 {
1016 case 'T':
1017 case 'S':
1018 {
1019 // Stop with signal and thread info
1020 const uint8_t signo = stop_packet.GetHexU8();
1021 std::string name;
1022 std::string value;
1023 std::string thread_name;
1024 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001025 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001026 uint32_t tid = LLDB_INVALID_THREAD_ID;
1027 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1028 uint32_t exc_data_count = 0;
1029 while (stop_packet.GetNameColonValue(name, value))
1030 {
1031 if (name.compare("metype") == 0)
1032 {
1033 // exception type in big endian hex
1034 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1035 }
1036 else if (name.compare("mecount") == 0)
1037 {
1038 // exception count in big endian hex
1039 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1040 }
1041 else if (name.compare("medata") == 0)
1042 {
1043 // exception data in big endian hex
1044 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1045 }
1046 else if (name.compare("thread") == 0)
1047 {
1048 // thread in big endian hex
1049 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1050 }
1051 else if (name.compare("name") == 0)
1052 {
1053 thread_name.swap (value);
1054 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001055 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001056 {
1057 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1058 }
1059 }
1060 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1061
1062 if (thread_sp)
1063 {
1064 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1065
1066 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1067 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001068 if (exc_type != 0)
1069 {
Greg Clayton643ee732010-08-04 01:40:35 +00001070 const size_t exc_data_count = exc_data.size();
1071
1072 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1073 exc_type,
1074 exc_data_count,
1075 exc_data_count >= 1 ? exc_data[0] : 0,
1076 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001077 }
1078 else if (signo)
1079 {
Greg Clayton643ee732010-08-04 01:40:35 +00001080 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001081 }
1082 else
1083 {
Greg Clayton643ee732010-08-04 01:40:35 +00001084 StopInfoSP invalid_stop_info_sp;
1085 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001086 }
1087 }
1088 return eStateStopped;
1089 }
1090 break;
1091
1092 case 'W':
1093 // process exited
1094 return eStateExited;
1095
1096 default:
1097 break;
1098 }
1099 return eStateInvalid;
1100}
1101
1102void
1103ProcessGDBRemote::RefreshStateAfterStop ()
1104{
Jim Ingham7508e732010-08-09 23:31:02 +00001105 // FIXME - add a variable to tell that we're in the middle of attaching if we
1106 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001107 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001108// if (!GetTarget().GetArchitecture().IsValid())
1109// {
1110// Module *exe_module = GetTarget().GetExecutableModule().get();
1111// if (exe_module)
1112// m_arch_spec = exe_module->GetArchitecture();
1113// }
1114
Chris Lattner24943d22010-06-08 16:52:24 +00001115 // Let all threads recover from stopping and do any clean up based
1116 // on the previous thread state (if any).
1117 m_thread_list.RefreshStateAfterStop();
1118
1119 // Discover new threads:
1120 UpdateThreadListIfNeeded ();
1121}
1122
1123Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001124ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001125{
1126 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001127 caused_stop = false;
1128
Chris Lattner24943d22010-06-08 16:52:24 +00001129 if (m_gdb_comm.IsRunning())
1130 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00001131 PausePrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00001132 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001133 Mutex::Locker locker;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001134
1135 if (m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1136 {
1137 EventSP event_sp;
1138 TimeValue timeout_time;
1139 timeout_time = TimeValue::Now();
1140 timeout_time.OffsetWithSeconds(2);
1141
1142 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1143
1144 if (!StateIsStoppedState (state))
1145 {
1146 LogSP log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1147 if (log)
1148 log->Printf("ProcessGDBRemote::DoHalt() failed to stop after sending interrupt");
1149 error.SetErrorString ("Did not get stopped event after interrupt succeeded.");
1150 }
1151 else
1152 caused_stop = true;
1153 }
1154 else
Chris Lattner24943d22010-06-08 16:52:24 +00001155 {
1156 if (timed_out)
1157 error.SetErrorString("timed out sending interrupt packet");
1158 else
1159 error.SetErrorString("unknown error sending interrupt packet");
1160 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001161
1162 // Resume the private state thread at this point.
1163 ResumePrivateStateThread();
1164
Chris Lattner24943d22010-06-08 16:52:24 +00001165 }
1166 return error;
1167}
1168
1169Error
1170ProcessGDBRemote::WillDetach ()
1171{
1172 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001173
Greg Clayton4fb400f2010-09-27 21:07:38 +00001174 if (m_gdb_comm.IsRunning())
1175 {
1176 bool timed_out = false;
1177 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001178 PausePrivateStateThread();
1179 m_thread_list.DiscardThreadPlans();
1180 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001181 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1182 {
1183 if (timed_out)
1184 error.SetErrorString("timed out sending interrupt packet");
1185 else
1186 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001187 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001188 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001189 TimeValue timeout_time;
1190 timeout_time = TimeValue::Now();
1191 timeout_time.OffsetWithSeconds(2);
1192
1193 EventSP event_sp;
1194 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1195 if (state != eStateStopped)
1196 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001197 }
Chris Lattner24943d22010-06-08 16:52:24 +00001198 return error;
1199}
1200
Greg Clayton4fb400f2010-09-27 21:07:38 +00001201Error
1202ProcessGDBRemote::DoDetach()
1203{
1204 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001205 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001206 if (log)
1207 log->Printf ("ProcessGDBRemote::DoDetach()");
1208
1209 DisableAllBreakpointSites ();
1210
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001211 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001212
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001213 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1214 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001215 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001216 if (response_size)
1217 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1218 else
1219 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001220 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001221 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001222 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001223
Greg Clayton4fb400f2010-09-27 21:07:38 +00001224 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001225 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001226
1227 SetPrivateState (eStateDetached);
1228 ResumePrivateStateThread();
1229
1230 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001231 return error;
1232}
Chris Lattner24943d22010-06-08 16:52:24 +00001233
1234Error
1235ProcessGDBRemote::DoDestroy ()
1236{
1237 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001238 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001239 if (log)
1240 log->Printf ("ProcessGDBRemote::DoDestroy()");
1241
1242 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001243 Mutex::Locker locker;
1244 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001245 DisableAllBreakpointSites ();
1246 SetExitStatus(-1, "process killed");
1247
1248 StringExtractorGDBRemote response;
1249 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1250 {
Caroline Tice926060e2010-10-29 21:48:37 +00001251 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001252 if (log)
1253 {
1254 if (response.IsOKPacket())
1255 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1256 else
1257 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1258 }
1259 }
1260
1261 StopAsyncThread ();
1262 m_gdb_comm.StopReadThread();
1263 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001264 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001265 return error;
1266}
1267
1268ByteOrder
1269ProcessGDBRemote::GetByteOrder () const
1270{
1271 return m_byte_order;
1272}
1273
1274//------------------------------------------------------------------
1275// Process Queries
1276//------------------------------------------------------------------
1277
1278bool
1279ProcessGDBRemote::IsAlive ()
1280{
1281 return m_gdb_comm.IsConnected();
1282}
1283
1284addr_t
1285ProcessGDBRemote::GetImageInfoAddress()
1286{
1287 if (!m_gdb_comm.IsRunning())
1288 {
1289 StringExtractorGDBRemote response;
1290 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1291 {
1292 if (response.IsNormalPacket())
1293 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1294 }
1295 }
1296 return LLDB_INVALID_ADDRESS;
1297}
1298
1299DynamicLoader *
1300ProcessGDBRemote::GetDynamicLoader()
1301{
1302 return m_dynamic_loader_ap.get();
1303}
1304
1305//------------------------------------------------------------------
1306// Process Memory
1307//------------------------------------------------------------------
1308size_t
1309ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1310{
1311 if (size > m_max_memory_size)
1312 {
1313 // Keep memory read sizes down to a sane limit. This function will be
1314 // called multiple times in order to complete the task by
1315 // lldb_private::Process so it is ok to do this.
1316 size = m_max_memory_size;
1317 }
1318
1319 char packet[64];
1320 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1321 assert (packet_len + 1 < sizeof(packet));
1322 StringExtractorGDBRemote response;
1323 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1324 {
1325 if (response.IsNormalPacket())
1326 {
1327 error.Clear();
1328 return response.GetHexBytes(buf, size, '\xdd');
1329 }
1330 else if (response.IsErrorPacket())
1331 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1332 else if (response.IsUnsupportedPacket())
1333 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1334 else
1335 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1336 }
1337 else
1338 {
1339 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1340 }
1341 return 0;
1342}
1343
1344size_t
1345ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1346{
1347 StreamString packet;
1348 packet.Printf("M%llx,%zx:", addr, size);
1349 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1350 StringExtractorGDBRemote response;
1351 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1352 {
1353 if (response.IsOKPacket())
1354 {
1355 error.Clear();
1356 return size;
1357 }
1358 else if (response.IsErrorPacket())
1359 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1360 else if (response.IsUnsupportedPacket())
1361 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1362 else
1363 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1364 }
1365 else
1366 {
1367 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1368 }
1369 return 0;
1370}
1371
1372lldb::addr_t
1373ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1374{
1375 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1376 if (allocated_addr == LLDB_INVALID_ADDRESS)
1377 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1378 else
1379 error.Clear();
1380 return allocated_addr;
1381}
1382
1383Error
1384ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1385{
1386 Error error;
1387 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1388 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1389 return error;
1390}
1391
1392
1393//------------------------------------------------------------------
1394// Process STDIO
1395//------------------------------------------------------------------
1396
1397size_t
1398ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1399{
1400 Mutex::Locker locker(m_stdio_mutex);
1401 size_t bytes_available = m_stdout_data.size();
1402 if (bytes_available > 0)
1403 {
1404 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1405 if (bytes_available > buf_size)
1406 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001407 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001408 m_stdout_data.erase(0, buf_size);
1409 bytes_available = buf_size;
1410 }
1411 else
1412 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001413 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001414 m_stdout_data.clear();
1415
1416 //ResetEventBits(eBroadcastBitSTDOUT);
1417 }
1418 }
1419 return bytes_available;
1420}
1421
1422size_t
1423ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1424{
1425 // Can we get STDERR through the remote protocol?
1426 return 0;
1427}
1428
1429size_t
1430ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1431{
1432 if (m_stdio_communication.IsConnected())
1433 {
1434 ConnectionStatus status;
1435 m_stdio_communication.Write(src, src_len, status, NULL);
1436 }
1437 return 0;
1438}
1439
1440Error
1441ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1442{
1443 Error error;
1444 assert (bp_site != NULL);
1445
Greg Claytone005f2c2010-11-06 01:53:30 +00001446 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001447 user_id_t site_id = bp_site->GetID();
1448 const addr_t addr = bp_site->GetLoadAddress();
1449 if (log)
1450 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1451
1452 if (bp_site->IsEnabled())
1453 {
1454 if (log)
1455 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1456 return error;
1457 }
1458 else
1459 {
1460 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1461
1462 if (bp_site->HardwarePreferred())
1463 {
1464 // Try and set hardware breakpoint, and if that fails, fall through
1465 // and set a software breakpoint?
1466 }
1467
1468 if (m_z0_supported)
1469 {
1470 char packet[64];
1471 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1472 assert (packet_len + 1 < sizeof(packet));
1473 StringExtractorGDBRemote response;
1474 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1475 {
1476 if (response.IsUnsupportedPacket())
1477 {
1478 // Disable z packet support and try again
1479 m_z0_supported = 0;
1480 return EnableBreakpoint (bp_site);
1481 }
1482 else if (response.IsOKPacket())
1483 {
1484 bp_site->SetEnabled(true);
1485 bp_site->SetType (BreakpointSite::eExternal);
1486 return error;
1487 }
1488 else
1489 {
1490 uint8_t error_byte = response.GetError();
1491 if (error_byte)
1492 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1493 }
1494 }
1495 }
1496 else
1497 {
1498 return EnableSoftwareBreakpoint (bp_site);
1499 }
1500 }
1501
1502 if (log)
1503 {
1504 const char *err_string = error.AsCString();
1505 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1506 bp_site->GetLoadAddress(),
1507 err_string ? err_string : "NULL");
1508 }
1509 // We shouldn't reach here on a successful breakpoint enable...
1510 if (error.Success())
1511 error.SetErrorToGenericError();
1512 return error;
1513}
1514
1515Error
1516ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1517{
1518 Error error;
1519 assert (bp_site != NULL);
1520 addr_t addr = bp_site->GetLoadAddress();
1521 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001522 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001523 if (log)
1524 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1525
1526 if (bp_site->IsEnabled())
1527 {
1528 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1529
1530 if (bp_site->IsHardware())
1531 {
1532 // TODO: disable hardware breakpoint...
1533 }
1534 else
1535 {
1536 if (m_z0_supported)
1537 {
1538 char packet[64];
1539 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1540 assert (packet_len + 1 < sizeof(packet));
1541 StringExtractorGDBRemote response;
1542 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1543 {
1544 if (response.IsUnsupportedPacket())
1545 {
1546 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1547 }
1548 else if (response.IsOKPacket())
1549 {
1550 if (log)
1551 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1552 bp_site->SetEnabled(false);
1553 return error;
1554 }
1555 else
1556 {
1557 uint8_t error_byte = response.GetError();
1558 if (error_byte)
1559 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1560 }
1561 }
1562 }
1563 else
1564 {
1565 return DisableSoftwareBreakpoint (bp_site);
1566 }
1567 }
1568 }
1569 else
1570 {
1571 if (log)
1572 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1573 return error;
1574 }
1575
1576 if (error.Success())
1577 error.SetErrorToGenericError();
1578 return error;
1579}
1580
1581Error
1582ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1583{
1584 Error error;
1585 if (wp)
1586 {
1587 user_id_t watchID = wp->GetID();
1588 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001589 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001590 if (log)
1591 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1592 if (wp->IsEnabled())
1593 {
1594 if (log)
1595 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1596 return error;
1597 }
1598 else
1599 {
1600 // Pass down an appropriate z/Z packet...
1601 error.SetErrorString("watchpoints not supported");
1602 }
1603 }
1604 else
1605 {
1606 error.SetErrorString("Watchpoint location argument was NULL.");
1607 }
1608 if (error.Success())
1609 error.SetErrorToGenericError();
1610 return error;
1611}
1612
1613Error
1614ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1615{
1616 Error error;
1617 if (wp)
1618 {
1619 user_id_t watchID = wp->GetID();
1620
Greg Claytone005f2c2010-11-06 01:53:30 +00001621 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001622
1623 addr_t addr = wp->GetLoadAddress();
1624 if (log)
1625 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1626
1627 if (wp->IsHardware())
1628 {
1629 // Pass down an appropriate z/Z packet...
1630 error.SetErrorString("watchpoints not supported");
1631 }
1632 // TODO: clear software watchpoints if we implement them
1633 }
1634 else
1635 {
1636 error.SetErrorString("Watchpoint location argument was NULL.");
1637 }
1638 if (error.Success())
1639 error.SetErrorToGenericError();
1640 return error;
1641}
1642
1643void
1644ProcessGDBRemote::Clear()
1645{
1646 m_flags = 0;
1647 m_thread_list.Clear();
1648 {
1649 Mutex::Locker locker(m_stdio_mutex);
1650 m_stdout_data.clear();
1651 }
1652 DestoryLibUnwindAddressSpace();
1653}
1654
1655Error
1656ProcessGDBRemote::DoSignal (int signo)
1657{
1658 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001659 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001660 if (log)
1661 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1662
1663 if (!m_gdb_comm.SendAsyncSignal (signo))
1664 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1665 return error;
1666}
1667
Caroline Tice861efb32010-11-16 05:07:41 +00001668//void
1669//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1670//{
1671// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1672// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1673//}
Chris Lattner24943d22010-06-08 16:52:24 +00001674
Caroline Tice861efb32010-11-16 05:07:41 +00001675//void
1676//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1677//{
1678// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1679// Mutex::Locker locker(m_stdio_mutex);
1680// m_stdout_data.append(s, len);
1681//
1682// // FIXME: Make a real data object for this and put it out.
1683// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1684//}
Chris Lattner24943d22010-06-08 16:52:24 +00001685
1686
1687Error
1688ProcessGDBRemote::StartDebugserverProcess
1689(
1690 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1691 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1692 char const *inferior_envp[], // Environment to pass along to the inferior program
1693 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001694 bool launch_process, // Set to true if we are going to be launching a the process
1695 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 +00001696 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1697 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Clayton23cf0c72010-11-08 04:29:11 +00001698 bool disable_aslr, // Disable ASLR
Chris Lattner24943d22010-06-08 16:52:24 +00001699 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1700)
1701{
1702 Error error;
1703 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1704 {
1705 // If we locate debugserver, keep that located version around
1706 static FileSpec g_debugserver_file_spec;
1707
1708 FileSpec debugserver_file_spec;
1709 char debugserver_path[PATH_MAX];
1710
1711 // Always check to see if we have an environment override for the path
1712 // to the debugserver to use and use it if we do.
1713 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1714 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001715 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001716 else
1717 debugserver_file_spec = g_debugserver_file_spec;
1718 bool debugserver_exists = debugserver_file_spec.Exists();
1719 if (!debugserver_exists)
1720 {
1721 // The debugserver binary is in the LLDB.framework/Resources
1722 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001723 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001724 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001725 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001726 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001727 if (debugserver_exists)
1728 {
1729 g_debugserver_file_spec = debugserver_file_spec;
1730 }
1731 else
1732 {
1733 g_debugserver_file_spec.Clear();
1734 debugserver_file_spec.Clear();
1735 }
Chris Lattner24943d22010-06-08 16:52:24 +00001736 }
1737 }
1738
1739 if (debugserver_exists)
1740 {
1741 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1742
1743 m_stdio_communication.Clear();
1744 posix_spawnattr_t attr;
1745
Greg Claytone005f2c2010-11-06 01:53:30 +00001746 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001747
1748 Error local_err; // Errors that don't affect the spawning.
1749 if (log)
1750 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1751 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1752 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001753 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001754 if (error.Fail())
1755 return error;;
1756
1757#if !defined (__arm__)
1758
Greg Clayton24b48ff2010-10-17 22:03:32 +00001759 // We don't need to do this for ARM, and we really shouldn't now
1760 // that we have multiple CPU subtypes and no posix_spawnattr call
1761 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001762 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001763 {
Greg Claytoncf015052010-06-11 03:25:34 +00001764 cpu_type_t cpu = inferior_arch.GetCPUType();
1765 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1766 {
1767 size_t ocount = 0;
1768 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1769 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001770 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 +00001771
Greg Claytoncf015052010-06-11 03:25:34 +00001772 if (error.Fail() != 0 || ocount != 1)
1773 return error;
1774 }
Chris Lattner24943d22010-06-08 16:52:24 +00001775 }
1776
1777#endif
1778
1779 Args debugserver_args;
1780 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001781
Chris Lattner24943d22010-06-08 16:52:24 +00001782 lldb_utility::PseudoTerminal pty;
Greg Clayton23cf0c72010-11-08 04:29:11 +00001783 if (launch_process && stdio_path == NULL && m_local_debugserver)
Chris Lattner24943d22010-06-08 16:52:24 +00001784 {
Chris Lattner24943d22010-06-08 16:52:24 +00001785 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001786 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001787 }
1788
1789 // Start args with "debugserver /file/path -r --"
1790 debugserver_args.AppendArgument(debugserver_path);
1791 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001792 // use native registers, not the GDB registers
1793 debugserver_args.AppendArgument("--native-regs");
1794 // make debugserver run in its own session so signals generated by
1795 // special terminal key sequences (^C) don't affect debugserver
1796 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001797
Greg Clayton452bf612010-08-31 18:35:14 +00001798 if (disable_aslr)
1799 debugserver_args.AppendArguments("--disable-aslr");
1800
Chris Lattner24943d22010-06-08 16:52:24 +00001801 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001802 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001803 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001804 debugserver_args.AppendArgument("--stdio-path");
1805 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001806 }
1807
1808 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1809 if (env_debugserver_log_file)
1810 {
1811 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1812 debugserver_args.AppendArgument(arg_cstr);
1813 }
1814
1815 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1816 if (env_debugserver_log_flags)
1817 {
1818 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1819 debugserver_args.AppendArgument(arg_cstr);
1820 }
1821// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1822// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1823
1824 // Now append the program arguments
1825 if (launch_process)
1826 {
1827 if (inferior_argv)
1828 {
1829 // Terminate the debugserver args so we can now append the inferior args
1830 debugserver_args.AppendArgument("--");
1831
1832 for (int i = 0; inferior_argv[i] != NULL; ++i)
1833 debugserver_args.AppendArgument (inferior_argv[i]);
1834 }
1835 else
1836 {
1837 // Will send environment entries with the 'QEnvironment:' packet
1838 // Will send arguments with the 'A' packet
1839 }
1840 }
1841 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1842 {
1843 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1844 debugserver_args.AppendArgument (arg_cstr);
1845 }
1846 else if (attach_name && attach_name[0])
1847 {
1848 if (wait_for_launch)
1849 debugserver_args.AppendArgument ("--waitfor");
1850 else
1851 debugserver_args.AppendArgument ("--attach");
1852 debugserver_args.AppendArgument (attach_name);
1853 }
1854
1855 Error file_actions_err;
1856 posix_spawn_file_actions_t file_actions;
1857#if DONT_CLOSE_DEBUGSERVER_STDIO
1858 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1859#else
1860 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1861 if (file_actions_err.Success())
1862 {
1863 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1864 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1865 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1866 }
1867#endif
1868
1869 if (log)
1870 {
1871 StreamString strm;
1872 debugserver_args.Dump (&strm);
1873 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1874 }
1875
1876 error.SetError(::posix_spawnp (&m_debugserver_pid,
1877 debugserver_path,
1878 file_actions_err.Success() ? &file_actions : NULL,
1879 &attr,
1880 debugserver_args.GetArgumentVector(),
1881 (char * const*)inferior_envp),
1882 eErrorTypePOSIX);
1883
Greg Claytone9d0df42010-07-02 01:29:13 +00001884
1885 ::posix_spawnattr_destroy (&attr);
1886
Chris Lattner24943d22010-06-08 16:52:24 +00001887 if (file_actions_err.Success())
1888 ::posix_spawn_file_actions_destroy (&file_actions);
1889
1890 // We have seen some cases where posix_spawnp was returning a valid
1891 // looking pid even when an error was returned, so clear it out
1892 if (error.Fail())
1893 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1894
1895 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001896 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 +00001897
Caroline Tice91a1dab2010-11-05 22:37:44 +00001898 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1899 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001900 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001901 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001902 }
Chris Lattner24943d22010-06-08 16:52:24 +00001903 }
1904 else
1905 {
1906 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1907 }
1908
1909 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1910 StartAsyncThread ();
1911 }
1912 return error;
1913}
1914
1915bool
1916ProcessGDBRemote::MonitorDebugserverProcess
1917(
1918 void *callback_baton,
1919 lldb::pid_t debugserver_pid,
1920 int signo, // Zero for no signal
1921 int exit_status // Exit value of process if signal is zero
1922)
1923{
1924 // We pass in the ProcessGDBRemote inferior process it and name it
1925 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1926 // pointer value itself, thus we need the double cast...
1927
1928 // "debugserver_pid" argument passed in is the process ID for
1929 // debugserver that we are tracking...
1930
Greg Clayton75ccf502010-08-21 02:22:51 +00001931 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1932
1933 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001934 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001935 // Sleep for a half a second to make sure our inferior process has
1936 // time to set its exit status before we set it incorrectly when
1937 // both the debugserver and the inferior process shut down.
1938 usleep (500000);
1939 // If our process hasn't yet exited, debugserver might have died.
1940 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001941 const StateType state = process->GetState();
1942
1943 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1944 state != eStateInvalid &&
1945 state != eStateUnloaded &&
1946 state != eStateExited &&
1947 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001948 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001949 char error_str[1024];
1950 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001951 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001952 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1953 if (signal_cstr)
1954 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001955 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001956 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001957 }
1958 else
1959 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001960 ::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 +00001961 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001962
1963 process->SetExitStatus (-1, error_str);
1964 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001965 // Debugserver has exited we need to let our ProcessGDBRemote
1966 // know that it no longer has a debugserver instance
1967 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1968 // We are returning true to this function below, so we can
1969 // forget about the monitor handle.
1970 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001971 }
1972 return true;
1973}
1974
1975void
1976ProcessGDBRemote::KillDebugserverProcess ()
1977{
1978 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1979 {
1980 ::kill (m_debugserver_pid, SIGINT);
1981 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1982 }
1983}
1984
1985void
1986ProcessGDBRemote::Initialize()
1987{
1988 static bool g_initialized = false;
1989
1990 if (g_initialized == false)
1991 {
1992 g_initialized = true;
1993 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1994 GetPluginDescriptionStatic(),
1995 CreateInstance);
1996
1997 Log::Callbacks log_callbacks = {
1998 ProcessGDBRemoteLog::DisableLog,
1999 ProcessGDBRemoteLog::EnableLog,
2000 ProcessGDBRemoteLog::ListLogCategories
2001 };
2002
2003 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2004 }
2005}
2006
2007bool
2008ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2009{
2010 if (m_curr_tid == tid)
2011 return true;
2012
2013 char packet[32];
2014 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2015 assert (packet_len + 1 < sizeof(packet));
2016 StringExtractorGDBRemote response;
2017 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2018 {
2019 if (response.IsOKPacket())
2020 {
2021 m_curr_tid = tid;
2022 return true;
2023 }
2024 }
2025 return false;
2026}
2027
2028bool
2029ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2030{
2031 if (m_curr_tid_run == tid)
2032 return true;
2033
2034 char packet[32];
2035 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2036 assert (packet_len + 1 < sizeof(packet));
2037 StringExtractorGDBRemote response;
2038 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2039 {
2040 if (response.IsOKPacket())
2041 {
2042 m_curr_tid_run = tid;
2043 return true;
2044 }
2045 }
2046 return false;
2047}
2048
2049void
2050ProcessGDBRemote::ResetGDBRemoteState ()
2051{
2052 // Reset and GDB remote state
2053 m_curr_tid = LLDB_INVALID_THREAD_ID;
2054 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2055 m_z0_supported = 1;
2056}
2057
2058
2059bool
2060ProcessGDBRemote::StartAsyncThread ()
2061{
2062 ResetGDBRemoteState ();
2063
Greg Claytone005f2c2010-11-06 01:53:30 +00002064 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002065
2066 if (log)
2067 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2068
2069 // Create a thread that watches our internal state and controls which
2070 // events make it to clients (into the DCProcess event queue).
2071 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2072 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2073}
2074
2075void
2076ProcessGDBRemote::StopAsyncThread ()
2077{
Greg Claytone005f2c2010-11-06 01:53:30 +00002078 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002079
2080 if (log)
2081 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2082
2083 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2084
2085 // Stop the stdio thread
2086 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2087 {
2088 Host::ThreadJoin (m_async_thread, NULL, NULL);
2089 }
2090}
2091
2092
2093void *
2094ProcessGDBRemote::AsyncThread (void *arg)
2095{
2096 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2097
Greg Claytone005f2c2010-11-06 01:53:30 +00002098 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002099 if (log)
2100 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2101
2102 Listener listener ("ProcessGDBRemote::AsyncThread");
2103 EventSP event_sp;
2104 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2105 eBroadcastBitAsyncThreadShouldExit;
2106
2107 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2108 {
2109 bool done = false;
2110 while (!done)
2111 {
Caroline Tice926060e2010-10-29 21:48:37 +00002112 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002113 if (log)
2114 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2115 if (listener.WaitForEvent (NULL, event_sp))
2116 {
2117 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002118 if (log)
2119 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2120
Chris Lattner24943d22010-06-08 16:52:24 +00002121 switch (event_type)
2122 {
2123 case eBroadcastBitAsyncContinue:
2124 {
2125 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2126
2127 if (continue_packet)
2128 {
2129 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2130 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002131 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002132 if (log)
2133 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2134
2135 process->SetPrivateState(eStateRunning);
2136 StringExtractorGDBRemote response;
2137 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2138
2139 switch (stop_state)
2140 {
2141 case eStateStopped:
2142 case eStateCrashed:
2143 case eStateSuspended:
2144 process->m_last_stop_packet = response;
2145 process->m_last_stop_packet.SetFilePos (0);
2146 process->SetPrivateState (stop_state);
2147 break;
2148
2149 case eStateExited:
2150 process->m_last_stop_packet = response;
2151 process->m_last_stop_packet.SetFilePos (0);
2152 response.SetFilePos(1);
2153 process->SetExitStatus(response.GetHexU8(), NULL);
2154 done = true;
2155 break;
2156
2157 case eStateInvalid:
2158 break;
2159
2160 default:
2161 process->SetPrivateState (stop_state);
2162 break;
2163 }
2164 }
2165 }
2166 break;
2167
2168 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002169 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002170 if (log)
2171 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2172 done = true;
2173 break;
2174
2175 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002176 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002177 if (log)
2178 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2179 done = true;
2180 break;
2181 }
2182 }
2183 else
2184 {
Caroline Tice926060e2010-10-29 21:48:37 +00002185 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002186 if (log)
2187 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2188 done = true;
2189 }
2190 }
2191 }
2192
Caroline Tice926060e2010-10-29 21:48:37 +00002193 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002194 if (log)
2195 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2196
2197 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2198 return NULL;
2199}
2200
2201lldb_private::unw_addr_space_t
2202ProcessGDBRemote::GetLibUnwindAddressSpace ()
2203{
2204 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002205
2206 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2207 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002208 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002209 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002210 target_type = UNW_TARGET_X86_64;
2211
2212 if (m_libunwind_addr_space)
2213 {
2214 if (m_libunwind_target_type != target_type)
2215 DestoryLibUnwindAddressSpace();
2216 else
2217 return m_libunwind_addr_space;
2218 }
2219 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2220 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2221 if (m_libunwind_addr_space)
2222 m_libunwind_target_type = target_type;
2223 else
2224 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2225 return m_libunwind_addr_space;
2226}
2227
2228void
2229ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2230{
2231 if (m_libunwind_addr_space)
2232 {
2233 unw_destroy_addr_space (m_libunwind_addr_space);
2234 m_libunwind_addr_space = NULL;
2235 }
2236 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2237}
2238
2239
2240const char *
2241ProcessGDBRemote::GetDispatchQueueNameForThread
2242(
2243 addr_t thread_dispatch_qaddr,
2244 std::string &dispatch_queue_name
2245)
2246{
2247 dispatch_queue_name.clear();
2248 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2249 {
2250 // Cache the dispatch_queue_offsets_addr value so we don't always have
2251 // to look it up
2252 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2253 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002254 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2255 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002256 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002257 if (module_sp)
2258 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2259
2260 if (dispatch_queue_offsets_symbol == NULL)
2261 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002262 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002263 if (module_sp)
2264 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2265 }
Chris Lattner24943d22010-06-08 16:52:24 +00002266 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002267 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002268
2269 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2270 return NULL;
2271 }
2272
2273 uint8_t memory_buffer[8];
2274 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2275
2276 // Excerpt from src/queue_private.h
2277 struct dispatch_queue_offsets_s
2278 {
2279 uint16_t dqo_version;
2280 uint16_t dqo_label;
2281 uint16_t dqo_label_size;
2282 } dispatch_queue_offsets;
2283
2284
2285 Error error;
2286 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2287 {
2288 uint32_t data_offset = 0;
2289 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2290 {
2291 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2292 {
2293 data_offset = 0;
2294 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2295 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2296 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2297 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2298 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2299 dispatch_queue_name.erase (bytes_read);
2300 }
2301 }
2302 }
2303 }
2304 if (dispatch_queue_name.empty())
2305 return NULL;
2306 return dispatch_queue_name.c_str();
2307}
2308
Jim Ingham7508e732010-08-09 23:31:02 +00002309uint32_t
2310ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2311{
2312 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2313 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2314 if (m_local_debugserver)
2315 {
2316 return Host::ListProcessesMatchingName (name, matches, pids);
2317 }
2318 else
2319 {
2320 // FIXME: Implement talking to the remote debugserver.
2321 return 0;
2322 }
2323
2324}