blob: f0087ec420077da59d3fb0d90180abc43bc19cce [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"
Greg Clayton643ee732010-08-04 01:40:35 +000048#include "StopInfoMachException.h"
49
Chris Lattner24943d22010-06-08 16:52:24 +000050
Chris Lattner24943d22010-06-08 16:52:24 +000051
52#define DEBUGSERVER_BASENAME "debugserver"
53using namespace lldb;
54using namespace lldb_private;
55
56static inline uint16_t
57get_random_port ()
58{
59 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u;
60}
61
62
63const char *
64ProcessGDBRemote::GetPluginNameStatic()
65{
66 return "process.gdb-remote";
67}
68
69const char *
70ProcessGDBRemote::GetPluginDescriptionStatic()
71{
72 return "GDB Remote protocol based debugging plug-in.";
73}
74
75void
76ProcessGDBRemote::Terminate()
77{
78 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
79}
80
81
82Process*
83ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
84{
85 return new ProcessGDBRemote (target, listener);
86}
87
88bool
89ProcessGDBRemote::CanDebug(Target &target)
90{
91 // For now we are just making sure the file exists for a given module
92 ModuleSP exe_module_sp(target.GetExecutableModule());
93 if (exe_module_sp.get())
94 return exe_module_sp->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +000095 // However, if there is no executable module, we return true since we might be preparing to attach.
96 return true;
Chris Lattner24943d22010-06-08 16:52:24 +000097}
98
99//----------------------------------------------------------------------
100// ProcessGDBRemote constructor
101//----------------------------------------------------------------------
102ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
103 Process (target, listener),
104 m_dynamic_loader_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000105 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000106 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000107 m_gdb_comm(),
108 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000109 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000110 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000111 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000112 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
113 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000114 m_curr_tid (LLDB_INVALID_THREAD_ID),
115 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000116 m_z0_supported (1),
117 m_continue_packet(),
118 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000119 m_packet_timeout (1),
120 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000121 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000122 m_local_debugserver (true),
123 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000124{
125}
126
127//----------------------------------------------------------------------
128// Destructor
129//----------------------------------------------------------------------
130ProcessGDBRemote::~ProcessGDBRemote()
131{
Greg Claytonff5cac22010-12-13 18:11:18 +0000132 m_dynamic_loader_ap.reset();
133
Greg Clayton75ccf502010-08-21 02:22:51 +0000134 if (m_debugserver_thread != LLDB_INVALID_HOST_THREAD)
135 {
136 Host::ThreadCancel (m_debugserver_thread, NULL);
137 thread_result_t thread_result;
138 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
139 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
140 }
Chris Lattner24943d22010-06-08 16:52:24 +0000141 // m_mach_process.UnregisterNotificationCallbacks (this);
142 Clear();
143}
144
145//----------------------------------------------------------------------
146// PluginInterface
147//----------------------------------------------------------------------
148const char *
149ProcessGDBRemote::GetPluginName()
150{
151 return "Process debugging plug-in that uses the GDB remote protocol";
152}
153
154const char *
155ProcessGDBRemote::GetShortPluginName()
156{
157 return GetPluginNameStatic();
158}
159
160uint32_t
161ProcessGDBRemote::GetPluginVersion()
162{
163 return 1;
164}
165
166void
167ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
168{
169 strm->Printf("TODO: fill this in\n");
170}
171
172Error
173ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
174{
175 Error error;
176 error.SetErrorString("No plug-in commands are currently supported.");
177 return error;
178}
179
180Log *
181ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
182{
183 return NULL;
184}
185
186void
187ProcessGDBRemote::BuildDynamicRegisterInfo ()
188{
189 char register_info_command[64];
190 m_register_info.Clear();
191 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
192 uint32_t reg_offset = 0;
193 uint32_t reg_num = 0;
194 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
195 {
196 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num);
197 StringExtractorGDBRemote response;
198 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false))
199 {
200 packet_type = response.GetType();
201 if (packet_type == StringExtractorGDBRemote::eResponse)
202 {
203 std::string name;
204 std::string value;
205 ConstString reg_name;
206 ConstString alt_name;
207 ConstString set_name;
208 RegisterInfo reg_info = { NULL, // Name
209 NULL, // Alt name
210 0, // byte size
211 reg_offset, // offset
212 eEncodingUint, // encoding
213 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000214 {
215 LLDB_INVALID_REGNUM, // GCC reg num
216 LLDB_INVALID_REGNUM, // DWARF reg num
217 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000218 reg_num, // GDB reg num
219 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000220 }
221 };
222
223 while (response.GetNameColonValue(name, value))
224 {
225 if (name.compare("name") == 0)
226 {
227 reg_name.SetCString(value.c_str());
228 }
229 else if (name.compare("alt-name") == 0)
230 {
231 alt_name.SetCString(value.c_str());
232 }
233 else if (name.compare("bitsize") == 0)
234 {
235 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
236 }
237 else if (name.compare("offset") == 0)
238 {
239 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000240 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000241 {
242 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000243 }
244 }
245 else if (name.compare("encoding") == 0)
246 {
247 if (value.compare("uint") == 0)
248 reg_info.encoding = eEncodingUint;
249 else if (value.compare("sint") == 0)
250 reg_info.encoding = eEncodingSint;
251 else if (value.compare("ieee754") == 0)
252 reg_info.encoding = eEncodingIEEE754;
253 else if (value.compare("vector") == 0)
254 reg_info.encoding = eEncodingVector;
255 }
256 else if (name.compare("format") == 0)
257 {
258 if (value.compare("binary") == 0)
259 reg_info.format = eFormatBinary;
260 else if (value.compare("decimal") == 0)
261 reg_info.format = eFormatDecimal;
262 else if (value.compare("hex") == 0)
263 reg_info.format = eFormatHex;
264 else if (value.compare("float") == 0)
265 reg_info.format = eFormatFloat;
266 else if (value.compare("vector-sint8") == 0)
267 reg_info.format = eFormatVectorOfSInt8;
268 else if (value.compare("vector-uint8") == 0)
269 reg_info.format = eFormatVectorOfUInt8;
270 else if (value.compare("vector-sint16") == 0)
271 reg_info.format = eFormatVectorOfSInt16;
272 else if (value.compare("vector-uint16") == 0)
273 reg_info.format = eFormatVectorOfUInt16;
274 else if (value.compare("vector-sint32") == 0)
275 reg_info.format = eFormatVectorOfSInt32;
276 else if (value.compare("vector-uint32") == 0)
277 reg_info.format = eFormatVectorOfUInt32;
278 else if (value.compare("vector-float32") == 0)
279 reg_info.format = eFormatVectorOfFloat32;
280 else if (value.compare("vector-uint128") == 0)
281 reg_info.format = eFormatVectorOfUInt128;
282 }
283 else if (name.compare("set") == 0)
284 {
285 set_name.SetCString(value.c_str());
286 }
287 else if (name.compare("gcc") == 0)
288 {
289 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
290 }
291 else if (name.compare("dwarf") == 0)
292 {
293 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
294 }
295 else if (name.compare("generic") == 0)
296 {
297 if (value.compare("pc") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
299 else if (value.compare("sp") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
301 else if (value.compare("fp") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
303 else if (value.compare("ra") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
305 else if (value.compare("flags") == 0)
306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
307 }
308 }
309
Jason Molenda53d96862010-06-11 23:44:18 +0000310 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000311 assert (reg_info.byte_size != 0);
312 reg_offset += reg_info.byte_size;
313 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
314 }
315 }
316 else
317 {
318 packet_type = StringExtractorGDBRemote::eError;
319 }
320 }
321
322 if (reg_num == 0)
323 {
324 // We didn't get anything. See if we are debugging ARM and fill with
325 // a hard coded register set until we can get an updated debugserver
326 // down on the devices.
327 ArchSpec arm_arch ("arm");
328 if (GetTarget().GetArchitecture() == arm_arch)
329 m_register_info.HardcodeARMRegisters();
330 }
331 m_register_info.Finalize ();
332}
333
334Error
335ProcessGDBRemote::WillLaunch (Module* module)
336{
337 return WillLaunchOrAttach ();
338}
339
340Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000341ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000342{
343 return WillLaunchOrAttach ();
344}
345
346Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000347ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000348{
349 return WillLaunchOrAttach ();
350}
351
352Error
353ProcessGDBRemote::WillLaunchOrAttach ()
354{
355 Error error;
356 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
357 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
358
359 if (m_dynamic_loader_ap.get() == NULL)
360 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
361 m_stdio_communication.Clear ();
362
363 return error;
364}
365
366//----------------------------------------------------------------------
367// Process Control
368//----------------------------------------------------------------------
369Error
370ProcessGDBRemote::DoLaunch
371(
372 Module* module,
373 char const *argv[],
374 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000375 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000376 const char *stdin_path,
377 const char *stdout_path,
378 const char *stderr_path
379)
380{
Greg Clayton4b407112010-09-30 21:49:03 +0000381 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000382 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
383 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
384 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000385
386 ObjectFile * object_file = module->GetObjectFile();
387 if (object_file)
388 {
389 ArchSpec inferior_arch(module->GetArchitecture());
390 char host_port[128];
391 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
392
Greg Clayton23cf0c72010-11-08 04:29:11 +0000393 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000394 bool start_debugserver_with_inferior_args = false;
395 if (start_debugserver_with_inferior_args)
396 {
397 // We want to launch debugserver with the inferior program and its
398 // arguments on the command line. We should only do this if we
399 // the GDB server we are talking to doesn't support the 'A' packet.
400 error = StartDebugserverProcess (host_port,
401 argv,
402 envp,
403 NULL, //stdin_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000404 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000405 LLDB_INVALID_PROCESS_ID,
406 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000407 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000408 inferior_arch);
409 if (error.Fail())
410 return error;
411
412 error = ConnectToDebugserver (host_port);
413 if (error.Success())
414 {
415 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
416 }
417 }
418 else
419 {
420 error = StartDebugserverProcess (host_port,
421 NULL,
422 NULL,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000423 NULL, //stdin_path
424 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000425 LLDB_INVALID_PROCESS_ID,
426 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000427 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000428 inferior_arch);
429 if (error.Fail())
430 return error;
431
432 error = ConnectToDebugserver (host_port);
433 if (error.Success())
434 {
435 // Send the environment and the program + arguments after we connect
436 if (envp)
437 {
438 const char *env_entry;
439 for (int i=0; (env_entry = envp[i]); ++i)
440 {
441 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
442 break;
443 }
444 }
445
Greg Clayton960d6a42010-08-03 00:35:52 +0000446 // FIXME: convert this to use the new set/show variables when they are available
447#if 0
448 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
449 {
450 const uint32_t attach_debugserver_secs = 10;
451 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
452 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
453 {
454 printf ("%i\n", attach_debugserver_secs - i);
455 sleep (1);
456 }
457 }
458#endif
459
Chris Lattner24943d22010-06-08 16:52:24 +0000460 const uint32_t arg_timeout_seconds = 10;
461 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
462 if (arg_packet_err == 0)
463 {
464 std::string error_str;
465 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
466 {
467 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
468 }
469 else
470 {
471 error.SetErrorString (error_str.c_str());
472 }
473 }
474 else
475 {
476 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
477 }
478
479 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
480 }
481 }
482
483 if (GetID() == LLDB_INVALID_PROCESS_ID)
484 {
485 KillDebugserverProcess ();
486 return error;
487 }
488
489 StringExtractorGDBRemote response;
490 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
491 SetPrivateState (SetThreadStopInfo (response));
492
493 }
494 else
495 {
496 // Set our user ID to an invalid process ID.
497 SetID(LLDB_INVALID_PROCESS_ID);
498 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
499 }
Chris Lattner24943d22010-06-08 16:52:24 +0000500 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000501
Chris Lattner24943d22010-06-08 16:52:24 +0000502}
503
504
505Error
506ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
507{
508 Error error;
509 // Sleep and wait a bit for debugserver to start to listen...
510 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
511 if (conn_ap.get())
512 {
513 std::string connect_url("connect://");
514 connect_url.append (host_port);
515 const uint32_t max_retry_count = 50;
516 uint32_t retry_count = 0;
517 while (!m_gdb_comm.IsConnected())
518 {
519 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
520 {
521 m_gdb_comm.SetConnection (conn_ap.release());
522 break;
523 }
524 retry_count++;
525
526 if (retry_count >= max_retry_count)
527 break;
528
529 usleep (100000);
530 }
531 }
532
533 if (!m_gdb_comm.IsConnected())
534 {
535 if (error.Success())
536 error.SetErrorString("not connected to remote gdb server");
537 return error;
538 }
539
540 m_gdb_comm.SetAckMode (true);
541 if (m_gdb_comm.StartReadThread(&error))
542 {
543 // Send an initial ack
544 m_gdb_comm.SendAck('+');
545
546 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000547 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
548 this,
549 m_debugserver_pid,
550 false);
551
Chris Lattner24943d22010-06-08 16:52:24 +0000552 StringExtractorGDBRemote response;
553 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
554 {
555 if (response.IsOKPacket())
556 m_gdb_comm.SetAckMode (false);
557 }
Greg Claytonc71899e2011-01-18 19:36:39 +0000558
559 if (m_gdb_comm.SendPacketAndWaitForResponse("QThreadSuffixSupported", response, 1, false))
560 {
561 if (response.IsOKPacket())
562 m_gdb_comm.SetThreadSuffixSupported (true);
563 }
564
Chris Lattner24943d22010-06-08 16:52:24 +0000565 }
566 return error;
567}
568
569void
570ProcessGDBRemote::DidLaunchOrAttach ()
571{
572 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
573 if (GetID() == LLDB_INVALID_PROCESS_ID)
574 {
575 m_dynamic_loader_ap.reset();
576 }
577 else
578 {
579 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
580
Greg Clayton20d338f2010-11-18 05:57:03 +0000581 BuildDynamicRegisterInfo ();
582
583 m_byte_order = m_gdb_comm.GetByteOrder();
584
Chris Lattner24943d22010-06-08 16:52:24 +0000585 StreamString strm;
586
587 ArchSpec inferior_arch;
588 // See if the GDB server supports the qHostInfo information
589 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
590 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Clayton20d338f2010-11-18 05:57:03 +0000591 ArchSpec arch_spec (GetTarget().GetArchitecture());
Chris Lattner24943d22010-06-08 16:52:24 +0000592
Jim Ingham7508e732010-08-09 23:31:02 +0000593 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000594 {
595 // For ARM we can't trust the arch of the process as it could
596 // have an armv6 object file, but be running on armv7 kernel.
597 inferior_arch = m_gdb_comm.GetHostArchitecture();
598 }
599
600 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000601 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000602
603 if (vendor == NULL)
604 vendor = Host::GetVendorString().AsCString("apple");
605
606 if (os_type == NULL)
607 os_type = Host::GetOSString().AsCString("darwin");
608
609 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
610
611 std::transform (strm.GetString().begin(),
612 strm.GetString().end(),
613 strm.GetString().begin(),
614 ::tolower);
615
616 m_target_triple.SetCString(strm.GetString().c_str());
617 }
618}
619
620void
621ProcessGDBRemote::DidLaunch ()
622{
623 DidLaunchOrAttach ();
624 if (m_dynamic_loader_ap.get())
625 m_dynamic_loader_ap->DidLaunch();
626}
627
628Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000629ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000630{
631 Error error;
632 // Clear out and clean up from any current state
633 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000634 ArchSpec arch_spec = GetTarget().GetArchitecture();
635
Greg Claytone005f2c2010-11-06 01:53:30 +0000636 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000637
638
Chris Lattner24943d22010-06-08 16:52:24 +0000639 if (attach_pid != LLDB_INVALID_PROCESS_ID)
640 {
Chris Lattner24943d22010-06-08 16:52:24 +0000641 char host_port[128];
642 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000643 error = StartDebugserverProcess (host_port, // debugserver_url
644 NULL, // inferior_argv
645 NULL, // inferior_envp
646 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000647 false, // launch_process == false (we are attaching)
648 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
649 NULL, // Don't send any attach by process name option to debugserver
650 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000651 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000652 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000653
654 if (error.Fail())
655 {
656 const char *error_string = error.AsCString();
657 if (error_string == NULL)
658 error_string = "unable to launch " DEBUGSERVER_BASENAME;
659
660 SetExitStatus (-1, error_string);
661 }
662 else
663 {
664 error = ConnectToDebugserver (host_port);
665 if (error.Success())
666 {
667 char packet[64];
668 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
669 StringExtractorGDBRemote response;
670 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
671 packet,
672 packet_len,
673 response);
674 switch (stop_state)
675 {
676 case eStateStopped:
677 case eStateCrashed:
678 case eStateSuspended:
679 SetID (attach_pid);
680 m_last_stop_packet = response;
681 m_last_stop_packet.SetFilePos (0);
682 SetPrivateState (stop_state);
683 break;
684
685 case eStateExited:
686 m_last_stop_packet = response;
687 m_last_stop_packet.SetFilePos (0);
688 response.SetFilePos(1);
689 SetExitStatus(response.GetHexU8(), NULL);
690 break;
691
692 default:
693 SetExitStatus(-1, "unable to attach to process");
694 break;
695 }
696
697 }
698 }
699 }
700
701 lldb::pid_t pid = GetID();
702 if (pid == LLDB_INVALID_PROCESS_ID)
703 {
704 KillDebugserverProcess();
705 }
706 return error;
707}
708
709size_t
710ProcessGDBRemote::AttachInputReaderCallback
711(
712 void *baton,
713 InputReader *reader,
714 lldb::InputReaderAction notification,
715 const char *bytes,
716 size_t bytes_len
717)
718{
719 if (notification == eInputReaderGotToken)
720 {
721 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
722 if (gdb_process->m_waiting_for_attach)
723 gdb_process->m_waiting_for_attach = false;
724 reader->SetIsDone(true);
725 return 1;
726 }
727 return 0;
728}
729
730Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000731ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000732{
733 Error error;
734 // Clear out and clean up from any current state
735 Clear();
736 // HACK: require arch be set correctly at the target level until we can
737 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000738
Greg Claytone005f2c2010-11-06 01:53:30 +0000739 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000740 if (process_name && process_name[0])
741 {
Chris Lattner24943d22010-06-08 16:52:24 +0000742 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000743 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000744 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000745 error = StartDebugserverProcess (host_port, // debugserver_url
746 NULL, // inferior_argv
747 NULL, // inferior_envp
748 NULL, // stdin_path
Greg Clayton23cf0c72010-11-08 04:29:11 +0000749 false, // launch_process == false (we are attaching)
750 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
751 NULL, // Don't send any attach by process name option to debugserver
752 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000753 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000754 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000755 if (error.Fail())
756 {
757 const char *error_string = error.AsCString();
758 if (error_string == NULL)
759 error_string = "unable to launch " DEBUGSERVER_BASENAME;
760
761 SetExitStatus (-1, error_string);
762 }
763 else
764 {
765 error = ConnectToDebugserver (host_port);
766 if (error.Success())
767 {
768 StreamString packet;
769
Chris Lattner24943d22010-06-08 16:52:24 +0000770 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000771 packet.PutCString("vAttachWait");
772 else
773 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000774 packet.PutChar(';');
775 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
776 StringExtractorGDBRemote response;
777 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
778 packet.GetData(),
779 packet.GetSize(),
780 response);
781 switch (stop_state)
782 {
783 case eStateStopped:
784 case eStateCrashed:
785 case eStateSuspended:
786 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
787 m_last_stop_packet = response;
788 m_last_stop_packet.SetFilePos (0);
789 SetPrivateState (stop_state);
790 break;
791
792 case eStateExited:
793 m_last_stop_packet = response;
794 m_last_stop_packet.SetFilePos (0);
795 response.SetFilePos(1);
796 SetExitStatus(response.GetHexU8(), NULL);
797 break;
798
799 default:
800 SetExitStatus(-1, "unable to attach to process");
801 break;
802 }
803 }
804 }
805 }
806
807 lldb::pid_t pid = GetID();
808 if (pid == LLDB_INVALID_PROCESS_ID)
809 {
810 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000811
812 if (error.Success())
813 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000814 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000815
Chris Lattner24943d22010-06-08 16:52:24 +0000816 return error;
817}
818
819//
820// if (wait_for_launch)
821// {
822// InputReaderSP reader_sp (new InputReader());
823// StreamString instructions;
824// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
825// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
826// this, // baton
827// eInputReaderGranularityByte,
828// NULL, // End token
829// false);
830//
831// StringExtractorGDBRemote response;
832// m_waiting_for_attach = true;
833// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
834// while (m_waiting_for_attach)
835// {
836// // Wait for one second for the stop reply packet
837// if (m_gdb_comm.WaitForPacket(response, 1))
838// {
839// // Got some sort of packet, see if it is the stop reply packet?
840// char ch = response.GetChar(0);
841// if (ch == 'T')
842// {
843// m_waiting_for_attach = false;
844// }
845// }
846// else
847// {
848// // Put a period character every second
849// fputc('.', reader_out_fh);
850// }
851// }
852// }
853// }
854// return GetID();
855//}
856
857void
858ProcessGDBRemote::DidAttach ()
859{
Chris Lattner24943d22010-06-08 16:52:24 +0000860 if (m_dynamic_loader_ap.get())
861 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000862 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000863}
864
865Error
866ProcessGDBRemote::WillResume ()
867{
868 m_continue_packet.Clear();
869 // Start the continue packet we will use to run the target. Each thread
870 // will append what it is supposed to be doing to this packet when the
871 // ThreadList::WillResume() is called. If a thread it supposed
872 // to stay stopped, then don't append anything to this string.
873 m_continue_packet.Printf("vCont");
874 return Error();
875}
876
877Error
878ProcessGDBRemote::DoResume ()
879{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000880 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000881 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000882
883 Listener listener ("gdb-remote.resume-packet-sent");
884 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
885 {
886 EventSP event_sp;
887 TimeValue timeout;
888 timeout = TimeValue::Now();
889 timeout.OffsetWithSeconds (5);
890 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
891
892 if (listener.WaitForEvent (&timeout, event_sp) == false)
893 error.SetErrorString("Resume timed out.");
894 }
895
Jim Ingham3ae449a2010-11-17 02:32:00 +0000896 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000897}
898
899size_t
900ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
901{
902 const uint8_t *trap_opcode = NULL;
903 uint32_t trap_opcode_size = 0;
904
905 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
906 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
907 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
908 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
909
Jim Ingham7508e732010-08-09 23:31:02 +0000910 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000911 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000912 {
Greg Claytoncf015052010-06-11 03:25:34 +0000913 case ArchSpec::eCPU_i386:
914 case ArchSpec::eCPU_x86_64:
915 trap_opcode = g_i386_breakpoint_opcode;
916 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
917 break;
918
919 case ArchSpec::eCPU_arm:
920 // TODO: fill this in for ARM. We need to dig up the symbol for
921 // the address in the breakpoint locaiton and figure out if it is
922 // an ARM or Thumb breakpoint.
923 trap_opcode = g_arm_breakpoint_opcode;
924 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
925 break;
926
927 case ArchSpec::eCPU_ppc:
928 case ArchSpec::eCPU_ppc64:
929 trap_opcode = g_ppc_breakpoint_opcode;
930 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
931 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000932
Greg Claytoncf015052010-06-11 03:25:34 +0000933 default:
934 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
935 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000936 }
937
938 if (trap_opcode && trap_opcode_size)
939 {
940 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
941 return trap_opcode_size;
942 }
943 return 0;
944}
945
946uint32_t
947ProcessGDBRemote::UpdateThreadListIfNeeded ()
948{
949 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000950 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000951 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000952 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
953
Greg Clayton5205f0b2010-09-03 17:10:42 +0000954 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000955 const uint32_t stop_id = GetStopID();
956 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
957 {
958 // Update the thread list's stop id immediately so we don't recurse into this function.
959 ThreadList curr_thread_list (this);
960 curr_thread_list.SetStopID(stop_id);
961
962 Error err;
963 StringExtractorGDBRemote response;
964 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
965 response.IsNormalPacket();
966 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
967 {
968 char ch = response.GetChar();
969 if (ch == 'l')
970 break;
971 if (ch == 'm')
972 {
973 do
974 {
975 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
976
977 if (tid != LLDB_INVALID_THREAD_ID)
978 {
979 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +0000980 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000981 thread_sp.reset (new ThreadGDBRemote (*this, tid));
982 curr_thread_list.AddThread(thread_sp);
983 }
984
985 ch = response.GetChar();
986 } while (ch == ',');
987 }
988 }
989
990 m_thread_list = curr_thread_list;
991
992 SetThreadStopInfo (m_last_stop_packet);
993 }
994 return GetThreadList().GetSize(false);
995}
996
997
998StateType
999ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1000{
1001 const char stop_type = stop_packet.GetChar();
1002 switch (stop_type)
1003 {
1004 case 'T':
1005 case 'S':
1006 {
1007 // Stop with signal and thread info
1008 const uint8_t signo = stop_packet.GetHexU8();
1009 std::string name;
1010 std::string value;
1011 std::string thread_name;
1012 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001013 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001014 uint32_t tid = LLDB_INVALID_THREAD_ID;
1015 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1016 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001017 ThreadSP thread_sp;
1018
Chris Lattner24943d22010-06-08 16:52:24 +00001019 while (stop_packet.GetNameColonValue(name, value))
1020 {
1021 if (name.compare("metype") == 0)
1022 {
1023 // exception type in big endian hex
1024 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1025 }
1026 else if (name.compare("mecount") == 0)
1027 {
1028 // exception count in big endian hex
1029 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1030 }
1031 else if (name.compare("medata") == 0)
1032 {
1033 // exception data in big endian hex
1034 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1035 }
1036 else if (name.compare("thread") == 0)
1037 {
1038 // thread in big endian hex
1039 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytona875b642011-01-09 21:07:35 +00001040 thread_sp = m_thread_list.FindThreadByID(tid, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001041 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001042 else if (name.compare("hexname") == 0)
1043 {
1044 StringExtractor name_extractor;
1045 // Swap "value" over into "name_extractor"
1046 name_extractor.GetStringRef().swap(value);
1047 // Now convert the HEX bytes into a string value
1048 name_extractor.GetHexByteString (value);
1049 thread_name.swap (value);
1050 }
Chris Lattner24943d22010-06-08 16:52:24 +00001051 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 }
Greg Claytona875b642011-01-09 21:07:35 +00001059 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1060 {
1061 // We have a register number that contains an expedited
1062 // register value. Lets supply this register to our thread
1063 // so it won't have to go and read it.
1064 if (thread_sp)
1065 {
1066 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1067
1068 if (reg != UINT32_MAX)
1069 {
1070 StringExtractor reg_value_extractor;
1071 // Swap "value" over into "reg_value_extractor"
1072 reg_value_extractor.GetStringRef().swap(value);
1073 static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor);
1074 }
1075 }
1076 }
Chris Lattner24943d22010-06-08 16:52:24 +00001077 }
Chris Lattner24943d22010-06-08 16:52:24 +00001078
1079 if (thread_sp)
1080 {
1081 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1082
1083 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1084 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00001085 if (exc_type != 0)
1086 {
Greg Clayton643ee732010-08-04 01:40:35 +00001087 const size_t exc_data_count = exc_data.size();
1088
1089 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1090 exc_type,
1091 exc_data_count,
1092 exc_data_count >= 1 ? exc_data[0] : 0,
1093 exc_data_count >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001094 }
1095 else if (signo)
1096 {
Greg Clayton643ee732010-08-04 01:40:35 +00001097 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001098 }
1099 else
1100 {
Greg Clayton643ee732010-08-04 01:40:35 +00001101 StopInfoSP invalid_stop_info_sp;
1102 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001103 }
1104 }
1105 return eStateStopped;
1106 }
1107 break;
1108
1109 case 'W':
1110 // process exited
1111 return eStateExited;
1112
1113 default:
1114 break;
1115 }
1116 return eStateInvalid;
1117}
1118
1119void
1120ProcessGDBRemote::RefreshStateAfterStop ()
1121{
Jim Ingham7508e732010-08-09 23:31:02 +00001122 // FIXME - add a variable to tell that we're in the middle of attaching if we
1123 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001124 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001125// if (!GetTarget().GetArchitecture().IsValid())
1126// {
1127// Module *exe_module = GetTarget().GetExecutableModule().get();
1128// if (exe_module)
1129// m_arch_spec = exe_module->GetArchitecture();
1130// }
1131
Chris Lattner24943d22010-06-08 16:52:24 +00001132 // Let all threads recover from stopping and do any clean up based
1133 // on the previous thread state (if any).
1134 m_thread_list.RefreshStateAfterStop();
1135
1136 // Discover new threads:
1137 UpdateThreadListIfNeeded ();
1138}
1139
1140Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001141ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001142{
1143 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001144
Chris Lattner24943d22010-06-08 16:52:24 +00001145 if (m_gdb_comm.IsRunning())
1146 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001147 caused_stop = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001148 bool timed_out = false;
Greg Clayton1a679462010-09-03 19:15:43 +00001149 Mutex::Locker locker;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001150
Greg Clayton20d338f2010-11-18 05:57:03 +00001151 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
Chris Lattner24943d22010-06-08 16:52:24 +00001152 {
1153 if (timed_out)
1154 error.SetErrorString("timed out sending interrupt packet");
1155 else
1156 error.SetErrorString("unknown error sending interrupt packet");
1157 }
1158 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001159 else
1160 {
1161 caused_stop = false;
1162 }
1163
Chris Lattner24943d22010-06-08 16:52:24 +00001164 return error;
1165}
1166
1167Error
1168ProcessGDBRemote::WillDetach ()
1169{
1170 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001171
Greg Clayton4fb400f2010-09-27 21:07:38 +00001172 if (m_gdb_comm.IsRunning())
1173 {
1174 bool timed_out = false;
1175 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001176 PausePrivateStateThread();
1177 m_thread_list.DiscardThreadPlans();
1178 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001179 if (!m_gdb_comm.SendInterrupt (locker, 2, &timed_out))
1180 {
1181 if (timed_out)
1182 error.SetErrorString("timed out sending interrupt packet");
1183 else
1184 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001185 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001186 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001187 TimeValue timeout_time;
1188 timeout_time = TimeValue::Now();
1189 timeout_time.OffsetWithSeconds(2);
1190
1191 EventSP event_sp;
1192 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1193 if (state != eStateStopped)
1194 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001195 }
Chris Lattner24943d22010-06-08 16:52:24 +00001196 return error;
1197}
1198
Greg Clayton4fb400f2010-09-27 21:07:38 +00001199Error
1200ProcessGDBRemote::DoDetach()
1201{
1202 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001203 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001204 if (log)
1205 log->Printf ("ProcessGDBRemote::DoDetach()");
1206
1207 DisableAllBreakpointSites ();
1208
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001209 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001210
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001211 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1212 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001213 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001214 if (response_size)
1215 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1216 else
1217 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001218 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001219 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001220 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001221
Greg Clayton4fb400f2010-09-27 21:07:38 +00001222 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001223 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001224
1225 SetPrivateState (eStateDetached);
1226 ResumePrivateStateThread();
1227
1228 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001229 return error;
1230}
Chris Lattner24943d22010-06-08 16:52:24 +00001231
1232Error
1233ProcessGDBRemote::DoDestroy ()
1234{
1235 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001236 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001237 if (log)
1238 log->Printf ("ProcessGDBRemote::DoDestroy()");
1239
1240 // Interrupt if our inferior is running...
Greg Clayton1a679462010-09-03 19:15:43 +00001241 Mutex::Locker locker;
1242 m_gdb_comm.SendInterrupt (locker, 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001243 DisableAllBreakpointSites ();
1244 SetExitStatus(-1, "process killed");
1245
1246 StringExtractorGDBRemote response;
Greg Claytonb749a262010-12-03 06:02:24 +00001247 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 1, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001248 {
Caroline Tice926060e2010-10-29 21:48:37 +00001249 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001250 if (log)
1251 {
1252 if (response.IsOKPacket())
1253 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful");
1254 else
1255 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str());
1256 }
1257 }
1258
1259 StopAsyncThread ();
1260 m_gdb_comm.StopReadThread();
1261 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001262 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001263 return error;
1264}
1265
Chris Lattner24943d22010-06-08 16:52:24 +00001266//------------------------------------------------------------------
1267// Process Queries
1268//------------------------------------------------------------------
1269
1270bool
1271ProcessGDBRemote::IsAlive ()
1272{
Greg Clayton58e844b2010-12-08 05:08:21 +00001273 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001274}
1275
1276addr_t
1277ProcessGDBRemote::GetImageInfoAddress()
1278{
1279 if (!m_gdb_comm.IsRunning())
1280 {
1281 StringExtractorGDBRemote response;
1282 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1283 {
1284 if (response.IsNormalPacket())
1285 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1286 }
1287 }
1288 return LLDB_INVALID_ADDRESS;
1289}
1290
1291DynamicLoader *
1292ProcessGDBRemote::GetDynamicLoader()
1293{
1294 return m_dynamic_loader_ap.get();
1295}
1296
1297//------------------------------------------------------------------
1298// Process Memory
1299//------------------------------------------------------------------
1300size_t
1301ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1302{
1303 if (size > m_max_memory_size)
1304 {
1305 // Keep memory read sizes down to a sane limit. This function will be
1306 // called multiple times in order to complete the task by
1307 // lldb_private::Process so it is ok to do this.
1308 size = m_max_memory_size;
1309 }
1310
1311 char packet[64];
1312 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1313 assert (packet_len + 1 < sizeof(packet));
1314 StringExtractorGDBRemote response;
1315 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1316 {
1317 if (response.IsNormalPacket())
1318 {
1319 error.Clear();
1320 return response.GetHexBytes(buf, size, '\xdd');
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);
1326 else
1327 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1328 }
1329 else
1330 {
1331 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1332 }
1333 return 0;
1334}
1335
1336size_t
1337ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1338{
1339 StreamString packet;
1340 packet.Printf("M%llx,%zx:", addr, size);
1341 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1342 StringExtractorGDBRemote response;
1343 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1344 {
1345 if (response.IsOKPacket())
1346 {
1347 error.Clear();
1348 return size;
1349 }
1350 else if (response.IsErrorPacket())
1351 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1352 else if (response.IsUnsupportedPacket())
1353 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1354 else
1355 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1356 }
1357 else
1358 {
1359 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1360 }
1361 return 0;
1362}
1363
1364lldb::addr_t
1365ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1366{
1367 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1368 if (allocated_addr == LLDB_INVALID_ADDRESS)
1369 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1370 else
1371 error.Clear();
1372 return allocated_addr;
1373}
1374
1375Error
1376ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1377{
1378 Error error;
1379 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1380 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1381 return error;
1382}
1383
1384
1385//------------------------------------------------------------------
1386// Process STDIO
1387//------------------------------------------------------------------
1388
1389size_t
1390ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1391{
1392 Mutex::Locker locker(m_stdio_mutex);
1393 size_t bytes_available = m_stdout_data.size();
1394 if (bytes_available > 0)
1395 {
1396 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1397 if (bytes_available > buf_size)
1398 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001399 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001400 m_stdout_data.erase(0, buf_size);
1401 bytes_available = buf_size;
1402 }
1403 else
1404 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001405 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001406 m_stdout_data.clear();
1407
1408 //ResetEventBits(eBroadcastBitSTDOUT);
1409 }
1410 }
1411 return bytes_available;
1412}
1413
1414size_t
1415ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1416{
1417 // Can we get STDERR through the remote protocol?
1418 return 0;
1419}
1420
1421size_t
1422ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1423{
1424 if (m_stdio_communication.IsConnected())
1425 {
1426 ConnectionStatus status;
1427 m_stdio_communication.Write(src, src_len, status, NULL);
1428 }
1429 return 0;
1430}
1431
1432Error
1433ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1434{
1435 Error error;
1436 assert (bp_site != NULL);
1437
Greg Claytone005f2c2010-11-06 01:53:30 +00001438 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001439 user_id_t site_id = bp_site->GetID();
1440 const addr_t addr = bp_site->GetLoadAddress();
1441 if (log)
1442 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1443
1444 if (bp_site->IsEnabled())
1445 {
1446 if (log)
1447 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1448 return error;
1449 }
1450 else
1451 {
1452 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1453
1454 if (bp_site->HardwarePreferred())
1455 {
1456 // Try and set hardware breakpoint, and if that fails, fall through
1457 // and set a software breakpoint?
1458 }
1459
1460 if (m_z0_supported)
1461 {
1462 char packet[64];
1463 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1464 assert (packet_len + 1 < sizeof(packet));
1465 StringExtractorGDBRemote response;
1466 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1467 {
1468 if (response.IsUnsupportedPacket())
1469 {
1470 // Disable z packet support and try again
1471 m_z0_supported = 0;
1472 return EnableBreakpoint (bp_site);
1473 }
1474 else if (response.IsOKPacket())
1475 {
1476 bp_site->SetEnabled(true);
1477 bp_site->SetType (BreakpointSite::eExternal);
1478 return error;
1479 }
1480 else
1481 {
1482 uint8_t error_byte = response.GetError();
1483 if (error_byte)
1484 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1485 }
1486 }
1487 }
1488 else
1489 {
1490 return EnableSoftwareBreakpoint (bp_site);
1491 }
1492 }
1493
1494 if (log)
1495 {
1496 const char *err_string = error.AsCString();
1497 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1498 bp_site->GetLoadAddress(),
1499 err_string ? err_string : "NULL");
1500 }
1501 // We shouldn't reach here on a successful breakpoint enable...
1502 if (error.Success())
1503 error.SetErrorToGenericError();
1504 return error;
1505}
1506
1507Error
1508ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1509{
1510 Error error;
1511 assert (bp_site != NULL);
1512 addr_t addr = bp_site->GetLoadAddress();
1513 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001514 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001515 if (log)
1516 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1517
1518 if (bp_site->IsEnabled())
1519 {
1520 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1521
1522 if (bp_site->IsHardware())
1523 {
1524 // TODO: disable hardware breakpoint...
1525 }
1526 else
1527 {
1528 if (m_z0_supported)
1529 {
1530 char packet[64];
1531 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1532 assert (packet_len + 1 < sizeof(packet));
1533 StringExtractorGDBRemote response;
1534 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1535 {
1536 if (response.IsUnsupportedPacket())
1537 {
1538 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1539 }
1540 else if (response.IsOKPacket())
1541 {
1542 if (log)
1543 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1544 bp_site->SetEnabled(false);
1545 return error;
1546 }
1547 else
1548 {
1549 uint8_t error_byte = response.GetError();
1550 if (error_byte)
1551 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1552 }
1553 }
1554 }
1555 else
1556 {
1557 return DisableSoftwareBreakpoint (bp_site);
1558 }
1559 }
1560 }
1561 else
1562 {
1563 if (log)
1564 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1565 return error;
1566 }
1567
1568 if (error.Success())
1569 error.SetErrorToGenericError();
1570 return error;
1571}
1572
1573Error
1574ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1575{
1576 Error error;
1577 if (wp)
1578 {
1579 user_id_t watchID = wp->GetID();
1580 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001581 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001582 if (log)
1583 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1584 if (wp->IsEnabled())
1585 {
1586 if (log)
1587 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1588 return error;
1589 }
1590 else
1591 {
1592 // Pass down an appropriate z/Z packet...
1593 error.SetErrorString("watchpoints not supported");
1594 }
1595 }
1596 else
1597 {
1598 error.SetErrorString("Watchpoint location argument was NULL.");
1599 }
1600 if (error.Success())
1601 error.SetErrorToGenericError();
1602 return error;
1603}
1604
1605Error
1606ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1607{
1608 Error error;
1609 if (wp)
1610 {
1611 user_id_t watchID = wp->GetID();
1612
Greg Claytone005f2c2010-11-06 01:53:30 +00001613 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001614
1615 addr_t addr = wp->GetLoadAddress();
1616 if (log)
1617 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1618
1619 if (wp->IsHardware())
1620 {
1621 // Pass down an appropriate z/Z packet...
1622 error.SetErrorString("watchpoints not supported");
1623 }
1624 // TODO: clear software watchpoints if we implement them
1625 }
1626 else
1627 {
1628 error.SetErrorString("Watchpoint location argument was NULL.");
1629 }
1630 if (error.Success())
1631 error.SetErrorToGenericError();
1632 return error;
1633}
1634
1635void
1636ProcessGDBRemote::Clear()
1637{
1638 m_flags = 0;
1639 m_thread_list.Clear();
1640 {
1641 Mutex::Locker locker(m_stdio_mutex);
1642 m_stdout_data.clear();
1643 }
Chris Lattner24943d22010-06-08 16:52:24 +00001644}
1645
1646Error
1647ProcessGDBRemote::DoSignal (int signo)
1648{
1649 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001650 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001651 if (log)
1652 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1653
1654 if (!m_gdb_comm.SendAsyncSignal (signo))
1655 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1656 return error;
1657}
1658
Caroline Tice861efb32010-11-16 05:07:41 +00001659//void
1660//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1661//{
1662// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1663// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1664//}
Chris Lattner24943d22010-06-08 16:52:24 +00001665
Caroline Tice861efb32010-11-16 05:07:41 +00001666//void
1667//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1668//{
1669// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1670// Mutex::Locker locker(m_stdio_mutex);
1671// m_stdout_data.append(s, len);
1672//
1673// // FIXME: Make a real data object for this and put it out.
1674// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1675//}
Chris Lattner24943d22010-06-08 16:52:24 +00001676
1677
1678Error
1679ProcessGDBRemote::StartDebugserverProcess
1680(
1681 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1682 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1683 char const *inferior_envp[], // Environment to pass along to the inferior program
1684 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001685 bool launch_process, // Set to true if we are going to be launching a the process
1686 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID send this pid as an argument to debugserver
Chris Lattner24943d22010-06-08 16:52:24 +00001687 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1688 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001689 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001690 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1691)
1692{
1693 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001694 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1695 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001696 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1697 {
1698 // If we locate debugserver, keep that located version around
1699 static FileSpec g_debugserver_file_spec;
1700
1701 FileSpec debugserver_file_spec;
1702 char debugserver_path[PATH_MAX];
1703
1704 // Always check to see if we have an environment override for the path
1705 // to the debugserver to use and use it if we do.
1706 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1707 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001708 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001709 else
1710 debugserver_file_spec = g_debugserver_file_spec;
1711 bool debugserver_exists = debugserver_file_spec.Exists();
1712 if (!debugserver_exists)
1713 {
1714 // The debugserver binary is in the LLDB.framework/Resources
1715 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001716 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001717 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001718 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001719 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001720 if (debugserver_exists)
1721 {
1722 g_debugserver_file_spec = debugserver_file_spec;
1723 }
1724 else
1725 {
1726 g_debugserver_file_spec.Clear();
1727 debugserver_file_spec.Clear();
1728 }
Chris Lattner24943d22010-06-08 16:52:24 +00001729 }
1730 }
1731
1732 if (debugserver_exists)
1733 {
1734 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1735
1736 m_stdio_communication.Clear();
1737 posix_spawnattr_t attr;
1738
Greg Claytone005f2c2010-11-06 01:53:30 +00001739 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001740
1741 Error local_err; // Errors that don't affect the spawning.
1742 if (log)
1743 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1744 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1745 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001746 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001747 if (error.Fail())
1748 return error;;
1749
1750#if !defined (__arm__)
1751
Greg Clayton24b48ff2010-10-17 22:03:32 +00001752 // We don't need to do this for ARM, and we really shouldn't now
1753 // that we have multiple CPU subtypes and no posix_spawnattr call
1754 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001755 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001756 {
Greg Claytoncf015052010-06-11 03:25:34 +00001757 cpu_type_t cpu = inferior_arch.GetCPUType();
1758 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1759 {
1760 size_t ocount = 0;
1761 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1762 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001763 error.PutToLog(log.get(), "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount);
Chris Lattner24943d22010-06-08 16:52:24 +00001764
Greg Claytoncf015052010-06-11 03:25:34 +00001765 if (error.Fail() != 0 || ocount != 1)
1766 return error;
1767 }
Chris Lattner24943d22010-06-08 16:52:24 +00001768 }
1769
1770#endif
1771
1772 Args debugserver_args;
1773 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001774
Chris Lattner24943d22010-06-08 16:52:24 +00001775 lldb_utility::PseudoTerminal pty;
Caroline Ticebd666012010-12-03 18:46:09 +00001776 if (launch_process && stdio_path == NULL && m_local_debugserver && !no_stdio)
Chris Lattner24943d22010-06-08 16:52:24 +00001777 {
Chris Lattner24943d22010-06-08 16:52:24 +00001778 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001779 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001780 }
1781
1782 // Start args with "debugserver /file/path -r --"
1783 debugserver_args.AppendArgument(debugserver_path);
1784 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001785 // use native registers, not the GDB registers
1786 debugserver_args.AppendArgument("--native-regs");
1787 // make debugserver run in its own session so signals generated by
1788 // special terminal key sequences (^C) don't affect debugserver
1789 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001790
Greg Clayton452bf612010-08-31 18:35:14 +00001791 if (disable_aslr)
1792 debugserver_args.AppendArguments("--disable-aslr");
1793
Chris Lattner24943d22010-06-08 16:52:24 +00001794 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001795 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001796 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001797 debugserver_args.AppendArgument("--stdio-path");
1798 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001799 }
Caroline Ticebd666012010-12-03 18:46:09 +00001800 else if (launch_process && no_stdio)
1801 {
1802 debugserver_args.AppendArgument("--no-stdio");
1803 }
Chris Lattner24943d22010-06-08 16:52:24 +00001804
1805 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1806 if (env_debugserver_log_file)
1807 {
1808 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1809 debugserver_args.AppendArgument(arg_cstr);
1810 }
1811
1812 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1813 if (env_debugserver_log_flags)
1814 {
1815 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1816 debugserver_args.AppendArgument(arg_cstr);
1817 }
1818// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1819// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1820
1821 // Now append the program arguments
1822 if (launch_process)
1823 {
1824 if (inferior_argv)
1825 {
1826 // Terminate the debugserver args so we can now append the inferior args
1827 debugserver_args.AppendArgument("--");
1828
1829 for (int i = 0; inferior_argv[i] != NULL; ++i)
1830 debugserver_args.AppendArgument (inferior_argv[i]);
1831 }
1832 else
1833 {
1834 // Will send environment entries with the 'QEnvironment:' packet
1835 // Will send arguments with the 'A' packet
1836 }
1837 }
1838 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1839 {
1840 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1841 debugserver_args.AppendArgument (arg_cstr);
1842 }
1843 else if (attach_name && attach_name[0])
1844 {
1845 if (wait_for_launch)
1846 debugserver_args.AppendArgument ("--waitfor");
1847 else
1848 debugserver_args.AppendArgument ("--attach");
1849 debugserver_args.AppendArgument (attach_name);
1850 }
1851
1852 Error file_actions_err;
1853 posix_spawn_file_actions_t file_actions;
1854#if DONT_CLOSE_DEBUGSERVER_STDIO
1855 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1856#else
1857 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1858 if (file_actions_err.Success())
1859 {
1860 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1861 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1862 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1863 }
1864#endif
1865
1866 if (log)
1867 {
1868 StreamString strm;
1869 debugserver_args.Dump (&strm);
1870 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1871 }
1872
1873 error.SetError(::posix_spawnp (&m_debugserver_pid,
1874 debugserver_path,
1875 file_actions_err.Success() ? &file_actions : NULL,
1876 &attr,
1877 debugserver_args.GetArgumentVector(),
1878 (char * const*)inferior_envp),
1879 eErrorTypePOSIX);
1880
Greg Claytone9d0df42010-07-02 01:29:13 +00001881
1882 ::posix_spawnattr_destroy (&attr);
1883
Chris Lattner24943d22010-06-08 16:52:24 +00001884 if (file_actions_err.Success())
1885 ::posix_spawn_file_actions_destroy (&file_actions);
1886
1887 // We have seen some cases where posix_spawnp was returning a valid
1888 // looking pid even when an error was returned, so clear it out
1889 if (error.Fail())
1890 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1891
1892 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001893 error.PutToLog(log.get(), "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", m_debugserver_pid, debugserver_path, NULL, &attr, inferior_argv, inferior_envp);
Chris Lattner24943d22010-06-08 16:52:24 +00001894
Caroline Ticebd666012010-12-03 18:46:09 +00001895 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00001896 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001897 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001898 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001899 }
Chris Lattner24943d22010-06-08 16:52:24 +00001900 }
1901 else
1902 {
1903 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1904 }
1905
1906 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1907 StartAsyncThread ();
1908 }
1909 return error;
1910}
1911
1912bool
1913ProcessGDBRemote::MonitorDebugserverProcess
1914(
1915 void *callback_baton,
1916 lldb::pid_t debugserver_pid,
1917 int signo, // Zero for no signal
1918 int exit_status // Exit value of process if signal is zero
1919)
1920{
1921 // We pass in the ProcessGDBRemote inferior process it and name it
1922 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1923 // pointer value itself, thus we need the double cast...
1924
1925 // "debugserver_pid" argument passed in is the process ID for
1926 // debugserver that we are tracking...
1927
Greg Clayton75ccf502010-08-21 02:22:51 +00001928 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1929
1930 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001931 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001932 // Sleep for a half a second to make sure our inferior process has
1933 // time to set its exit status before we set it incorrectly when
1934 // both the debugserver and the inferior process shut down.
1935 usleep (500000);
1936 // If our process hasn't yet exited, debugserver might have died.
1937 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001938 const StateType state = process->GetState();
1939
1940 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1941 state != eStateInvalid &&
1942 state != eStateUnloaded &&
1943 state != eStateExited &&
1944 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001945 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001946 char error_str[1024];
1947 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001948 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001949 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1950 if (signal_cstr)
1951 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001952 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001953 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001954 }
1955 else
1956 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001957 ::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 +00001958 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001959
1960 process->SetExitStatus (-1, error_str);
1961 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001962 // Debugserver has exited we need to let our ProcessGDBRemote
1963 // know that it no longer has a debugserver instance
1964 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1965 // We are returning true to this function below, so we can
1966 // forget about the monitor handle.
1967 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001968 }
1969 return true;
1970}
1971
1972void
1973ProcessGDBRemote::KillDebugserverProcess ()
1974{
1975 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1976 {
1977 ::kill (m_debugserver_pid, SIGINT);
1978 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1979 }
1980}
1981
1982void
1983ProcessGDBRemote::Initialize()
1984{
1985 static bool g_initialized = false;
1986
1987 if (g_initialized == false)
1988 {
1989 g_initialized = true;
1990 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1991 GetPluginDescriptionStatic(),
1992 CreateInstance);
1993
1994 Log::Callbacks log_callbacks = {
1995 ProcessGDBRemoteLog::DisableLog,
1996 ProcessGDBRemoteLog::EnableLog,
1997 ProcessGDBRemoteLog::ListLogCategories
1998 };
1999
2000 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2001 }
2002}
2003
2004bool
2005ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2006{
2007 if (m_curr_tid == tid)
2008 return true;
2009
2010 char packet[32];
2011 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2012 assert (packet_len + 1 < sizeof(packet));
2013 StringExtractorGDBRemote response;
2014 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2015 {
2016 if (response.IsOKPacket())
2017 {
2018 m_curr_tid = tid;
2019 return true;
2020 }
2021 }
2022 return false;
2023}
2024
2025bool
2026ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2027{
2028 if (m_curr_tid_run == tid)
2029 return true;
2030
2031 char packet[32];
Greg Claytonc71899e2011-01-18 19:36:39 +00002032 const int packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002033 assert (packet_len + 1 < sizeof(packet));
2034 StringExtractorGDBRemote response;
2035 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2036 {
2037 if (response.IsOKPacket())
2038 {
2039 m_curr_tid_run = tid;
2040 return true;
2041 }
2042 }
2043 return false;
2044}
2045
2046void
2047ProcessGDBRemote::ResetGDBRemoteState ()
2048{
2049 // Reset and GDB remote state
2050 m_curr_tid = LLDB_INVALID_THREAD_ID;
2051 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2052 m_z0_supported = 1;
2053}
2054
2055
2056bool
2057ProcessGDBRemote::StartAsyncThread ()
2058{
2059 ResetGDBRemoteState ();
2060
Greg Claytone005f2c2010-11-06 01:53:30 +00002061 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002062
2063 if (log)
2064 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2065
2066 // Create a thread that watches our internal state and controls which
2067 // events make it to clients (into the DCProcess event queue).
2068 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2069 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2070}
2071
2072void
2073ProcessGDBRemote::StopAsyncThread ()
2074{
Greg Claytone005f2c2010-11-06 01:53:30 +00002075 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002076
2077 if (log)
2078 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2079
2080 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2081
2082 // Stop the stdio thread
2083 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2084 {
2085 Host::ThreadJoin (m_async_thread, NULL, NULL);
2086 }
2087}
2088
2089
2090void *
2091ProcessGDBRemote::AsyncThread (void *arg)
2092{
2093 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2094
Greg Claytone005f2c2010-11-06 01:53:30 +00002095 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002096 if (log)
2097 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2098
2099 Listener listener ("ProcessGDBRemote::AsyncThread");
2100 EventSP event_sp;
2101 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2102 eBroadcastBitAsyncThreadShouldExit;
2103
2104 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2105 {
2106 bool done = false;
2107 while (!done)
2108 {
Caroline Tice926060e2010-10-29 21:48:37 +00002109 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002110 if (log)
2111 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2112 if (listener.WaitForEvent (NULL, event_sp))
2113 {
2114 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002115 if (log)
2116 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2117
Chris Lattner24943d22010-06-08 16:52:24 +00002118 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 ();
Caroline Tice926060e2010-10-29 21:48:37 +00002128 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002129 if (log)
2130 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2131
2132 process->SetPrivateState(eStateRunning);
2133 StringExtractorGDBRemote response;
2134 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2135
2136 switch (stop_state)
2137 {
2138 case eStateStopped:
2139 case eStateCrashed:
2140 case eStateSuspended:
2141 process->m_last_stop_packet = response;
2142 process->m_last_stop_packet.SetFilePos (0);
2143 process->SetPrivateState (stop_state);
2144 break;
2145
2146 case eStateExited:
2147 process->m_last_stop_packet = response;
2148 process->m_last_stop_packet.SetFilePos (0);
2149 response.SetFilePos(1);
2150 process->SetExitStatus(response.GetHexU8(), NULL);
2151 done = true;
2152 break;
2153
2154 case eStateInvalid:
2155 break;
2156
2157 default:
2158 process->SetPrivateState (stop_state);
2159 break;
2160 }
2161 }
2162 }
2163 break;
2164
2165 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002166 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002167 if (log)
2168 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2169 done = true;
2170 break;
2171
2172 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002173 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002174 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 {
Caroline Tice926060e2010-10-29 21:48:37 +00002182 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002183 if (log)
2184 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2185 done = true;
2186 }
2187 }
2188 }
2189
Caroline Tice926060e2010-10-29 21:48:37 +00002190 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002191 if (log)
2192 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2193
2194 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2195 return NULL;
2196}
2197
Chris Lattner24943d22010-06-08 16:52:24 +00002198const char *
2199ProcessGDBRemote::GetDispatchQueueNameForThread
2200(
2201 addr_t thread_dispatch_qaddr,
2202 std::string &dispatch_queue_name
2203)
2204{
2205 dispatch_queue_name.clear();
2206 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2207 {
2208 // Cache the dispatch_queue_offsets_addr value so we don't always have
2209 // to look it up
2210 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2211 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002212 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2213 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002214 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002215 if (module_sp)
2216 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2217
2218 if (dispatch_queue_offsets_symbol == NULL)
2219 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002220 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002221 if (module_sp)
2222 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2223 }
Chris Lattner24943d22010-06-08 16:52:24 +00002224 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002225 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002226
2227 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2228 return NULL;
2229 }
2230
2231 uint8_t memory_buffer[8];
2232 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2233
2234 // Excerpt from src/queue_private.h
2235 struct dispatch_queue_offsets_s
2236 {
2237 uint16_t dqo_version;
2238 uint16_t dqo_label;
2239 uint16_t dqo_label_size;
2240 } dispatch_queue_offsets;
2241
2242
2243 Error error;
2244 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2245 {
2246 uint32_t data_offset = 0;
2247 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2248 {
2249 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2250 {
2251 data_offset = 0;
2252 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2253 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2254 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2255 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2256 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2257 dispatch_queue_name.erase (bytes_read);
2258 }
2259 }
2260 }
2261 }
2262 if (dispatch_queue_name.empty())
2263 return NULL;
2264 return dispatch_queue_name.c_str();
2265}
2266
Jim Ingham7508e732010-08-09 23:31:02 +00002267uint32_t
2268ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2269{
2270 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2271 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2272 if (m_local_debugserver)
2273 {
2274 return Host::ListProcessesMatchingName (name, matches, pids);
2275 }
2276 else
2277 {
2278 // FIXME: Implement talking to the remote debugserver.
2279 return 0;
2280 }
2281
2282}
Jim Ingham55e01d82011-01-22 01:33:44 +00002283
2284bool
2285ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2286 lldb_private::StoppointCallbackContext *context,
2287 lldb::user_id_t break_id,
2288 lldb::user_id_t break_loc_id)
2289{
2290 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2291 // run so I can stop it if that's what I want to do.
2292 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2293 if (log)
2294 log->Printf("Hit New Thread Notification breakpoint.");
2295 return false;
2296}
2297
2298
2299bool
2300ProcessGDBRemote::StartNoticingNewThreads()
2301{
2302 static const char *bp_names[] =
2303 {
2304 "start_wqthread",
2305 "_pthread_start",
2306 NULL
2307 };
2308
2309 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2310 size_t num_bps = m_thread_observation_bps.size();
2311 if (num_bps != 0)
2312 {
2313 for (int i = 0; i < num_bps; i++)
2314 {
2315 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2316 if (break_sp)
2317 {
2318 if (log)
2319 log->Printf("Enabled noticing new thread breakpoint.");
2320 break_sp->SetEnabled(true);
2321 }
2322 }
2323 }
2324 else
2325 {
2326 for (int i = 0; bp_names[i] != NULL; i++)
2327 {
2328 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2329 if (breakpoint)
2330 {
2331 if (log)
2332 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2333 m_thread_observation_bps.push_back(breakpoint->GetID());
2334 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2335 }
2336 else
2337 {
2338 if (log)
2339 log->Printf("Failed to create new thread notification breakpoint.");
2340 return false;
2341 }
2342 }
2343 }
2344
2345 return true;
2346}
2347
2348bool
2349ProcessGDBRemote::StopNoticingNewThreads()
2350{
2351 size_t num_bps = m_thread_observation_bps.size();
2352 if (num_bps != 0)
2353 {
2354 for (int i = 0; i < num_bps; i++)
2355 {
2356 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2357
2358 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2359 if (break_sp)
2360 {
2361 if (log)
2362 log->Printf ("Disabling new thread notification breakpoint.");
2363 break_sp->SetEnabled(false);
2364 }
2365 }
2366 }
2367 return true;
2368}
2369
2370