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