blob: 4b45bd459f7f49c9e5b1d46034659da09e4af4b4 [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
369//----------------------------------------------------------------------
370// Process Control
371//----------------------------------------------------------------------
372Error
373ProcessGDBRemote::DoLaunch
374(
375 Module* module,
376 char const *argv[],
377 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000378 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000379 const char *stdin_path,
380 const char *stdout_path,
381 const char *stderr_path
382)
383{
Greg Clayton4b407112010-09-30 21:49:03 +0000384 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000385 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
386 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
387 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000388
389 ObjectFile * object_file = module->GetObjectFile();
390 if (object_file)
391 {
392 ArchSpec inferior_arch(module->GetArchitecture());
393 char host_port[128];
394 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
395
396 bool start_debugserver_with_inferior_args = false;
397 if (start_debugserver_with_inferior_args)
398 {
399 // We want to launch debugserver with the inferior program and its
400 // arguments on the command line. We should only do this if we
401 // the GDB server we are talking to doesn't support the 'A' packet.
402 error = StartDebugserverProcess (host_port,
403 argv,
404 envp,
405 NULL, //stdin_path,
406 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,
424 NULL, //stdin_path,
425 LLDB_INVALID_PROCESS_ID,
426 NULL, false,
Benjamin Kramer2653be92010-09-03 18:20:07 +0000427 (launch_flags & eLaunchFlagDisableASLR) != 0,
Chris Lattner24943d22010-06-08 16:52:24 +0000428 inferior_arch);
429 if (error.Fail())
430 return error;
431
432 error = ConnectToDebugserver (host_port);
433 if (error.Success())
434 {
435 // Send the environment and the program + arguments after we connect
436 if (envp)
437 {
438 const char *env_entry;
439 for (int i=0; (env_entry = envp[i]); ++i)
440 {
441 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
442 break;
443 }
444 }
445
Greg Clayton960d6a42010-08-03 00:35:52 +0000446 // FIXME: convert this to use the new set/show variables when they are available
447#if 0
448 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
449 {
450 const uint32_t attach_debugserver_secs = 10;
451 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
452 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
453 {
454 printf ("%i\n", attach_debugserver_secs - i);
455 sleep (1);
456 }
457 }
458#endif
459
Chris Lattner24943d22010-06-08 16:52:24 +0000460 const uint32_t arg_timeout_seconds = 10;
461 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
462 if (arg_packet_err == 0)
463 {
464 std::string error_str;
465 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
466 {
467 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
468 }
469 else
470 {
471 error.SetErrorString (error_str.c_str());
472 }
473 }
474 else
475 {
476 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
477 }
478
479 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
480 }
481 }
482
483 if (GetID() == LLDB_INVALID_PROCESS_ID)
484 {
485 KillDebugserverProcess ();
486 return error;
487 }
488
489 StringExtractorGDBRemote response;
490 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
491 SetPrivateState (SetThreadStopInfo (response));
492
493 }
494 else
495 {
496 // Set our user ID to an invalid process ID.
497 SetID(LLDB_INVALID_PROCESS_ID);
498 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
499 }
Chris Lattner24943d22010-06-08 16:52:24 +0000500 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000501
Chris Lattner24943d22010-06-08 16:52:24 +0000502}
503
504
505Error
506ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
507{
508 Error error;
509 // Sleep and wait a bit for debugserver to start to listen...
510 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
511 if (conn_ap.get())
512 {
513 std::string connect_url("connect://");
514 connect_url.append (host_port);
515 const uint32_t max_retry_count = 50;
516 uint32_t retry_count = 0;
517 while (!m_gdb_comm.IsConnected())
518 {
519 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
520 {
521 m_gdb_comm.SetConnection (conn_ap.release());
522 break;
523 }
524 retry_count++;
525
526 if (retry_count >= max_retry_count)
527 break;
528
529 usleep (100000);
530 }
531 }
532
533 if (!m_gdb_comm.IsConnected())
534 {
535 if (error.Success())
536 error.SetErrorString("not connected to remote gdb server");
537 return error;
538 }
539
540 m_gdb_comm.SetAckMode (true);
541 if (m_gdb_comm.StartReadThread(&error))
542 {
543 // Send an initial ack
544 m_gdb_comm.SendAck('+');
545
546 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000547 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
548 this,
549 m_debugserver_pid,
550 false);
551
Chris Lattner24943d22010-06-08 16:52:24 +0000552 StringExtractorGDBRemote response;
553 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
554 {
555 if (response.IsOKPacket())
556 m_gdb_comm.SetAckMode (false);
557 }
558
559 BuildDynamicRegisterInfo ();
560 }
561 return error;
562}
563
564void
565ProcessGDBRemote::DidLaunchOrAttach ()
566{
567 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
568 if (GetID() == LLDB_INVALID_PROCESS_ID)
569 {
570 m_dynamic_loader_ap.reset();
571 }
572 else
573 {
574 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
575
Jim Ingham7508e732010-08-09 23:31:02 +0000576 Module * exe_module = GetTarget().GetExecutableModule ().get();
Chris Lattner24943d22010-06-08 16:52:24 +0000577 assert(exe_module);
578
Chris Lattner24943d22010-06-08 16:52:24 +0000579 ObjectFile *exe_objfile = exe_module->GetObjectFile();
580 assert(exe_objfile);
581
582 m_byte_order = exe_objfile->GetByteOrder();
583 assert (m_byte_order != eByteOrderInvalid);
584
585 StreamString strm;
586
587 ArchSpec inferior_arch;
588 // See if the GDB server supports the qHostInfo information
589 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
590 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Jim Ingham7508e732010-08-09 23:31:02 +0000591 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000592
Jim Ingham7508e732010-08-09 23:31:02 +0000593 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000594 {
595 // For ARM we can't trust the arch of the process as it could
596 // have an armv6 object file, but be running on armv7 kernel.
597 inferior_arch = m_gdb_comm.GetHostArchitecture();
598 }
599
600 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000601 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000602
603 if (vendor == NULL)
604 vendor = Host::GetVendorString().AsCString("apple");
605
606 if (os_type == NULL)
607 os_type = Host::GetOSString().AsCString("darwin");
608
609 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
610
611 std::transform (strm.GetString().begin(),
612 strm.GetString().end(),
613 strm.GetString().begin(),
614 ::tolower);
615
616 m_target_triple.SetCString(strm.GetString().c_str());
617 }
618}
619
620void
621ProcessGDBRemote::DidLaunch ()
622{
623 DidLaunchOrAttach ();
624 if (m_dynamic_loader_ap.get())
625 m_dynamic_loader_ap->DidLaunch();
626}
627
628Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000629ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000630{
631 Error error;
632 // Clear out and clean up from any current state
633 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000634 ArchSpec arch_spec = GetTarget().GetArchitecture();
635
Chris Lattner24943d22010-06-08 16:52:24 +0000636 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Jim Ingham7508e732010-08-09 23:31:02 +0000637
638
Chris Lattner24943d22010-06-08 16:52:24 +0000639 if (attach_pid != LLDB_INVALID_PROCESS_ID)
640 {
Chris Lattner24943d22010-06-08 16:52:24 +0000641 char host_port[128];
642 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000643 error = StartDebugserverProcess (host_port, // debugserver_url
644 NULL, // inferior_argv
645 NULL, // inferior_envp
646 NULL, // stdin_path
647 LLDB_INVALID_PROCESS_ID, // attach_pid
648 NULL, // attach_pid_name
649 false, // wait_for_launch
650 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000651 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000652
653 if (error.Fail())
654 {
655 const char *error_string = error.AsCString();
656 if (error_string == NULL)
657 error_string = "unable to launch " DEBUGSERVER_BASENAME;
658
659 SetExitStatus (-1, error_string);
660 }
661 else
662 {
663 error = ConnectToDebugserver (host_port);
664 if (error.Success())
665 {
666 char packet[64];
667 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
668 StringExtractorGDBRemote response;
669 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
670 packet,
671 packet_len,
672 response);
673 switch (stop_state)
674 {
675 case eStateStopped:
676 case eStateCrashed:
677 case eStateSuspended:
678 SetID (attach_pid);
679 m_last_stop_packet = response;
680 m_last_stop_packet.SetFilePos (0);
681 SetPrivateState (stop_state);
682 break;
683
684 case eStateExited:
685 m_last_stop_packet = response;
686 m_last_stop_packet.SetFilePos (0);
687 response.SetFilePos(1);
688 SetExitStatus(response.GetHexU8(), NULL);
689 break;
690
691 default:
692 SetExitStatus(-1, "unable to attach to process");
693 break;
694 }
695
696 }
697 }
698 }
699
700 lldb::pid_t pid = GetID();
701 if (pid == LLDB_INVALID_PROCESS_ID)
702 {
703 KillDebugserverProcess();
704 }
705 return error;
706}
707
708size_t
709ProcessGDBRemote::AttachInputReaderCallback
710(
711 void *baton,
712 InputReader *reader,
713 lldb::InputReaderAction notification,
714 const char *bytes,
715 size_t bytes_len
716)
717{
718 if (notification == eInputReaderGotToken)
719 {
720 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
721 if (gdb_process->m_waiting_for_attach)
722 gdb_process->m_waiting_for_attach = false;
723 reader->SetIsDone(true);
724 return 1;
725 }
726 return 0;
727}
728
729Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000730ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000731{
732 Error error;
733 // Clear out and clean up from any current state
734 Clear();
735 // HACK: require arch be set correctly at the target level until we can
736 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000737
738 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
739 if (process_name && process_name[0])
740 {
Chris Lattner24943d22010-06-08 16:52:24 +0000741 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000742 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000743 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000744 error = StartDebugserverProcess (host_port, // debugserver_url
745 NULL, // inferior_argv
746 NULL, // inferior_envp
747 NULL, // stdin_path
748 LLDB_INVALID_PROCESS_ID, // attach_pid
749 NULL, // attach_pid_name
750 false, // wait_for_launch
751 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000752 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000753 if (error.Fail())
754 {
755 const char *error_string = error.AsCString();
756 if (error_string == NULL)
757 error_string = "unable to launch " DEBUGSERVER_BASENAME;
758
759 SetExitStatus (-1, error_string);
760 }
761 else
762 {
763 error = ConnectToDebugserver (host_port);
764 if (error.Success())
765 {
766 StreamString packet;
767
Chris Lattner24943d22010-06-08 16:52:24 +0000768 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000769 packet.PutCString("vAttachWait");
770 else
771 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000772 packet.PutChar(';');
773 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
774 StringExtractorGDBRemote response;
775 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
776 packet.GetData(),
777 packet.GetSize(),
778 response);
779 switch (stop_state)
780 {
781 case eStateStopped:
782 case eStateCrashed:
783 case eStateSuspended:
784 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
785 m_last_stop_packet = response;
786 m_last_stop_packet.SetFilePos (0);
787 SetPrivateState (stop_state);
788 break;
789
790 case eStateExited:
791 m_last_stop_packet = response;
792 m_last_stop_packet.SetFilePos (0);
793 response.SetFilePos(1);
794 SetExitStatus(response.GetHexU8(), NULL);
795 break;
796
797 default:
798 SetExitStatus(-1, "unable to attach to process");
799 break;
800 }
801 }
802 }
803 }
804
805 lldb::pid_t pid = GetID();
806 if (pid == LLDB_INVALID_PROCESS_ID)
807 {
808 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000809
810 if (error.Success())
811 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000812 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000813
Chris Lattner24943d22010-06-08 16:52:24 +0000814 return error;
815}
816
817//
818// if (wait_for_launch)
819// {
820// InputReaderSP reader_sp (new InputReader());
821// StreamString instructions;
822// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
823// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
824// this, // baton
825// eInputReaderGranularityByte,
826// NULL, // End token
827// false);
828//
829// StringExtractorGDBRemote response;
830// m_waiting_for_attach = true;
831// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
832// while (m_waiting_for_attach)
833// {
834// // Wait for one second for the stop reply packet
835// if (m_gdb_comm.WaitForPacket(response, 1))
836// {
837// // Got some sort of packet, see if it is the stop reply packet?
838// char ch = response.GetChar(0);
839// if (ch == 'T')
840// {
841// m_waiting_for_attach = false;
842// }
843// }
844// else
845// {
846// // Put a period character every second
847// fputc('.', reader_out_fh);
848// }
849// }
850// }
851// }
852// return GetID();
853//}
854
855void
856ProcessGDBRemote::DidAttach ()
857{
Jim Ingham7508e732010-08-09 23:31:02 +0000858 // If we haven't got an executable module yet, then we should make a dynamic loader, and
859 // see if it can find the executable module for us. If we do have an executable module,
860 // make sure it matches the process we've just attached to.
861
862 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
863 if (!m_dynamic_loader_ap.get())
864 {
865 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
866 }
867
Chris Lattner24943d22010-06-08 16:52:24 +0000868 if (m_dynamic_loader_ap.get())
869 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000870
871 Module * new_exe_module = GetTarget().GetExecutableModule().get();
872 if (new_exe_module == NULL)
873 {
874
875 }
876
877 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000878}
879
880Error
881ProcessGDBRemote::WillResume ()
882{
883 m_continue_packet.Clear();
884 // Start the continue packet we will use to run the target. Each thread
885 // will append what it is supposed to be doing to this packet when the
886 // ThreadList::WillResume() is called. If a thread it supposed
887 // to stay stopped, then don't append anything to this string.
888 m_continue_packet.Printf("vCont");
889 return Error();
890}
891
892Error
893ProcessGDBRemote::DoResume ()
894{
895 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
896 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
897 return Error();
898}
899
900size_t
901ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
902{
903 const uint8_t *trap_opcode = NULL;
904 uint32_t trap_opcode_size = 0;
905
906 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
907 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
908 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
909 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
910
Jim Ingham7508e732010-08-09 23:31:02 +0000911 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000912 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000913 {
Greg Claytoncf015052010-06-11 03:25:34 +0000914 case ArchSpec::eCPU_i386:
915 case ArchSpec::eCPU_x86_64:
916 trap_opcode = g_i386_breakpoint_opcode;
917 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
918 break;
919
920 case ArchSpec::eCPU_arm:
921 // TODO: fill this in for ARM. We need to dig up the symbol for
922 // the address in the breakpoint locaiton and figure out if it is
923 // an ARM or Thumb breakpoint.
924 trap_opcode = g_arm_breakpoint_opcode;
925 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
926 break;
927
928 case ArchSpec::eCPU_ppc:
929 case ArchSpec::eCPU_ppc64:
930 trap_opcode = g_ppc_breakpoint_opcode;
931 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
932 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000933
Greg Claytoncf015052010-06-11 03:25:34 +0000934 default:
935 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
936 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000937 }
938
939 if (trap_opcode && trap_opcode_size)
940 {
941 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
942 return trap_opcode_size;
943 }
944 return 0;
945}
946
947uint32_t
948ProcessGDBRemote::UpdateThreadListIfNeeded ()
949{
950 // locker will keep a mutex locked until it goes out of scope
951 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD);
952 if (log && log->GetMask().IsSet(GDBR_LOG_VERBOSE))
953 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
954
Greg Clayton5205f0b2010-09-03 17:10:42 +0000955 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000956 const uint32_t stop_id = GetStopID();
957 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
958 {
959 // Update the thread list's stop id immediately so we don't recurse into this function.
960 ThreadList curr_thread_list (this);
961 curr_thread_list.SetStopID(stop_id);
962
963 Error err;
964 StringExtractorGDBRemote response;
965 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
966 response.IsNormalPacket();
967 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
968 {
969 char ch = response.GetChar();
970 if (ch == 'l')
971 break;
972 if (ch == 'm')
973 {
974 do
975 {
976 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
977
978 if (tid != LLDB_INVALID_THREAD_ID)
979 {
980 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
981 if (thread_sp)
982 thread_sp->GetRegisterContext()->Invalidate();
983 else
984 thread_sp.reset (new ThreadGDBRemote (*this, tid));
985 curr_thread_list.AddThread(thread_sp);
986 }
987
988 ch = response.GetChar();
989 } while (ch == ',');
990 }
991 }
992
993 m_thread_list = curr_thread_list;
994
995 SetThreadStopInfo (m_last_stop_packet);
996 }
997 return GetThreadList().GetSize(false);
998}
999
1000
1001StateType
1002ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1003{
1004 const char stop_type = stop_packet.GetChar();
1005 switch (stop_type)
1006 {
1007 case 'T':
1008 case 'S':
1009 {
1010 // Stop with signal and thread info
1011 const uint8_t signo = stop_packet.GetHexU8();
1012 std::string name;
1013 std::string value;
1014 std::string thread_name;
1015 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001016 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001017 uint32_t tid = LLDB_INVALID_THREAD_ID;
1018 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1019 uint32_t exc_data_count = 0;
1020 while (stop_packet.GetNameColonValue(name, value))
1021 {
1022 if (name.compare("metype") == 0)
1023 {
1024 // exception type in big endian hex
1025 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1026 }
1027 else if (name.compare("mecount") == 0)
1028 {
1029 // exception count in big endian hex
1030 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1031 }
1032 else if (name.compare("medata") == 0)
1033 {
1034 // exception data in big endian hex
1035 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1036 }
1037 else if (name.compare("thread") == 0)
1038 {
1039 // thread in big endian hex
1040 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1041 }
1042 else if (name.compare("name") == 0)
1043 {
1044 thread_name.swap (value);
1045 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001046 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001047 {
1048 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1049 }
1050 }
1051 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1052
1053 if (thread_sp)
1054 {
1055 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1056
1057 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1058 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001059 if (exc_type != 0)
1060 {
Greg Clayton643ee732010-08-04 01:40:35 +00001061 const size_t exc_data_count = exc_data.size();
1062
1063 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1064 exc_type,
1065 exc_data_count,
1066 exc_data_count >= 1 ? exc_data[0] : 0,
1067 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001068 }
1069 else if (signo)
1070 {
Greg Clayton643ee732010-08-04 01:40:35 +00001071 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001072 }
1073 else
1074 {
Greg Clayton643ee732010-08-04 01:40:35 +00001075 StopInfoSP invalid_stop_info_sp;
1076 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001077 }
1078 }
1079 return eStateStopped;
1080 }
1081 break;
1082
1083 case 'W':
1084 // process exited
1085 return eStateExited;
1086
1087 default:
1088 break;
1089 }
1090 return eStateInvalid;
1091}
1092
1093void
1094ProcessGDBRemote::RefreshStateAfterStop ()
1095{
Jim Ingham7508e732010-08-09 23:31:02 +00001096 // FIXME - add a variable to tell that we're in the middle of attaching if we
1097 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001098 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001099// if (!GetTarget().GetArchitecture().IsValid())
1100// {
1101// Module *exe_module = GetTarget().GetExecutableModule().get();
1102// if (exe_module)
1103// m_arch_spec = exe_module->GetArchitecture();
1104// }
1105
Chris Lattner24943d22010-06-08 16:52:24 +00001106 // Let all threads recover from stopping and do any clean up based
1107 // on the previous thread state (if any).
1108 m_thread_list.RefreshStateAfterStop();
1109
1110 // Discover new threads:
1111 UpdateThreadListIfNeeded ();
1112}
1113
1114Error
1115ProcessGDBRemote::DoHalt ()
1116{
1117 Error error;
1118 if (m_gdb_comm.IsRunning())
1119 {
1120 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001121 Mutex::Locker locker;
1122 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001123 {
1124 if (timed_out)
1125 error.SetErrorString("timed out sending interrupt packet");
1126 else
1127 error.SetErrorString("unknown error sending interrupt packet");
1128 }
1129 }
1130 return error;
1131}
1132
1133Error
1134ProcessGDBRemote::WillDetach ()
1135{
1136 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001137
Greg Clayton4fb400f2010-09-27 21:07:38 +00001138 if (m_gdb_comm.IsRunning())
1139 {
1140 bool timed_out = false;
1141 Mutex::Locker locker;
1142 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1143 {
1144 if (timed_out)
1145 error.SetErrorString("timed out sending interrupt packet");
1146 else
1147 error.SetErrorString("unknown error sending interrupt packet");
1148 }
1149 }
Chris Lattner24943d22010-06-08 16:52:24 +00001150 return error;
1151}
1152
Greg Clayton4fb400f2010-09-27 21:07:38 +00001153Error
1154ProcessGDBRemote::DoDetach()
1155{
1156 Error error;
1157 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1158 if (log)
1159 log->Printf ("ProcessGDBRemote::DoDetach()");
1160
1161 DisableAllBreakpointSites ();
1162
1163 StringExtractorGDBRemote response;
1164 size_t response_size = m_gdb_comm.SendPacketAndWaitForResponse("D", response, 2, false);
1165 if (response_size)
1166 {
1167 if (response.IsOKPacket())
1168 {
1169 if (log)
1170 log->Printf ("ProcessGDBRemote::DoDetach() detach was successful");
1171
1172 }
1173 else if (log)
1174 {
1175 log->Printf ("ProcessGDBRemote::DoDestroy() detach failed: %s", response.GetStringRef().c_str());
1176 }
1177 }
1178 else if (log)
1179 {
1180 log->PutCString ("ProcessGDBRemote::DoDestroy() detach failed for unknown reasons");
1181 }
1182 StopAsyncThread ();
1183 m_gdb_comm.StopReadThread();
1184 KillDebugserverProcess ();
1185 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
1186 SetPublicState (eStateDetached);
1187 return error;
1188}
Chris Lattner24943d22010-06-08 16:52:24 +00001189
1190Error
1191ProcessGDBRemote::DoDestroy ()
1192{
1193 Error error;
1194 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1195 if (log)
1196 log->Printf ("ProcessGDBRemote::DoDestroy()");
1197
1198 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001199 Mutex::Locker locker;
1200 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001201 DisableAllBreakpointSites ();
1202 SetExitStatus(-1, "process killed");
1203
1204 StringExtractorGDBRemote response;
1205 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1206 {
1207 if (log)
1208 {
1209 if (response.IsOKPacket())
1210 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1211 else
1212 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1213 }
1214 }
1215
1216 StopAsyncThread ();
1217 m_gdb_comm.StopReadThread();
1218 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001219 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001220 return error;
1221}
1222
1223ByteOrder
1224ProcessGDBRemote::GetByteOrder () const
1225{
1226 return m_byte_order;
1227}
1228
1229//------------------------------------------------------------------
1230// Process Queries
1231//------------------------------------------------------------------
1232
1233bool
1234ProcessGDBRemote::IsAlive ()
1235{
1236 return m_gdb_comm.IsConnected();
1237}
1238
1239addr_t
1240ProcessGDBRemote::GetImageInfoAddress()
1241{
1242 if (!m_gdb_comm.IsRunning())
1243 {
1244 StringExtractorGDBRemote response;
1245 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1246 {
1247 if (response.IsNormalPacket())
1248 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1249 }
1250 }
1251 return LLDB_INVALID_ADDRESS;
1252}
1253
1254DynamicLoader *
1255ProcessGDBRemote::GetDynamicLoader()
1256{
1257 return m_dynamic_loader_ap.get();
1258}
1259
1260//------------------------------------------------------------------
1261// Process Memory
1262//------------------------------------------------------------------
1263size_t
1264ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1265{
1266 if (size > m_max_memory_size)
1267 {
1268 // Keep memory read sizes down to a sane limit. This function will be
1269 // called multiple times in order to complete the task by
1270 // lldb_private::Process so it is ok to do this.
1271 size = m_max_memory_size;
1272 }
1273
1274 char packet[64];
1275 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1276 assert (packet_len + 1 < sizeof(packet));
1277 StringExtractorGDBRemote response;
1278 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1279 {
1280 if (response.IsNormalPacket())
1281 {
1282 error.Clear();
1283 return response.GetHexBytes(buf, size, '\xdd');
1284 }
1285 else if (response.IsErrorPacket())
1286 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1287 else if (response.IsUnsupportedPacket())
1288 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1289 else
1290 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1291 }
1292 else
1293 {
1294 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1295 }
1296 return 0;
1297}
1298
1299size_t
1300ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1301{
1302 StreamString packet;
1303 packet.Printf("M%llx,%zx:", addr, size);
1304 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1305 StringExtractorGDBRemote response;
1306 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1307 {
1308 if (response.IsOKPacket())
1309 {
1310 error.Clear();
1311 return size;
1312 }
1313 else if (response.IsErrorPacket())
1314 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1315 else if (response.IsUnsupportedPacket())
1316 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1317 else
1318 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1319 }
1320 else
1321 {
1322 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1323 }
1324 return 0;
1325}
1326
1327lldb::addr_t
1328ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1329{
1330 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1331 if (allocated_addr == LLDB_INVALID_ADDRESS)
1332 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1333 else
1334 error.Clear();
1335 return allocated_addr;
1336}
1337
1338Error
1339ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1340{
1341 Error error;
1342 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1343 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1344 return error;
1345}
1346
1347
1348//------------------------------------------------------------------
1349// Process STDIO
1350//------------------------------------------------------------------
1351
1352size_t
1353ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1354{
1355 Mutex::Locker locker(m_stdio_mutex);
1356 size_t bytes_available = m_stdout_data.size();
1357 if (bytes_available > 0)
1358 {
1359 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1360 if (bytes_available > buf_size)
1361 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001362 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001363 m_stdout_data.erase(0, buf_size);
1364 bytes_available = buf_size;
1365 }
1366 else
1367 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001368 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001369 m_stdout_data.clear();
1370
1371 //ResetEventBits(eBroadcastBitSTDOUT);
1372 }
1373 }
1374 return bytes_available;
1375}
1376
1377size_t
1378ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1379{
1380 // Can we get STDERR through the remote protocol?
1381 return 0;
1382}
1383
1384size_t
1385ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1386{
1387 if (m_stdio_communication.IsConnected())
1388 {
1389 ConnectionStatus status;
1390 m_stdio_communication.Write(src, src_len, status, NULL);
1391 }
1392 return 0;
1393}
1394
1395Error
1396ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1397{
1398 Error error;
1399 assert (bp_site != NULL);
1400
1401 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1402 user_id_t site_id = bp_site->GetID();
1403 const addr_t addr = bp_site->GetLoadAddress();
1404 if (log)
1405 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1406
1407 if (bp_site->IsEnabled())
1408 {
1409 if (log)
1410 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1411 return error;
1412 }
1413 else
1414 {
1415 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1416
1417 if (bp_site->HardwarePreferred())
1418 {
1419 // Try and set hardware breakpoint, and if that fails, fall through
1420 // and set a software breakpoint?
1421 }
1422
1423 if (m_z0_supported)
1424 {
1425 char packet[64];
1426 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1427 assert (packet_len + 1 < sizeof(packet));
1428 StringExtractorGDBRemote response;
1429 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1430 {
1431 if (response.IsUnsupportedPacket())
1432 {
1433 // Disable z packet support and try again
1434 m_z0_supported = 0;
1435 return EnableBreakpoint (bp_site);
1436 }
1437 else if (response.IsOKPacket())
1438 {
1439 bp_site->SetEnabled(true);
1440 bp_site->SetType (BreakpointSite::eExternal);
1441 return error;
1442 }
1443 else
1444 {
1445 uint8_t error_byte = response.GetError();
1446 if (error_byte)
1447 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1448 }
1449 }
1450 }
1451 else
1452 {
1453 return EnableSoftwareBreakpoint (bp_site);
1454 }
1455 }
1456
1457 if (log)
1458 {
1459 const char *err_string = error.AsCString();
1460 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1461 bp_site->GetLoadAddress(),
1462 err_string ? err_string : "NULL");
1463 }
1464 // We shouldn't reach here on a successful breakpoint enable...
1465 if (error.Success())
1466 error.SetErrorToGenericError();
1467 return error;
1468}
1469
1470Error
1471ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1472{
1473 Error error;
1474 assert (bp_site != NULL);
1475 addr_t addr = bp_site->GetLoadAddress();
1476 user_id_t site_id = bp_site->GetID();
1477 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1478 if (log)
1479 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1480
1481 if (bp_site->IsEnabled())
1482 {
1483 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1484
1485 if (bp_site->IsHardware())
1486 {
1487 // TODO: disable hardware breakpoint...
1488 }
1489 else
1490 {
1491 if (m_z0_supported)
1492 {
1493 char packet[64];
1494 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1495 assert (packet_len + 1 < sizeof(packet));
1496 StringExtractorGDBRemote response;
1497 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1498 {
1499 if (response.IsUnsupportedPacket())
1500 {
1501 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1502 }
1503 else if (response.IsOKPacket())
1504 {
1505 if (log)
1506 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1507 bp_site->SetEnabled(false);
1508 return error;
1509 }
1510 else
1511 {
1512 uint8_t error_byte = response.GetError();
1513 if (error_byte)
1514 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1515 }
1516 }
1517 }
1518 else
1519 {
1520 return DisableSoftwareBreakpoint (bp_site);
1521 }
1522 }
1523 }
1524 else
1525 {
1526 if (log)
1527 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1528 return error;
1529 }
1530
1531 if (error.Success())
1532 error.SetErrorToGenericError();
1533 return error;
1534}
1535
1536Error
1537ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1538{
1539 Error error;
1540 if (wp)
1541 {
1542 user_id_t watchID = wp->GetID();
1543 addr_t addr = wp->GetLoadAddress();
1544 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1545 if (log)
1546 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1547 if (wp->IsEnabled())
1548 {
1549 if (log)
1550 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1551 return error;
1552 }
1553 else
1554 {
1555 // Pass down an appropriate z/Z packet...
1556 error.SetErrorString("watchpoints not supported");
1557 }
1558 }
1559 else
1560 {
1561 error.SetErrorString("Watchpoint location argument was NULL.");
1562 }
1563 if (error.Success())
1564 error.SetErrorToGenericError();
1565 return error;
1566}
1567
1568Error
1569ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1570{
1571 Error error;
1572 if (wp)
1573 {
1574 user_id_t watchID = wp->GetID();
1575
1576 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1577
1578 addr_t addr = wp->GetLoadAddress();
1579 if (log)
1580 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1581
1582 if (wp->IsHardware())
1583 {
1584 // Pass down an appropriate z/Z packet...
1585 error.SetErrorString("watchpoints not supported");
1586 }
1587 // TODO: clear software watchpoints if we implement them
1588 }
1589 else
1590 {
1591 error.SetErrorString("Watchpoint location argument was NULL.");
1592 }
1593 if (error.Success())
1594 error.SetErrorToGenericError();
1595 return error;
1596}
1597
1598void
1599ProcessGDBRemote::Clear()
1600{
1601 m_flags = 0;
1602 m_thread_list.Clear();
1603 {
1604 Mutex::Locker locker(m_stdio_mutex);
1605 m_stdout_data.clear();
1606 }
1607 DestoryLibUnwindAddressSpace();
1608}
1609
1610Error
1611ProcessGDBRemote::DoSignal (int signo)
1612{
1613 Error error;
1614 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1615 if (log)
1616 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1617
1618 if (!m_gdb_comm.SendAsyncSignal (signo))
1619 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1620 return error;
1621}
1622
Chris Lattner24943d22010-06-08 16:52:24 +00001623void
1624ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1625{
1626 ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1627 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1628}
1629
1630void
1631ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1632{
1633 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1634 Mutex::Locker locker(m_stdio_mutex);
1635 m_stdout_data.append(s, len);
1636
1637 // FIXME: Make a real data object for this and put it out.
1638 BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1639}
1640
1641
1642Error
1643ProcessGDBRemote::StartDebugserverProcess
1644(
1645 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1646 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1647 char const *inferior_envp[], // Environment to pass along to the inferior program
1648 char const *stdio_path,
1649 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID then attach to this attach_pid
1650 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1651 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Clayton452bf612010-08-31 18:35:14 +00001652 bool disable_aslr, // Disable ASLR
Chris Lattner24943d22010-06-08 16:52:24 +00001653 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1654)
1655{
1656 Error error;
1657 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1658 {
1659 // If we locate debugserver, keep that located version around
1660 static FileSpec g_debugserver_file_spec;
1661
1662 FileSpec debugserver_file_spec;
1663 char debugserver_path[PATH_MAX];
1664
1665 // Always check to see if we have an environment override for the path
1666 // to the debugserver to use and use it if we do.
1667 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1668 if (env_debugserver_path)
1669 debugserver_file_spec.SetFile (env_debugserver_path);
1670 else
1671 debugserver_file_spec = g_debugserver_file_spec;
1672 bool debugserver_exists = debugserver_file_spec.Exists();
1673 if (!debugserver_exists)
1674 {
1675 // The debugserver binary is in the LLDB.framework/Resources
1676 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001677 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001678 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001679 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001680 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001681 if (debugserver_exists)
1682 {
1683 g_debugserver_file_spec = debugserver_file_spec;
1684 }
1685 else
1686 {
1687 g_debugserver_file_spec.Clear();
1688 debugserver_file_spec.Clear();
1689 }
Chris Lattner24943d22010-06-08 16:52:24 +00001690 }
1691 }
1692
1693 if (debugserver_exists)
1694 {
1695 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1696
1697 m_stdio_communication.Clear();
1698 posix_spawnattr_t attr;
1699
1700 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
1701
1702 Error local_err; // Errors that don't affect the spawning.
1703 if (log)
1704 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1705 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1706 if (error.Fail() || log)
1707 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
1708 if (error.Fail())
1709 return error;;
1710
1711#if !defined (__arm__)
1712
Greg Clayton24b48ff2010-10-17 22:03:32 +00001713 // We don't need to do this for ARM, and we really shouldn't now
1714 // that we have multiple CPU subtypes and no posix_spawnattr call
1715 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001716 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001717 {
Greg Claytoncf015052010-06-11 03:25:34 +00001718 cpu_type_t cpu = inferior_arch.GetCPUType();
1719 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1720 {
1721 size_t ocount = 0;
1722 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1723 if (error.Fail() || log)
1724 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 +00001725
Greg Claytoncf015052010-06-11 03:25:34 +00001726 if (error.Fail() != 0 || ocount != 1)
1727 return error;
1728 }
Chris Lattner24943d22010-06-08 16:52:24 +00001729 }
1730
1731#endif
1732
1733 Args debugserver_args;
1734 char arg_cstr[PATH_MAX];
1735 bool launch_process = true;
1736
1737 if (inferior_argv == NULL && attach_pid != LLDB_INVALID_PROCESS_ID)
1738 launch_process = false;
1739 else if (attach_name)
1740 launch_process = false; // Wait for a process whose basename matches that in inferior_argv[0]
1741
1742 bool pass_stdio_path_to_debugserver = true;
1743 lldb_utility::PseudoTerminal pty;
1744 if (stdio_path == NULL)
1745 {
1746 pass_stdio_path_to_debugserver = false;
1747 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
1748 {
1749 struct termios stdin_termios;
1750 if (::tcgetattr (pty.GetMasterFileDescriptor(), &stdin_termios) == 0)
1751 {
1752 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing
1753 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time
1754 ::tcsetattr (pty.GetMasterFileDescriptor(), TCSANOW, &stdin_termios);
1755 }
1756 stdio_path = pty.GetSlaveName (NULL, 0);
1757 }
1758 }
1759
1760 // Start args with "debugserver /file/path -r --"
1761 debugserver_args.AppendArgument(debugserver_path);
1762 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001763 // use native registers, not the GDB registers
1764 debugserver_args.AppendArgument("--native-regs");
1765 // make debugserver run in its own session so signals generated by
1766 // special terminal key sequences (^C) don't affect debugserver
1767 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001768
Greg Clayton452bf612010-08-31 18:35:14 +00001769 if (disable_aslr)
1770 debugserver_args.AppendArguments("--disable-aslr");
1771
Chris Lattner24943d22010-06-08 16:52:24 +00001772 // Only set the inferior
1773 if (launch_process)
1774 {
1775 if (stdio_path && pass_stdio_path_to_debugserver)
1776 {
1777 debugserver_args.AppendArgument("-s"); // short for --stdio-path
1778 StreamString strm;
1779 strm.Printf("'%s'", stdio_path);
1780 debugserver_args.AppendArgument(strm.GetData()); // path to file to have inferior open as it's STDIO
1781 }
1782 }
1783
1784 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1785 if (env_debugserver_log_file)
1786 {
1787 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1788 debugserver_args.AppendArgument(arg_cstr);
1789 }
1790
1791 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1792 if (env_debugserver_log_flags)
1793 {
1794 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1795 debugserver_args.AppendArgument(arg_cstr);
1796 }
1797// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1798// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1799
1800 // Now append the program arguments
1801 if (launch_process)
1802 {
1803 if (inferior_argv)
1804 {
1805 // Terminate the debugserver args so we can now append the inferior args
1806 debugserver_args.AppendArgument("--");
1807
1808 for (int i = 0; inferior_argv[i] != NULL; ++i)
1809 debugserver_args.AppendArgument (inferior_argv[i]);
1810 }
1811 else
1812 {
1813 // Will send environment entries with the 'QEnvironment:' packet
1814 // Will send arguments with the 'A' packet
1815 }
1816 }
1817 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1818 {
1819 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1820 debugserver_args.AppendArgument (arg_cstr);
1821 }
1822 else if (attach_name && attach_name[0])
1823 {
1824 if (wait_for_launch)
1825 debugserver_args.AppendArgument ("--waitfor");
1826 else
1827 debugserver_args.AppendArgument ("--attach");
1828 debugserver_args.AppendArgument (attach_name);
1829 }
1830
1831 Error file_actions_err;
1832 posix_spawn_file_actions_t file_actions;
1833#if DONT_CLOSE_DEBUGSERVER_STDIO
1834 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1835#else
1836 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1837 if (file_actions_err.Success())
1838 {
1839 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1840 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1841 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1842 }
1843#endif
1844
1845 if (log)
1846 {
1847 StreamString strm;
1848 debugserver_args.Dump (&strm);
1849 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1850 }
1851
1852 error.SetError(::posix_spawnp (&m_debugserver_pid,
1853 debugserver_path,
1854 file_actions_err.Success() ? &file_actions : NULL,
1855 &attr,
1856 debugserver_args.GetArgumentVector(),
1857 (char * const*)inferior_envp),
1858 eErrorTypePOSIX);
1859
Greg Claytone9d0df42010-07-02 01:29:13 +00001860
1861 ::posix_spawnattr_destroy (&attr);
1862
Chris Lattner24943d22010-06-08 16:52:24 +00001863 if (file_actions_err.Success())
1864 ::posix_spawn_file_actions_destroy (&file_actions);
1865
1866 // We have seen some cases where posix_spawnp was returning a valid
1867 // looking pid even when an error was returned, so clear it out
1868 if (error.Fail())
1869 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1870
1871 if (error.Fail() || log)
1872 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);
1873
1874// if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1875// {
1876// std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true));
1877// if (conn_ap.get())
1878// {
1879// m_stdio_communication.SetConnection(conn_ap.release());
1880// if (m_stdio_communication.IsConnected())
1881// {
1882// m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1883// m_stdio_communication.StartReadThread();
1884// }
1885// }
1886// }
1887 }
1888 else
1889 {
1890 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1891 }
1892
1893 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1894 StartAsyncThread ();
1895 }
1896 return error;
1897}
1898
1899bool
1900ProcessGDBRemote::MonitorDebugserverProcess
1901(
1902 void *callback_baton,
1903 lldb::pid_t debugserver_pid,
1904 int signo, // Zero for no signal
1905 int exit_status // Exit value of process if signal is zero
1906)
1907{
1908 // We pass in the ProcessGDBRemote inferior process it and name it
1909 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1910 // pointer value itself, thus we need the double cast...
1911
1912 // "debugserver_pid" argument passed in is the process ID for
1913 // debugserver that we are tracking...
1914
Greg Clayton75ccf502010-08-21 02:22:51 +00001915 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1916
1917 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001918 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001919 // Sleep for a half a second to make sure our inferior process has
1920 // time to set its exit status before we set it incorrectly when
1921 // both the debugserver and the inferior process shut down.
1922 usleep (500000);
1923 // If our process hasn't yet exited, debugserver might have died.
1924 // If the process did exit, the we are reaping it.
1925 if (process->GetState() != eStateExited)
Chris Lattner24943d22010-06-08 16:52:24 +00001926 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001927 char error_str[1024];
1928 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001929 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001930 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1931 if (signal_cstr)
1932 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001933 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001934 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001935 }
1936 else
1937 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001938 ::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 +00001939 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001940
1941 process->SetExitStatus (-1, error_str);
1942 }
1943 else
1944 {
1945 // Debugserver has exited we need to let our ProcessGDBRemote
1946 // know that it no longer has a debugserver instance
1947 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1948 // We are returning true to this function below, so we can
1949 // forget about the monitor handle.
1950 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001951 }
1952 }
1953 return true;
1954}
1955
1956void
1957ProcessGDBRemote::KillDebugserverProcess ()
1958{
1959 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1960 {
1961 ::kill (m_debugserver_pid, SIGINT);
1962 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1963 }
1964}
1965
1966void
1967ProcessGDBRemote::Initialize()
1968{
1969 static bool g_initialized = false;
1970
1971 if (g_initialized == false)
1972 {
1973 g_initialized = true;
1974 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1975 GetPluginDescriptionStatic(),
1976 CreateInstance);
1977
1978 Log::Callbacks log_callbacks = {
1979 ProcessGDBRemoteLog::DisableLog,
1980 ProcessGDBRemoteLog::EnableLog,
1981 ProcessGDBRemoteLog::ListLogCategories
1982 };
1983
1984 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1985 }
1986}
1987
1988bool
1989ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1990{
1991 if (m_curr_tid == tid)
1992 return true;
1993
1994 char packet[32];
1995 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1996 assert (packet_len + 1 < sizeof(packet));
1997 StringExtractorGDBRemote response;
1998 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1999 {
2000 if (response.IsOKPacket())
2001 {
2002 m_curr_tid = tid;
2003 return true;
2004 }
2005 }
2006 return false;
2007}
2008
2009bool
2010ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2011{
2012 if (m_curr_tid_run == tid)
2013 return true;
2014
2015 char packet[32];
2016 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2017 assert (packet_len + 1 < sizeof(packet));
2018 StringExtractorGDBRemote response;
2019 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2020 {
2021 if (response.IsOKPacket())
2022 {
2023 m_curr_tid_run = tid;
2024 return true;
2025 }
2026 }
2027 return false;
2028}
2029
2030void
2031ProcessGDBRemote::ResetGDBRemoteState ()
2032{
2033 // Reset and GDB remote state
2034 m_curr_tid = LLDB_INVALID_THREAD_ID;
2035 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2036 m_z0_supported = 1;
2037}
2038
2039
2040bool
2041ProcessGDBRemote::StartAsyncThread ()
2042{
2043 ResetGDBRemoteState ();
2044
2045 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2046
2047 if (log)
2048 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2049
2050 // Create a thread that watches our internal state and controls which
2051 // events make it to clients (into the DCProcess event queue).
2052 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2053 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2054}
2055
2056void
2057ProcessGDBRemote::StopAsyncThread ()
2058{
2059 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2060
2061 if (log)
2062 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2063
2064 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2065
2066 // Stop the stdio thread
2067 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2068 {
2069 Host::ThreadJoin (m_async_thread, NULL, NULL);
2070 }
2071}
2072
2073
2074void *
2075ProcessGDBRemote::AsyncThread (void *arg)
2076{
2077 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2078
2079 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
2080 if (log)
2081 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2082
2083 Listener listener ("ProcessGDBRemote::AsyncThread");
2084 EventSP event_sp;
2085 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2086 eBroadcastBitAsyncThreadShouldExit;
2087
2088 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2089 {
2090 bool done = false;
2091 while (!done)
2092 {
2093 if (log)
2094 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2095 if (listener.WaitForEvent (NULL, event_sp))
2096 {
2097 const uint32_t event_type = event_sp->GetType();
2098 switch (event_type)
2099 {
2100 case eBroadcastBitAsyncContinue:
2101 {
2102 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2103
2104 if (continue_packet)
2105 {
2106 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2107 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2108 if (log)
2109 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2110
2111 process->SetPrivateState(eStateRunning);
2112 StringExtractorGDBRemote response;
2113 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2114
2115 switch (stop_state)
2116 {
2117 case eStateStopped:
2118 case eStateCrashed:
2119 case eStateSuspended:
2120 process->m_last_stop_packet = response;
2121 process->m_last_stop_packet.SetFilePos (0);
2122 process->SetPrivateState (stop_state);
2123 break;
2124
2125 case eStateExited:
2126 process->m_last_stop_packet = response;
2127 process->m_last_stop_packet.SetFilePos (0);
2128 response.SetFilePos(1);
2129 process->SetExitStatus(response.GetHexU8(), NULL);
2130 done = true;
2131 break;
2132
2133 case eStateInvalid:
2134 break;
2135
2136 default:
2137 process->SetPrivateState (stop_state);
2138 break;
2139 }
2140 }
2141 }
2142 break;
2143
2144 case eBroadcastBitAsyncThreadShouldExit:
2145 if (log)
2146 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2147 done = true;
2148 break;
2149
2150 default:
2151 if (log)
2152 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2153 done = true;
2154 break;
2155 }
2156 }
2157 else
2158 {
2159 if (log)
2160 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2161 done = true;
2162 }
2163 }
2164 }
2165
2166 if (log)
2167 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2168
2169 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2170 return NULL;
2171}
2172
2173lldb_private::unw_addr_space_t
2174ProcessGDBRemote::GetLibUnwindAddressSpace ()
2175{
2176 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002177
2178 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2179 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002180 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002181 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002182 target_type = UNW_TARGET_X86_64;
2183
2184 if (m_libunwind_addr_space)
2185 {
2186 if (m_libunwind_target_type != target_type)
2187 DestoryLibUnwindAddressSpace();
2188 else
2189 return m_libunwind_addr_space;
2190 }
2191 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2192 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2193 if (m_libunwind_addr_space)
2194 m_libunwind_target_type = target_type;
2195 else
2196 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2197 return m_libunwind_addr_space;
2198}
2199
2200void
2201ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2202{
2203 if (m_libunwind_addr_space)
2204 {
2205 unw_destroy_addr_space (m_libunwind_addr_space);
2206 m_libunwind_addr_space = NULL;
2207 }
2208 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2209}
2210
2211
2212const char *
2213ProcessGDBRemote::GetDispatchQueueNameForThread
2214(
2215 addr_t thread_dispatch_qaddr,
2216 std::string &dispatch_queue_name
2217)
2218{
2219 dispatch_queue_name.clear();
2220 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2221 {
2222 // Cache the dispatch_queue_offsets_addr value so we don't always have
2223 // to look it up
2224 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2225 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002226 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2227 const Symbol *dispatch_queue_offsets_symbol = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00002228 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib")));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002229 if (module_sp)
2230 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2231
2232 if (dispatch_queue_offsets_symbol == NULL)
2233 {
2234 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib"));
2235 if (module_sp)
2236 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2237 }
Chris Lattner24943d22010-06-08 16:52:24 +00002238 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002239 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002240
2241 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2242 return NULL;
2243 }
2244
2245 uint8_t memory_buffer[8];
2246 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2247
2248 // Excerpt from src/queue_private.h
2249 struct dispatch_queue_offsets_s
2250 {
2251 uint16_t dqo_version;
2252 uint16_t dqo_label;
2253 uint16_t dqo_label_size;
2254 } dispatch_queue_offsets;
2255
2256
2257 Error error;
2258 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2259 {
2260 uint32_t data_offset = 0;
2261 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2262 {
2263 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2264 {
2265 data_offset = 0;
2266 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2267 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2268 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2269 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2270 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2271 dispatch_queue_name.erase (bytes_read);
2272 }
2273 }
2274 }
2275 }
2276 if (dispatch_queue_name.empty())
2277 return NULL;
2278 return dispatch_queue_name.c_str();
2279}
2280
Jim Ingham7508e732010-08-09 23:31:02 +00002281uint32_t
2282ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2283{
2284 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2285 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2286 if (m_local_debugserver)
2287 {
2288 return Host::ListProcessesMatchingName (name, matches, pids);
2289 }
2290 else
2291 {
2292 // FIXME: Implement talking to the remote debugserver.
2293 return 0;
2294 }
2295
2296}