blob: d84fedd9b48d6e67637d3e37ab016f58c84bf44b [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 {
655 SetPrivateState (eStateAttaching);
656 char host_port[128];
657 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000658 error = StartDebugserverProcess (host_port, // debugserver_url
659 NULL, // inferior_argv
660 NULL, // inferior_envp
661 NULL, // stdin_path
662 LLDB_INVALID_PROCESS_ID, // attach_pid
663 NULL, // attach_pid_name
664 false, // wait_for_launch
665 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000666 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000667
668 if (error.Fail())
669 {
670 const char *error_string = error.AsCString();
671 if (error_string == NULL)
672 error_string = "unable to launch " DEBUGSERVER_BASENAME;
673
674 SetExitStatus (-1, error_string);
675 }
676 else
677 {
678 error = ConnectToDebugserver (host_port);
679 if (error.Success())
680 {
681 char packet[64];
682 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
683 StringExtractorGDBRemote response;
684 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
685 packet,
686 packet_len,
687 response);
688 switch (stop_state)
689 {
690 case eStateStopped:
691 case eStateCrashed:
692 case eStateSuspended:
693 SetID (attach_pid);
694 m_last_stop_packet = response;
695 m_last_stop_packet.SetFilePos (0);
696 SetPrivateState (stop_state);
697 break;
698
699 case eStateExited:
700 m_last_stop_packet = response;
701 m_last_stop_packet.SetFilePos (0);
702 response.SetFilePos(1);
703 SetExitStatus(response.GetHexU8(), NULL);
704 break;
705
706 default:
707 SetExitStatus(-1, "unable to attach to process");
708 break;
709 }
710
711 }
712 }
713 }
714
715 lldb::pid_t pid = GetID();
716 if (pid == LLDB_INVALID_PROCESS_ID)
717 {
718 KillDebugserverProcess();
719 }
720 return error;
721}
722
723size_t
724ProcessGDBRemote::AttachInputReaderCallback
725(
726 void *baton,
727 InputReader *reader,
728 lldb::InputReaderAction notification,
729 const char *bytes,
730 size_t bytes_len
731)
732{
733 if (notification == eInputReaderGotToken)
734 {
735 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
736 if (gdb_process->m_waiting_for_attach)
737 gdb_process->m_waiting_for_attach = false;
738 reader->SetIsDone(true);
739 return 1;
740 }
741 return 0;
742}
743
744Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000745ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000746{
747 Error error;
748 // Clear out and clean up from any current state
749 Clear();
750 // HACK: require arch be set correctly at the target level until we can
751 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000752
753 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
754 if (process_name && process_name[0])
755 {
756
757 SetPrivateState (eStateAttaching);
758 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000759 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000760 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000761 error = StartDebugserverProcess (host_port, // debugserver_url
762 NULL, // inferior_argv
763 NULL, // inferior_envp
764 NULL, // stdin_path
765 LLDB_INVALID_PROCESS_ID, // attach_pid
766 NULL, // attach_pid_name
767 false, // wait_for_launch
768 false, // disable_aslr
Jim Ingham7508e732010-08-09 23:31:02 +0000769 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000770 if (error.Fail())
771 {
772 const char *error_string = error.AsCString();
773 if (error_string == NULL)
774 error_string = "unable to launch " DEBUGSERVER_BASENAME;
775
776 SetExitStatus (-1, error_string);
777 }
778 else
779 {
780 error = ConnectToDebugserver (host_port);
781 if (error.Success())
782 {
783 StreamString packet;
784
785 packet.PutCString("vAttach");
786 if (wait_for_launch)
787 packet.PutCString("Wait");
788 packet.PutChar(';');
789 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
790 StringExtractorGDBRemote response;
791 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
792 packet.GetData(),
793 packet.GetSize(),
794 response);
795 switch (stop_state)
796 {
797 case eStateStopped:
798 case eStateCrashed:
799 case eStateSuspended:
800 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
801 m_last_stop_packet = response;
802 m_last_stop_packet.SetFilePos (0);
803 SetPrivateState (stop_state);
804 break;
805
806 case eStateExited:
807 m_last_stop_packet = response;
808 m_last_stop_packet.SetFilePos (0);
809 response.SetFilePos(1);
810 SetExitStatus(response.GetHexU8(), NULL);
811 break;
812
813 default:
814 SetExitStatus(-1, "unable to attach to process");
815 break;
816 }
817 }
818 }
819 }
820
821 lldb::pid_t pid = GetID();
822 if (pid == LLDB_INVALID_PROCESS_ID)
823 {
824 KillDebugserverProcess();
825 }
826 return error;
827}
828
829//
830// if (wait_for_launch)
831// {
832// InputReaderSP reader_sp (new InputReader());
833// StreamString instructions;
834// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
835// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
836// this, // baton
837// eInputReaderGranularityByte,
838// NULL, // End token
839// false);
840//
841// StringExtractorGDBRemote response;
842// m_waiting_for_attach = true;
843// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
844// while (m_waiting_for_attach)
845// {
846// // Wait for one second for the stop reply packet
847// if (m_gdb_comm.WaitForPacket(response, 1))
848// {
849// // Got some sort of packet, see if it is the stop reply packet?
850// char ch = response.GetChar(0);
851// if (ch == 'T')
852// {
853// m_waiting_for_attach = false;
854// }
855// }
856// else
857// {
858// // Put a period character every second
859// fputc('.', reader_out_fh);
860// }
861// }
862// }
863// }
864// return GetID();
865//}
866
867void
868ProcessGDBRemote::DidAttach ()
869{
Jim Ingham7508e732010-08-09 23:31:02 +0000870 // If we haven't got an executable module yet, then we should make a dynamic loader, and
871 // see if it can find the executable module for us. If we do have an executable module,
872 // make sure it matches the process we've just attached to.
873
874 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
875 if (!m_dynamic_loader_ap.get())
876 {
877 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
878 }
879
Chris Lattner24943d22010-06-08 16:52:24 +0000880 if (m_dynamic_loader_ap.get())
881 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000882
883 Module * new_exe_module = GetTarget().GetExecutableModule().get();
884 if (new_exe_module == NULL)
885 {
886
887 }
888
889 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000890}
891
892Error
893ProcessGDBRemote::WillResume ()
894{
895 m_continue_packet.Clear();
896 // Start the continue packet we will use to run the target. Each thread
897 // will append what it is supposed to be doing to this packet when the
898 // ThreadList::WillResume() is called. If a thread it supposed
899 // to stay stopped, then don't append anything to this string.
900 m_continue_packet.Printf("vCont");
901 return Error();
902}
903
904Error
905ProcessGDBRemote::DoResume ()
906{
907 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
908 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
909 return Error();
910}
911
912size_t
913ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
914{
915 const uint8_t *trap_opcode = NULL;
916 uint32_t trap_opcode_size = 0;
917
918 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
919 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
920 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
921 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
922
Jim Ingham7508e732010-08-09 23:31:02 +0000923 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000924 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000925 {
Greg Claytoncf015052010-06-11 03:25:34 +0000926 case ArchSpec::eCPU_i386:
927 case ArchSpec::eCPU_x86_64:
928 trap_opcode = g_i386_breakpoint_opcode;
929 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
930 break;
931
932 case ArchSpec::eCPU_arm:
933 // TODO: fill this in for ARM. We need to dig up the symbol for
934 // the address in the breakpoint locaiton and figure out if it is
935 // an ARM or Thumb breakpoint.
936 trap_opcode = g_arm_breakpoint_opcode;
937 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
938 break;
939
940 case ArchSpec::eCPU_ppc:
941 case ArchSpec::eCPU_ppc64:
942 trap_opcode = g_ppc_breakpoint_opcode;
943 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
944 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000945
Greg Claytoncf015052010-06-11 03:25:34 +0000946 default:
947 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
948 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000949 }
950
951 if (trap_opcode && trap_opcode_size)
952 {
953 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
954 return trap_opcode_size;
955 }
956 return 0;
957}
958
959uint32_t
960ProcessGDBRemote::UpdateThreadListIfNeeded ()
961{
962 // locker will keep a mutex locked until it goes out of scope
963 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD);
964 if (log && log->GetMask().IsSet(GDBR_LOG_VERBOSE))
965 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
966
Greg Clayton5205f0b2010-09-03 17:10:42 +0000967 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000968 const uint32_t stop_id = GetStopID();
969 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
970 {
971 // Update the thread list's stop id immediately so we don't recurse into this function.
972 ThreadList curr_thread_list (this);
973 curr_thread_list.SetStopID(stop_id);
974
975 Error err;
976 StringExtractorGDBRemote response;
977 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
978 response.IsNormalPacket();
979 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
980 {
981 char ch = response.GetChar();
982 if (ch == 'l')
983 break;
984 if (ch == 'm')
985 {
986 do
987 {
988 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
989
990 if (tid != LLDB_INVALID_THREAD_ID)
991 {
992 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
993 if (thread_sp)
994 thread_sp->GetRegisterContext()->Invalidate();
995 else
996 thread_sp.reset (new ThreadGDBRemote (*this, tid));
997 curr_thread_list.AddThread(thread_sp);
998 }
999
1000 ch = response.GetChar();
1001 } while (ch == ',');
1002 }
1003 }
1004
1005 m_thread_list = curr_thread_list;
1006
1007 SetThreadStopInfo (m_last_stop_packet);
1008 }
1009 return GetThreadList().GetSize(false);
1010}
1011
1012
1013StateType
1014ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1015{
1016 const char stop_type = stop_packet.GetChar();
1017 switch (stop_type)
1018 {
1019 case 'T':
1020 case 'S':
1021 {
1022 // Stop with signal and thread info
1023 const uint8_t signo = stop_packet.GetHexU8();
1024 std::string name;
1025 std::string value;
1026 std::string thread_name;
1027 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001028 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001029 uint32_t tid = LLDB_INVALID_THREAD_ID;
1030 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1031 uint32_t exc_data_count = 0;
1032 while (stop_packet.GetNameColonValue(name, value))
1033 {
1034 if (name.compare("metype") == 0)
1035 {
1036 // exception type in big endian hex
1037 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1038 }
1039 else if (name.compare("mecount") == 0)
1040 {
1041 // exception count in big endian hex
1042 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1043 }
1044 else if (name.compare("medata") == 0)
1045 {
1046 // exception data in big endian hex
1047 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1048 }
1049 else if (name.compare("thread") == 0)
1050 {
1051 // thread in big endian hex
1052 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
1053 }
1054 else if (name.compare("name") == 0)
1055 {
1056 thread_name.swap (value);
1057 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001058 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001059 {
1060 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1061 }
1062 }
1063 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false));
1064
1065 if (thread_sp)
1066 {
1067 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1068
1069 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1070 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001071 if (exc_type != 0)
1072 {
Greg Clayton643ee732010-08-04 01:40:35 +00001073 const size_t exc_data_count = exc_data.size();
1074
1075 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1076 exc_type,
1077 exc_data_count,
1078 exc_data_count >= 1 ? exc_data[0] : 0,
1079 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001080 }
1081 else if (signo)
1082 {
Greg Clayton643ee732010-08-04 01:40:35 +00001083 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001084 }
1085 else
1086 {
Greg Clayton643ee732010-08-04 01:40:35 +00001087 StopInfoSP invalid_stop_info_sp;
1088 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001089 }
1090 }
1091 return eStateStopped;
1092 }
1093 break;
1094
1095 case 'W':
1096 // process exited
1097 return eStateExited;
1098
1099 default:
1100 break;
1101 }
1102 return eStateInvalid;
1103}
1104
1105void
1106ProcessGDBRemote::RefreshStateAfterStop ()
1107{
Jim Ingham7508e732010-08-09 23:31:02 +00001108 // FIXME - add a variable to tell that we're in the middle of attaching if we
1109 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001110 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001111// if (!GetTarget().GetArchitecture().IsValid())
1112// {
1113// Module *exe_module = GetTarget().GetExecutableModule().get();
1114// if (exe_module)
1115// m_arch_spec = exe_module->GetArchitecture();
1116// }
1117
Chris Lattner24943d22010-06-08 16:52:24 +00001118 // Let all threads recover from stopping and do any clean up based
1119 // on the previous thread state (if any).
1120 m_thread_list.RefreshStateAfterStop();
1121
1122 // Discover new threads:
1123 UpdateThreadListIfNeeded ();
1124}
1125
1126Error
1127ProcessGDBRemote::DoHalt ()
1128{
1129 Error error;
1130 if (m_gdb_comm.IsRunning())
1131 {
1132 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001133 Mutex::Locker locker;
1134 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001135 {
1136 if (timed_out)
1137 error.SetErrorString("timed out sending interrupt packet");
1138 else
1139 error.SetErrorString("unknown error sending interrupt packet");
1140 }
1141 }
1142 return error;
1143}
1144
1145Error
1146ProcessGDBRemote::WillDetach ()
1147{
1148 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001149
Greg Clayton4fb400f2010-09-27 21:07:38 +00001150 if (m_gdb_comm.IsRunning())
1151 {
1152 bool timed_out = false;
1153 Mutex::Locker locker;
1154 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1155 {
1156 if (timed_out)
1157 error.SetErrorString("timed out sending interrupt packet");
1158 else
1159 error.SetErrorString("unknown error sending interrupt packet");
1160 }
1161 }
Chris Lattner24943d22010-06-08 16:52:24 +00001162 return error;
1163}
1164
Greg Clayton4fb400f2010-09-27 21:07:38 +00001165Error
1166ProcessGDBRemote::DoDetach()
1167{
1168 Error error;
1169 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1170 if (log)
1171 log->Printf ("ProcessGDBRemote::DoDetach()");
1172
1173 DisableAllBreakpointSites ();
1174
1175 StringExtractorGDBRemote response;
1176 size_t response_size = m_gdb_comm.SendPacketAndWaitForResponse("D", response, 2, false);
1177 if (response_size)
1178 {
1179 if (response.IsOKPacket())
1180 {
1181 if (log)
1182 log->Printf ("ProcessGDBRemote::DoDetach() detach was successful");
1183
1184 }
1185 else if (log)
1186 {
1187 log->Printf ("ProcessGDBRemote::DoDestroy() detach failed: %s", response.GetStringRef().c_str());
1188 }
1189 }
1190 else if (log)
1191 {
1192 log->PutCString ("ProcessGDBRemote::DoDestroy() detach failed for unknown reasons");
1193 }
1194 StopAsyncThread ();
1195 m_gdb_comm.StopReadThread();
1196 KillDebugserverProcess ();
1197 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
1198 SetPublicState (eStateDetached);
1199 return error;
1200}
Chris Lattner24943d22010-06-08 16:52:24 +00001201
1202Error
1203ProcessGDBRemote::DoDestroy ()
1204{
1205 Error error;
1206 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1207 if (log)
1208 log->Printf ("ProcessGDBRemote::DoDestroy()");
1209
1210 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001211 Mutex::Locker locker;
1212 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001213 DisableAllBreakpointSites ();
1214 SetExitStatus(-1, "process killed");
1215
1216 StringExtractorGDBRemote response;
1217 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false))
1218 {
1219 if (log)
1220 {
1221 if (response.IsOKPacket())
1222 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1223 else
1224 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1225 }
1226 }
1227
1228 StopAsyncThread ();
1229 m_gdb_comm.StopReadThread();
1230 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001231 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001232 return error;
1233}
1234
1235ByteOrder
1236ProcessGDBRemote::GetByteOrder () const
1237{
1238 return m_byte_order;
1239}
1240
1241//------------------------------------------------------------------
1242// Process Queries
1243//------------------------------------------------------------------
1244
1245bool
1246ProcessGDBRemote::IsAlive ()
1247{
1248 return m_gdb_comm.IsConnected();
1249}
1250
1251addr_t
1252ProcessGDBRemote::GetImageInfoAddress()
1253{
1254 if (!m_gdb_comm.IsRunning())
1255 {
1256 StringExtractorGDBRemote response;
1257 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1258 {
1259 if (response.IsNormalPacket())
1260 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1261 }
1262 }
1263 return LLDB_INVALID_ADDRESS;
1264}
1265
1266DynamicLoader *
1267ProcessGDBRemote::GetDynamicLoader()
1268{
1269 return m_dynamic_loader_ap.get();
1270}
1271
1272//------------------------------------------------------------------
1273// Process Memory
1274//------------------------------------------------------------------
1275size_t
1276ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1277{
1278 if (size > m_max_memory_size)
1279 {
1280 // Keep memory read sizes down to a sane limit. This function will be
1281 // called multiple times in order to complete the task by
1282 // lldb_private::Process so it is ok to do this.
1283 size = m_max_memory_size;
1284 }
1285
1286 char packet[64];
1287 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1288 assert (packet_len + 1 < sizeof(packet));
1289 StringExtractorGDBRemote response;
1290 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1291 {
1292 if (response.IsNormalPacket())
1293 {
1294 error.Clear();
1295 return response.GetHexBytes(buf, size, '\xdd');
1296 }
1297 else if (response.IsErrorPacket())
1298 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1299 else if (response.IsUnsupportedPacket())
1300 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1301 else
1302 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1303 }
1304 else
1305 {
1306 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1307 }
1308 return 0;
1309}
1310
1311size_t
1312ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1313{
1314 StreamString packet;
1315 packet.Printf("M%llx,%zx:", addr, size);
1316 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1317 StringExtractorGDBRemote response;
1318 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1319 {
1320 if (response.IsOKPacket())
1321 {
1322 error.Clear();
1323 return size;
1324 }
1325 else if (response.IsErrorPacket())
1326 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1327 else if (response.IsUnsupportedPacket())
1328 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1329 else
1330 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1331 }
1332 else
1333 {
1334 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1335 }
1336 return 0;
1337}
1338
1339lldb::addr_t
1340ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1341{
1342 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1343 if (allocated_addr == LLDB_INVALID_ADDRESS)
1344 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1345 else
1346 error.Clear();
1347 return allocated_addr;
1348}
1349
1350Error
1351ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1352{
1353 Error error;
1354 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1355 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1356 return error;
1357}
1358
1359
1360//------------------------------------------------------------------
1361// Process STDIO
1362//------------------------------------------------------------------
1363
1364size_t
1365ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1366{
1367 Mutex::Locker locker(m_stdio_mutex);
1368 size_t bytes_available = m_stdout_data.size();
1369 if (bytes_available > 0)
1370 {
1371 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1372 if (bytes_available > buf_size)
1373 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001374 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001375 m_stdout_data.erase(0, buf_size);
1376 bytes_available = buf_size;
1377 }
1378 else
1379 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001380 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001381 m_stdout_data.clear();
1382
1383 //ResetEventBits(eBroadcastBitSTDOUT);
1384 }
1385 }
1386 return bytes_available;
1387}
1388
1389size_t
1390ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1391{
1392 // Can we get STDERR through the remote protocol?
1393 return 0;
1394}
1395
1396size_t
1397ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1398{
1399 if (m_stdio_communication.IsConnected())
1400 {
1401 ConnectionStatus status;
1402 m_stdio_communication.Write(src, src_len, status, NULL);
1403 }
1404 return 0;
1405}
1406
1407Error
1408ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1409{
1410 Error error;
1411 assert (bp_site != NULL);
1412
1413 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1414 user_id_t site_id = bp_site->GetID();
1415 const addr_t addr = bp_site->GetLoadAddress();
1416 if (log)
1417 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1418
1419 if (bp_site->IsEnabled())
1420 {
1421 if (log)
1422 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1423 return error;
1424 }
1425 else
1426 {
1427 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1428
1429 if (bp_site->HardwarePreferred())
1430 {
1431 // Try and set hardware breakpoint, and if that fails, fall through
1432 // and set a software breakpoint?
1433 }
1434
1435 if (m_z0_supported)
1436 {
1437 char packet[64];
1438 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1439 assert (packet_len + 1 < sizeof(packet));
1440 StringExtractorGDBRemote response;
1441 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1442 {
1443 if (response.IsUnsupportedPacket())
1444 {
1445 // Disable z packet support and try again
1446 m_z0_supported = 0;
1447 return EnableBreakpoint (bp_site);
1448 }
1449 else if (response.IsOKPacket())
1450 {
1451 bp_site->SetEnabled(true);
1452 bp_site->SetType (BreakpointSite::eExternal);
1453 return error;
1454 }
1455 else
1456 {
1457 uint8_t error_byte = response.GetError();
1458 if (error_byte)
1459 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1460 }
1461 }
1462 }
1463 else
1464 {
1465 return EnableSoftwareBreakpoint (bp_site);
1466 }
1467 }
1468
1469 if (log)
1470 {
1471 const char *err_string = error.AsCString();
1472 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1473 bp_site->GetLoadAddress(),
1474 err_string ? err_string : "NULL");
1475 }
1476 // We shouldn't reach here on a successful breakpoint enable...
1477 if (error.Success())
1478 error.SetErrorToGenericError();
1479 return error;
1480}
1481
1482Error
1483ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1484{
1485 Error error;
1486 assert (bp_site != NULL);
1487 addr_t addr = bp_site->GetLoadAddress();
1488 user_id_t site_id = bp_site->GetID();
1489 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS);
1490 if (log)
1491 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1492
1493 if (bp_site->IsEnabled())
1494 {
1495 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1496
1497 if (bp_site->IsHardware())
1498 {
1499 // TODO: disable hardware breakpoint...
1500 }
1501 else
1502 {
1503 if (m_z0_supported)
1504 {
1505 char packet[64];
1506 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1507 assert (packet_len + 1 < sizeof(packet));
1508 StringExtractorGDBRemote response;
1509 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1510 {
1511 if (response.IsUnsupportedPacket())
1512 {
1513 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1514 }
1515 else if (response.IsOKPacket())
1516 {
1517 if (log)
1518 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1519 bp_site->SetEnabled(false);
1520 return error;
1521 }
1522 else
1523 {
1524 uint8_t error_byte = response.GetError();
1525 if (error_byte)
1526 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1527 }
1528 }
1529 }
1530 else
1531 {
1532 return DisableSoftwareBreakpoint (bp_site);
1533 }
1534 }
1535 }
1536 else
1537 {
1538 if (log)
1539 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1540 return error;
1541 }
1542
1543 if (error.Success())
1544 error.SetErrorToGenericError();
1545 return error;
1546}
1547
1548Error
1549ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1550{
1551 Error error;
1552 if (wp)
1553 {
1554 user_id_t watchID = wp->GetID();
1555 addr_t addr = wp->GetLoadAddress();
1556 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1557 if (log)
1558 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1559 if (wp->IsEnabled())
1560 {
1561 if (log)
1562 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1563 return error;
1564 }
1565 else
1566 {
1567 // Pass down an appropriate z/Z packet...
1568 error.SetErrorString("watchpoints not supported");
1569 }
1570 }
1571 else
1572 {
1573 error.SetErrorString("Watchpoint location argument was NULL.");
1574 }
1575 if (error.Success())
1576 error.SetErrorToGenericError();
1577 return error;
1578}
1579
1580Error
1581ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1582{
1583 Error error;
1584 if (wp)
1585 {
1586 user_id_t watchID = wp->GetID();
1587
1588 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS);
1589
1590 addr_t addr = wp->GetLoadAddress();
1591 if (log)
1592 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1593
1594 if (wp->IsHardware())
1595 {
1596 // Pass down an appropriate z/Z packet...
1597 error.SetErrorString("watchpoints not supported");
1598 }
1599 // TODO: clear software watchpoints if we implement them
1600 }
1601 else
1602 {
1603 error.SetErrorString("Watchpoint location argument was NULL.");
1604 }
1605 if (error.Success())
1606 error.SetErrorToGenericError();
1607 return error;
1608}
1609
1610void
1611ProcessGDBRemote::Clear()
1612{
1613 m_flags = 0;
1614 m_thread_list.Clear();
1615 {
1616 Mutex::Locker locker(m_stdio_mutex);
1617 m_stdout_data.clear();
1618 }
1619 DestoryLibUnwindAddressSpace();
1620}
1621
1622Error
1623ProcessGDBRemote::DoSignal (int signo)
1624{
1625 Error error;
1626 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
1627 if (log)
1628 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1629
1630 if (!m_gdb_comm.SendAsyncSignal (signo))
1631 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1632 return error;
1633}
1634
Chris Lattner24943d22010-06-08 16:52:24 +00001635void
1636ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1637{
1638 ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1639 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1640}
1641
1642void
1643ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1644{
1645 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1646 Mutex::Locker locker(m_stdio_mutex);
1647 m_stdout_data.append(s, len);
1648
1649 // FIXME: Make a real data object for this and put it out.
1650 BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1651}
1652
1653
1654Error
1655ProcessGDBRemote::StartDebugserverProcess
1656(
1657 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1658 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1659 char const *inferior_envp[], // Environment to pass along to the inferior program
1660 char const *stdio_path,
1661 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID then attach to this attach_pid
1662 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1663 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Clayton452bf612010-08-31 18:35:14 +00001664 bool disable_aslr, // Disable ASLR
Chris Lattner24943d22010-06-08 16:52:24 +00001665 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1666)
1667{
1668 Error error;
1669 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1670 {
1671 // If we locate debugserver, keep that located version around
1672 static FileSpec g_debugserver_file_spec;
1673
1674 FileSpec debugserver_file_spec;
1675 char debugserver_path[PATH_MAX];
1676
1677 // Always check to see if we have an environment override for the path
1678 // to the debugserver to use and use it if we do.
1679 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1680 if (env_debugserver_path)
1681 debugserver_file_spec.SetFile (env_debugserver_path);
1682 else
1683 debugserver_file_spec = g_debugserver_file_spec;
1684 bool debugserver_exists = debugserver_file_spec.Exists();
1685 if (!debugserver_exists)
1686 {
1687 // The debugserver binary is in the LLDB.framework/Resources
1688 // directory.
1689 FileSpec framework_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)lldb_private::Initialize));
1690 const char *framework_dir = framework_file_spec.GetDirectory().AsCString();
1691 const char *lldb_framework = ::strstr (framework_dir, "/LLDB.framework");
1692
1693 if (lldb_framework)
1694 {
1695 int len = lldb_framework - framework_dir + strlen ("/LLDB.framework");
1696 ::snprintf (debugserver_path,
1697 sizeof(debugserver_path),
1698 "%.*s/Resources/%s",
1699 len,
1700 framework_dir,
1701 DEBUGSERVER_BASENAME);
1702 debugserver_file_spec.SetFile (debugserver_path);
1703 debugserver_exists = debugserver_file_spec.Exists();
1704 }
1705
1706 if (debugserver_exists)
1707 {
1708 g_debugserver_file_spec = debugserver_file_spec;
1709 }
1710 else
1711 {
1712 g_debugserver_file_spec.Clear();
1713 debugserver_file_spec.Clear();
1714 }
1715 }
1716
1717 if (debugserver_exists)
1718 {
1719 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1720
1721 m_stdio_communication.Clear();
1722 posix_spawnattr_t attr;
1723
1724 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
1725
1726 Error local_err; // Errors that don't affect the spawning.
1727 if (log)
1728 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1729 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1730 if (error.Fail() || log)
1731 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
1732 if (error.Fail())
1733 return error;;
1734
1735#if !defined (__arm__)
1736
1737 // We don't need to do this for ARM, and we really shouldn't now that we
1738 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1739 // to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001740 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001741 {
Greg Claytoncf015052010-06-11 03:25:34 +00001742 cpu_type_t cpu = inferior_arch.GetCPUType();
1743 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1744 {
1745 size_t ocount = 0;
1746 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1747 if (error.Fail() || log)
1748 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 +00001749
Greg Claytoncf015052010-06-11 03:25:34 +00001750 if (error.Fail() != 0 || ocount != 1)
1751 return error;
1752 }
Chris Lattner24943d22010-06-08 16:52:24 +00001753 }
1754
1755#endif
1756
1757 Args debugserver_args;
1758 char arg_cstr[PATH_MAX];
1759 bool launch_process = true;
1760
1761 if (inferior_argv == NULL && attach_pid != LLDB_INVALID_PROCESS_ID)
1762 launch_process = false;
1763 else if (attach_name)
1764 launch_process = false; // Wait for a process whose basename matches that in inferior_argv[0]
1765
1766 bool pass_stdio_path_to_debugserver = true;
1767 lldb_utility::PseudoTerminal pty;
1768 if (stdio_path == NULL)
1769 {
1770 pass_stdio_path_to_debugserver = false;
1771 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
1772 {
1773 struct termios stdin_termios;
1774 if (::tcgetattr (pty.GetMasterFileDescriptor(), &stdin_termios) == 0)
1775 {
1776 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing
1777 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time
1778 ::tcsetattr (pty.GetMasterFileDescriptor(), TCSANOW, &stdin_termios);
1779 }
1780 stdio_path = pty.GetSlaveName (NULL, 0);
1781 }
1782 }
1783
1784 // Start args with "debugserver /file/path -r --"
1785 debugserver_args.AppendArgument(debugserver_path);
1786 debugserver_args.AppendArgument(debugserver_url);
1787 debugserver_args.AppendArgument("--native-regs"); // use native registers, not the GDB registers
1788 debugserver_args.AppendArgument("--setsid"); // make debugserver run in its own session so
1789 // signals generated by special terminal key
1790 // sequences (^C) don't affect debugserver
1791
Greg Clayton452bf612010-08-31 18:35:14 +00001792 if (disable_aslr)
1793 debugserver_args.AppendArguments("--disable-aslr");
1794
Chris Lattner24943d22010-06-08 16:52:24 +00001795 // Only set the inferior
1796 if (launch_process)
1797 {
1798 if (stdio_path && pass_stdio_path_to_debugserver)
1799 {
1800 debugserver_args.AppendArgument("-s"); // short for --stdio-path
1801 StreamString strm;
1802 strm.Printf("'%s'", stdio_path);
1803 debugserver_args.AppendArgument(strm.GetData()); // path to file to have inferior open as it's STDIO
1804 }
1805 }
1806
1807 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1808 if (env_debugserver_log_file)
1809 {
1810 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1811 debugserver_args.AppendArgument(arg_cstr);
1812 }
1813
1814 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1815 if (env_debugserver_log_flags)
1816 {
1817 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1818 debugserver_args.AppendArgument(arg_cstr);
1819 }
1820// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1821// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1822
1823 // Now append the program arguments
1824 if (launch_process)
1825 {
1826 if (inferior_argv)
1827 {
1828 // Terminate the debugserver args so we can now append the inferior args
1829 debugserver_args.AppendArgument("--");
1830
1831 for (int i = 0; inferior_argv[i] != NULL; ++i)
1832 debugserver_args.AppendArgument (inferior_argv[i]);
1833 }
1834 else
1835 {
1836 // Will send environment entries with the 'QEnvironment:' packet
1837 // Will send arguments with the 'A' packet
1838 }
1839 }
1840 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1841 {
1842 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1843 debugserver_args.AppendArgument (arg_cstr);
1844 }
1845 else if (attach_name && attach_name[0])
1846 {
1847 if (wait_for_launch)
1848 debugserver_args.AppendArgument ("--waitfor");
1849 else
1850 debugserver_args.AppendArgument ("--attach");
1851 debugserver_args.AppendArgument (attach_name);
1852 }
1853
1854 Error file_actions_err;
1855 posix_spawn_file_actions_t file_actions;
1856#if DONT_CLOSE_DEBUGSERVER_STDIO
1857 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1858#else
1859 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1860 if (file_actions_err.Success())
1861 {
1862 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1863 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1864 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1865 }
1866#endif
1867
1868 if (log)
1869 {
1870 StreamString strm;
1871 debugserver_args.Dump (&strm);
1872 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1873 }
1874
1875 error.SetError(::posix_spawnp (&m_debugserver_pid,
1876 debugserver_path,
1877 file_actions_err.Success() ? &file_actions : NULL,
1878 &attr,
1879 debugserver_args.GetArgumentVector(),
1880 (char * const*)inferior_envp),
1881 eErrorTypePOSIX);
1882
Greg Claytone9d0df42010-07-02 01:29:13 +00001883
1884 ::posix_spawnattr_destroy (&attr);
1885
Chris Lattner24943d22010-06-08 16:52:24 +00001886 if (file_actions_err.Success())
1887 ::posix_spawn_file_actions_destroy (&file_actions);
1888
1889 // We have seen some cases where posix_spawnp was returning a valid
1890 // looking pid even when an error was returned, so clear it out
1891 if (error.Fail())
1892 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1893
1894 if (error.Fail() || log)
1895 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);
1896
1897// if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1898// {
1899// std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true));
1900// if (conn_ap.get())
1901// {
1902// m_stdio_communication.SetConnection(conn_ap.release());
1903// if (m_stdio_communication.IsConnected())
1904// {
1905// m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1906// m_stdio_communication.StartReadThread();
1907// }
1908// }
1909// }
1910 }
1911 else
1912 {
1913 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1914 }
1915
1916 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1917 StartAsyncThread ();
1918 }
1919 return error;
1920}
1921
1922bool
1923ProcessGDBRemote::MonitorDebugserverProcess
1924(
1925 void *callback_baton,
1926 lldb::pid_t debugserver_pid,
1927 int signo, // Zero for no signal
1928 int exit_status // Exit value of process if signal is zero
1929)
1930{
1931 // We pass in the ProcessGDBRemote inferior process it and name it
1932 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1933 // pointer value itself, thus we need the double cast...
1934
1935 // "debugserver_pid" argument passed in is the process ID for
1936 // debugserver that we are tracking...
1937
Greg Clayton75ccf502010-08-21 02:22:51 +00001938 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1939
1940 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001941 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001942 // Sleep for a half a second to make sure our inferior process has
1943 // time to set its exit status before we set it incorrectly when
1944 // both the debugserver and the inferior process shut down.
1945 usleep (500000);
1946 // If our process hasn't yet exited, debugserver might have died.
1947 // If the process did exit, the we are reaping it.
1948 if (process->GetState() != eStateExited)
Chris Lattner24943d22010-06-08 16:52:24 +00001949 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001950 char error_str[1024];
1951 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001952 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001953 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1954 if (signal_cstr)
1955 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001956 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001957 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001958 }
1959 else
1960 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001961 ::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 +00001962 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001963
1964 process->SetExitStatus (-1, error_str);
1965 }
1966 else
1967 {
1968 // Debugserver has exited we need to let our ProcessGDBRemote
1969 // know that it no longer has a debugserver instance
1970 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1971 // We are returning true to this function below, so we can
1972 // forget about the monitor handle.
1973 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001974 }
1975 }
1976 return true;
1977}
1978
1979void
1980ProcessGDBRemote::KillDebugserverProcess ()
1981{
1982 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1983 {
1984 ::kill (m_debugserver_pid, SIGINT);
1985 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1986 }
1987}
1988
1989void
1990ProcessGDBRemote::Initialize()
1991{
1992 static bool g_initialized = false;
1993
1994 if (g_initialized == false)
1995 {
1996 g_initialized = true;
1997 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1998 GetPluginDescriptionStatic(),
1999 CreateInstance);
2000
2001 Log::Callbacks log_callbacks = {
2002 ProcessGDBRemoteLog::DisableLog,
2003 ProcessGDBRemoteLog::EnableLog,
2004 ProcessGDBRemoteLog::ListLogCategories
2005 };
2006
2007 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2008 }
2009}
2010
2011bool
2012ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2013{
2014 if (m_curr_tid == tid)
2015 return true;
2016
2017 char packet[32];
2018 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2019 assert (packet_len + 1 < sizeof(packet));
2020 StringExtractorGDBRemote response;
2021 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2022 {
2023 if (response.IsOKPacket())
2024 {
2025 m_curr_tid = tid;
2026 return true;
2027 }
2028 }
2029 return false;
2030}
2031
2032bool
2033ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2034{
2035 if (m_curr_tid_run == tid)
2036 return true;
2037
2038 char packet[32];
2039 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2040 assert (packet_len + 1 < sizeof(packet));
2041 StringExtractorGDBRemote response;
2042 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2043 {
2044 if (response.IsOKPacket())
2045 {
2046 m_curr_tid_run = tid;
2047 return true;
2048 }
2049 }
2050 return false;
2051}
2052
2053void
2054ProcessGDBRemote::ResetGDBRemoteState ()
2055{
2056 // Reset and GDB remote state
2057 m_curr_tid = LLDB_INVALID_THREAD_ID;
2058 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2059 m_z0_supported = 1;
2060}
2061
2062
2063bool
2064ProcessGDBRemote::StartAsyncThread ()
2065{
2066 ResetGDBRemoteState ();
2067
2068 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2069
2070 if (log)
2071 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2072
2073 // Create a thread that watches our internal state and controls which
2074 // events make it to clients (into the DCProcess event queue).
2075 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2076 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2077}
2078
2079void
2080ProcessGDBRemote::StopAsyncThread ()
2081{
2082 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
2083
2084 if (log)
2085 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2086
2087 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2088
2089 // Stop the stdio thread
2090 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2091 {
2092 Host::ThreadJoin (m_async_thread, NULL, NULL);
2093 }
2094}
2095
2096
2097void *
2098ProcessGDBRemote::AsyncThread (void *arg)
2099{
2100 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2101
2102 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
2103 if (log)
2104 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2105
2106 Listener listener ("ProcessGDBRemote::AsyncThread");
2107 EventSP event_sp;
2108 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2109 eBroadcastBitAsyncThreadShouldExit;
2110
2111 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2112 {
2113 bool done = false;
2114 while (!done)
2115 {
2116 if (log)
2117 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2118 if (listener.WaitForEvent (NULL, event_sp))
2119 {
2120 const uint32_t event_type = event_sp->GetType();
2121 switch (event_type)
2122 {
2123 case eBroadcastBitAsyncContinue:
2124 {
2125 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2126
2127 if (continue_packet)
2128 {
2129 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2130 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2131 if (log)
2132 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2133
2134 process->SetPrivateState(eStateRunning);
2135 StringExtractorGDBRemote response;
2136 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2137
2138 switch (stop_state)
2139 {
2140 case eStateStopped:
2141 case eStateCrashed:
2142 case eStateSuspended:
2143 process->m_last_stop_packet = response;
2144 process->m_last_stop_packet.SetFilePos (0);
2145 process->SetPrivateState (stop_state);
2146 break;
2147
2148 case eStateExited:
2149 process->m_last_stop_packet = response;
2150 process->m_last_stop_packet.SetFilePos (0);
2151 response.SetFilePos(1);
2152 process->SetExitStatus(response.GetHexU8(), NULL);
2153 done = true;
2154 break;
2155
2156 case eStateInvalid:
2157 break;
2158
2159 default:
2160 process->SetPrivateState (stop_state);
2161 break;
2162 }
2163 }
2164 }
2165 break;
2166
2167 case eBroadcastBitAsyncThreadShouldExit:
2168 if (log)
2169 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2170 done = true;
2171 break;
2172
2173 default:
2174 if (log)
2175 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2176 done = true;
2177 break;
2178 }
2179 }
2180 else
2181 {
2182 if (log)
2183 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2184 done = true;
2185 }
2186 }
2187 }
2188
2189 if (log)
2190 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2191
2192 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2193 return NULL;
2194}
2195
2196lldb_private::unw_addr_space_t
2197ProcessGDBRemote::GetLibUnwindAddressSpace ()
2198{
2199 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED;
Greg Claytoncf015052010-06-11 03:25:34 +00002200
2201 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType();
2202 if (arch_cpu == ArchSpec::eCPU_i386)
Chris Lattner24943d22010-06-08 16:52:24 +00002203 target_type = UNW_TARGET_I386;
Greg Claytoncf015052010-06-11 03:25:34 +00002204 else if (arch_cpu == ArchSpec::eCPU_x86_64)
Chris Lattner24943d22010-06-08 16:52:24 +00002205 target_type = UNW_TARGET_X86_64;
2206
2207 if (m_libunwind_addr_space)
2208 {
2209 if (m_libunwind_target_type != target_type)
2210 DestoryLibUnwindAddressSpace();
2211 else
2212 return m_libunwind_addr_space;
2213 }
2214 unw_accessors_t callbacks = get_macosx_libunwind_callbacks ();
2215 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type);
2216 if (m_libunwind_addr_space)
2217 m_libunwind_target_type = target_type;
2218 else
2219 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2220 return m_libunwind_addr_space;
2221}
2222
2223void
2224ProcessGDBRemote::DestoryLibUnwindAddressSpace ()
2225{
2226 if (m_libunwind_addr_space)
2227 {
2228 unw_destroy_addr_space (m_libunwind_addr_space);
2229 m_libunwind_addr_space = NULL;
2230 }
2231 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED;
2232}
2233
2234
2235const char *
2236ProcessGDBRemote::GetDispatchQueueNameForThread
2237(
2238 addr_t thread_dispatch_qaddr,
2239 std::string &dispatch_queue_name
2240)
2241{
2242 dispatch_queue_name.clear();
2243 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2244 {
2245 // Cache the dispatch_queue_offsets_addr value so we don't always have
2246 // to look it up
2247 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2248 {
2249 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib")));
2250 if (module_sp.get() == NULL)
2251 return NULL;
2252
2253 const Symbol *dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (ConstString("dispatch_queue_offsets"), eSymbolTypeData);
2254 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002255 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002256
2257 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2258 return NULL;
2259 }
2260
2261 uint8_t memory_buffer[8];
2262 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2263
2264 // Excerpt from src/queue_private.h
2265 struct dispatch_queue_offsets_s
2266 {
2267 uint16_t dqo_version;
2268 uint16_t dqo_label;
2269 uint16_t dqo_label_size;
2270 } dispatch_queue_offsets;
2271
2272
2273 Error error;
2274 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2275 {
2276 uint32_t data_offset = 0;
2277 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2278 {
2279 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2280 {
2281 data_offset = 0;
2282 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2283 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2284 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2285 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2286 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2287 dispatch_queue_name.erase (bytes_read);
2288 }
2289 }
2290 }
2291 }
2292 if (dispatch_queue_name.empty())
2293 return NULL;
2294 return dispatch_queue_name.c_str();
2295}
2296
Jim Ingham7508e732010-08-09 23:31:02 +00002297uint32_t
2298ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2299{
2300 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2301 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2302 if (m_local_debugserver)
2303 {
2304 return Host::ListProcessesMatchingName (name, matches, pids);
2305 }
2306 else
2307 {
2308 // FIXME: Implement talking to the remote debugserver.
2309 return 0;
2310 }
2311
2312}