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