blob: 5abe070f9622d23e287887441860cf713e8c6ad0 [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
Greg Claytona4881d02011-01-22 07:12:45 +0000544 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000545
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
Greg Claytona4881d02011-01-22 07:12:45 +00001145 bool timed_out = false;
1146 Mutex::Locker locker;
1147
1148 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
Greg Clayton20d338f2010-11-18 05:57:03 +00001149 {
Greg Claytona4881d02011-01-22 07:12:45 +00001150 if (timed_out)
1151 error.SetErrorString("timed out sending interrupt packet");
1152 else
1153 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton20d338f2010-11-18 05:57:03 +00001154 }
1155
Chris Lattner24943d22010-06-08 16:52:24 +00001156 return error;
1157}
1158
1159Error
1160ProcessGDBRemote::WillDetach ()
1161{
1162 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001163
Greg Clayton4fb400f2010-09-27 21:07:38 +00001164 if (m_gdb_comm.IsRunning())
1165 {
1166 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001167 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001168 Mutex::Locker locker;
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001169 PausePrivateStateThread();
1170 m_thread_list.DiscardThreadPlans();
1171 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Claytona4881d02011-01-22 07:12:45 +00001172 if (!m_gdb_comm.SendInterrupt (locker, 2, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001173 {
1174 if (timed_out)
1175 error.SetErrorString("timed out sending interrupt packet");
1176 else
1177 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001178 ResumePrivateStateThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001179 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001180 TimeValue timeout_time;
1181 timeout_time = TimeValue::Now();
1182 timeout_time.OffsetWithSeconds(2);
1183
1184 EventSP event_sp;
1185 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1186 if (state != eStateStopped)
1187 error.SetErrorString("unable to stop target");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001188 }
Chris Lattner24943d22010-06-08 16:52:24 +00001189 return error;
1190}
1191
Greg Clayton4fb400f2010-09-27 21:07:38 +00001192Error
1193ProcessGDBRemote::DoDetach()
1194{
1195 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001196 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001197 if (log)
1198 log->Printf ("ProcessGDBRemote::DoDetach()");
1199
1200 DisableAllBreakpointSites ();
1201
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001202 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001203
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001204 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1205 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001206 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001207 if (response_size)
1208 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1209 else
1210 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001211 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001212 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001213 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001214
Greg Clayton4fb400f2010-09-27 21:07:38 +00001215 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001216 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001217
1218 SetPrivateState (eStateDetached);
1219 ResumePrivateStateThread();
1220
1221 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001222 return error;
1223}
Chris Lattner24943d22010-06-08 16:52:24 +00001224
1225Error
1226ProcessGDBRemote::DoDestroy ()
1227{
1228 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001229 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001230 if (log)
1231 log->Printf ("ProcessGDBRemote::DoDestroy()");
1232
1233 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001234 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001235 {
Greg Claytona4881d02011-01-22 07:12:45 +00001236 // Don't get a response when killing our
1237 m_gdb_comm.SendPacket ("k", 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001238 }
1239
1240 StopAsyncThread ();
1241 m_gdb_comm.StopReadThread();
1242 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001243 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001244 return error;
1245}
1246
Chris Lattner24943d22010-06-08 16:52:24 +00001247//------------------------------------------------------------------
1248// Process Queries
1249//------------------------------------------------------------------
1250
1251bool
1252ProcessGDBRemote::IsAlive ()
1253{
Greg Clayton58e844b2010-12-08 05:08:21 +00001254 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001255}
1256
1257addr_t
1258ProcessGDBRemote::GetImageInfoAddress()
1259{
1260 if (!m_gdb_comm.IsRunning())
1261 {
1262 StringExtractorGDBRemote response;
1263 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1264 {
1265 if (response.IsNormalPacket())
1266 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1267 }
1268 }
1269 return LLDB_INVALID_ADDRESS;
1270}
1271
1272DynamicLoader *
1273ProcessGDBRemote::GetDynamicLoader()
1274{
1275 return m_dynamic_loader_ap.get();
1276}
1277
1278//------------------------------------------------------------------
1279// Process Memory
1280//------------------------------------------------------------------
1281size_t
1282ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1283{
1284 if (size > m_max_memory_size)
1285 {
1286 // Keep memory read sizes down to a sane limit. This function will be
1287 // called multiple times in order to complete the task by
1288 // lldb_private::Process so it is ok to do this.
1289 size = m_max_memory_size;
1290 }
1291
1292 char packet[64];
1293 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1294 assert (packet_len + 1 < sizeof(packet));
1295 StringExtractorGDBRemote response;
1296 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1297 {
1298 if (response.IsNormalPacket())
1299 {
1300 error.Clear();
1301 return response.GetHexBytes(buf, size, '\xdd');
1302 }
1303 else if (response.IsErrorPacket())
1304 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1305 else if (response.IsUnsupportedPacket())
1306 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1307 else
1308 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1309 }
1310 else
1311 {
1312 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1313 }
1314 return 0;
1315}
1316
1317size_t
1318ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1319{
1320 StreamString packet;
1321 packet.Printf("M%llx,%zx:", addr, size);
1322 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1323 StringExtractorGDBRemote response;
1324 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1325 {
1326 if (response.IsOKPacket())
1327 {
1328 error.Clear();
1329 return size;
1330 }
1331 else if (response.IsErrorPacket())
1332 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1333 else if (response.IsUnsupportedPacket())
1334 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1335 else
1336 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1337 }
1338 else
1339 {
1340 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1341 }
1342 return 0;
1343}
1344
1345lldb::addr_t
1346ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1347{
1348 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1349 if (allocated_addr == LLDB_INVALID_ADDRESS)
1350 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1351 else
1352 error.Clear();
1353 return allocated_addr;
1354}
1355
1356Error
1357ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1358{
1359 Error error;
1360 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1361 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1362 return error;
1363}
1364
1365
1366//------------------------------------------------------------------
1367// Process STDIO
1368//------------------------------------------------------------------
1369
1370size_t
1371ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1372{
1373 Mutex::Locker locker(m_stdio_mutex);
1374 size_t bytes_available = m_stdout_data.size();
1375 if (bytes_available > 0)
1376 {
1377 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1378 if (bytes_available > buf_size)
1379 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001380 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001381 m_stdout_data.erase(0, buf_size);
1382 bytes_available = buf_size;
1383 }
1384 else
1385 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001386 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001387 m_stdout_data.clear();
1388
1389 //ResetEventBits(eBroadcastBitSTDOUT);
1390 }
1391 }
1392 return bytes_available;
1393}
1394
1395size_t
1396ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1397{
1398 // Can we get STDERR through the remote protocol?
1399 return 0;
1400}
1401
1402size_t
1403ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1404{
1405 if (m_stdio_communication.IsConnected())
1406 {
1407 ConnectionStatus status;
1408 m_stdio_communication.Write(src, src_len, status, NULL);
1409 }
1410 return 0;
1411}
1412
1413Error
1414ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1415{
1416 Error error;
1417 assert (bp_site != NULL);
1418
Greg Claytone005f2c2010-11-06 01:53:30 +00001419 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001420 user_id_t site_id = bp_site->GetID();
1421 const addr_t addr = bp_site->GetLoadAddress();
1422 if (log)
1423 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1424
1425 if (bp_site->IsEnabled())
1426 {
1427 if (log)
1428 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1429 return error;
1430 }
1431 else
1432 {
1433 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1434
1435 if (bp_site->HardwarePreferred())
1436 {
1437 // Try and set hardware breakpoint, and if that fails, fall through
1438 // and set a software breakpoint?
1439 }
1440
1441 if (m_z0_supported)
1442 {
1443 char packet[64];
1444 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1445 assert (packet_len + 1 < sizeof(packet));
1446 StringExtractorGDBRemote response;
1447 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1448 {
1449 if (response.IsUnsupportedPacket())
1450 {
1451 // Disable z packet support and try again
1452 m_z0_supported = 0;
1453 return EnableBreakpoint (bp_site);
1454 }
1455 else if (response.IsOKPacket())
1456 {
1457 bp_site->SetEnabled(true);
1458 bp_site->SetType (BreakpointSite::eExternal);
1459 return error;
1460 }
1461 else
1462 {
1463 uint8_t error_byte = response.GetError();
1464 if (error_byte)
1465 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1466 }
1467 }
1468 }
1469 else
1470 {
1471 return EnableSoftwareBreakpoint (bp_site);
1472 }
1473 }
1474
1475 if (log)
1476 {
1477 const char *err_string = error.AsCString();
1478 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1479 bp_site->GetLoadAddress(),
1480 err_string ? err_string : "NULL");
1481 }
1482 // We shouldn't reach here on a successful breakpoint enable...
1483 if (error.Success())
1484 error.SetErrorToGenericError();
1485 return error;
1486}
1487
1488Error
1489ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1490{
1491 Error error;
1492 assert (bp_site != NULL);
1493 addr_t addr = bp_site->GetLoadAddress();
1494 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001495 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001496 if (log)
1497 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1498
1499 if (bp_site->IsEnabled())
1500 {
1501 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1502
1503 if (bp_site->IsHardware())
1504 {
1505 // TODO: disable hardware breakpoint...
1506 }
1507 else
1508 {
1509 if (m_z0_supported)
1510 {
1511 char packet[64];
1512 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1513 assert (packet_len + 1 < sizeof(packet));
1514 StringExtractorGDBRemote response;
1515 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1516 {
1517 if (response.IsUnsupportedPacket())
1518 {
1519 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1520 }
1521 else if (response.IsOKPacket())
1522 {
1523 if (log)
1524 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1525 bp_site->SetEnabled(false);
1526 return error;
1527 }
1528 else
1529 {
1530 uint8_t error_byte = response.GetError();
1531 if (error_byte)
1532 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1533 }
1534 }
1535 }
1536 else
1537 {
1538 return DisableSoftwareBreakpoint (bp_site);
1539 }
1540 }
1541 }
1542 else
1543 {
1544 if (log)
1545 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1546 return error;
1547 }
1548
1549 if (error.Success())
1550 error.SetErrorToGenericError();
1551 return error;
1552}
1553
1554Error
1555ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1556{
1557 Error error;
1558 if (wp)
1559 {
1560 user_id_t watchID = wp->GetID();
1561 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001562 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001563 if (log)
1564 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1565 if (wp->IsEnabled())
1566 {
1567 if (log)
1568 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1569 return error;
1570 }
1571 else
1572 {
1573 // Pass down an appropriate z/Z packet...
1574 error.SetErrorString("watchpoints not supported");
1575 }
1576 }
1577 else
1578 {
1579 error.SetErrorString("Watchpoint location argument was NULL.");
1580 }
1581 if (error.Success())
1582 error.SetErrorToGenericError();
1583 return error;
1584}
1585
1586Error
1587ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1588{
1589 Error error;
1590 if (wp)
1591 {
1592 user_id_t watchID = wp->GetID();
1593
Greg Claytone005f2c2010-11-06 01:53:30 +00001594 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001595
1596 addr_t addr = wp->GetLoadAddress();
1597 if (log)
1598 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1599
1600 if (wp->IsHardware())
1601 {
1602 // Pass down an appropriate z/Z packet...
1603 error.SetErrorString("watchpoints not supported");
1604 }
1605 // TODO: clear software watchpoints if we implement them
1606 }
1607 else
1608 {
1609 error.SetErrorString("Watchpoint location argument was NULL.");
1610 }
1611 if (error.Success())
1612 error.SetErrorToGenericError();
1613 return error;
1614}
1615
1616void
1617ProcessGDBRemote::Clear()
1618{
1619 m_flags = 0;
1620 m_thread_list.Clear();
1621 {
1622 Mutex::Locker locker(m_stdio_mutex);
1623 m_stdout_data.clear();
1624 }
Chris Lattner24943d22010-06-08 16:52:24 +00001625}
1626
1627Error
1628ProcessGDBRemote::DoSignal (int signo)
1629{
1630 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001631 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001632 if (log)
1633 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1634
1635 if (!m_gdb_comm.SendAsyncSignal (signo))
1636 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1637 return error;
1638}
1639
Caroline Tice861efb32010-11-16 05:07:41 +00001640//void
1641//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1642//{
1643// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1644// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1645//}
Chris Lattner24943d22010-06-08 16:52:24 +00001646
Caroline Tice861efb32010-11-16 05:07:41 +00001647//void
1648//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1649//{
1650// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1651// Mutex::Locker locker(m_stdio_mutex);
1652// m_stdout_data.append(s, len);
1653//
1654// // FIXME: Make a real data object for this and put it out.
1655// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1656//}
Chris Lattner24943d22010-06-08 16:52:24 +00001657
1658
1659Error
1660ProcessGDBRemote::StartDebugserverProcess
1661(
1662 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1663 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1664 char const *inferior_envp[], // Environment to pass along to the inferior program
1665 char const *stdio_path,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001666 bool launch_process, // Set to true if we are going to be launching a the process
1667 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 +00001668 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1669 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001670 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001671 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1672)
1673{
1674 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001675 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1676 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001677 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1678 {
1679 // If we locate debugserver, keep that located version around
1680 static FileSpec g_debugserver_file_spec;
1681
1682 FileSpec debugserver_file_spec;
1683 char debugserver_path[PATH_MAX];
1684
1685 // Always check to see if we have an environment override for the path
1686 // to the debugserver to use and use it if we do.
1687 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1688 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001689 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001690 else
1691 debugserver_file_spec = g_debugserver_file_spec;
1692 bool debugserver_exists = debugserver_file_spec.Exists();
1693 if (!debugserver_exists)
1694 {
1695 // The debugserver binary is in the LLDB.framework/Resources
1696 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001697 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001698 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001699 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001700 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001701 if (debugserver_exists)
1702 {
1703 g_debugserver_file_spec = debugserver_file_spec;
1704 }
1705 else
1706 {
1707 g_debugserver_file_spec.Clear();
1708 debugserver_file_spec.Clear();
1709 }
Chris Lattner24943d22010-06-08 16:52:24 +00001710 }
1711 }
1712
1713 if (debugserver_exists)
1714 {
1715 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1716
1717 m_stdio_communication.Clear();
1718 posix_spawnattr_t attr;
1719
Greg Claytone005f2c2010-11-06 01:53:30 +00001720 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001721
1722 Error local_err; // Errors that don't affect the spawning.
1723 if (log)
1724 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1725 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1726 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001727 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001728 if (error.Fail())
1729 return error;;
1730
1731#if !defined (__arm__)
1732
Greg Clayton24b48ff2010-10-17 22:03:32 +00001733 // We don't need to do this for ARM, and we really shouldn't now
1734 // that we have multiple CPU subtypes and no posix_spawnattr call
1735 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001736 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001737 {
Greg Claytoncf015052010-06-11 03:25:34 +00001738 cpu_type_t cpu = inferior_arch.GetCPUType();
1739 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1740 {
1741 size_t ocount = 0;
1742 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1743 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001744 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 +00001745
Greg Claytoncf015052010-06-11 03:25:34 +00001746 if (error.Fail() != 0 || ocount != 1)
1747 return error;
1748 }
Chris Lattner24943d22010-06-08 16:52:24 +00001749 }
1750
1751#endif
1752
1753 Args debugserver_args;
1754 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001755
Chris Lattner24943d22010-06-08 16:52:24 +00001756 lldb_utility::PseudoTerminal pty;
Caroline Ticebd666012010-12-03 18:46:09 +00001757 if (launch_process && stdio_path == NULL && m_local_debugserver && !no_stdio)
Chris Lattner24943d22010-06-08 16:52:24 +00001758 {
Chris Lattner24943d22010-06-08 16:52:24 +00001759 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner24943d22010-06-08 16:52:24 +00001760 stdio_path = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +00001761 }
1762
1763 // Start args with "debugserver /file/path -r --"
1764 debugserver_args.AppendArgument(debugserver_path);
1765 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001766 // use native registers, not the GDB registers
1767 debugserver_args.AppendArgument("--native-regs");
1768 // make debugserver run in its own session so signals generated by
1769 // special terminal key sequences (^C) don't affect debugserver
1770 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001771
Greg Clayton452bf612010-08-31 18:35:14 +00001772 if (disable_aslr)
1773 debugserver_args.AppendArguments("--disable-aslr");
1774
Chris Lattner24943d22010-06-08 16:52:24 +00001775 // Only set the inferior
Greg Clayton23cf0c72010-11-08 04:29:11 +00001776 if (launch_process && stdio_path)
Chris Lattner24943d22010-06-08 16:52:24 +00001777 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001778 debugserver_args.AppendArgument("--stdio-path");
1779 debugserver_args.AppendArgument(stdio_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001780 }
Caroline Ticebd666012010-12-03 18:46:09 +00001781 else if (launch_process && no_stdio)
1782 {
1783 debugserver_args.AppendArgument("--no-stdio");
1784 }
Chris Lattner24943d22010-06-08 16:52:24 +00001785
1786 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1787 if (env_debugserver_log_file)
1788 {
1789 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1790 debugserver_args.AppendArgument(arg_cstr);
1791 }
1792
1793 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1794 if (env_debugserver_log_flags)
1795 {
1796 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1797 debugserver_args.AppendArgument(arg_cstr);
1798 }
1799// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1800// debugserver_args.AppendArgument("--log-flags=0x800e0e");
1801
1802 // Now append the program arguments
1803 if (launch_process)
1804 {
1805 if (inferior_argv)
1806 {
1807 // Terminate the debugserver args so we can now append the inferior args
1808 debugserver_args.AppendArgument("--");
1809
1810 for (int i = 0; inferior_argv[i] != NULL; ++i)
1811 debugserver_args.AppendArgument (inferior_argv[i]);
1812 }
1813 else
1814 {
1815 // Will send environment entries with the 'QEnvironment:' packet
1816 // Will send arguments with the 'A' packet
1817 }
1818 }
1819 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1820 {
1821 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1822 debugserver_args.AppendArgument (arg_cstr);
1823 }
1824 else if (attach_name && attach_name[0])
1825 {
1826 if (wait_for_launch)
1827 debugserver_args.AppendArgument ("--waitfor");
1828 else
1829 debugserver_args.AppendArgument ("--attach");
1830 debugserver_args.AppendArgument (attach_name);
1831 }
1832
1833 Error file_actions_err;
1834 posix_spawn_file_actions_t file_actions;
1835#if DONT_CLOSE_DEBUGSERVER_STDIO
1836 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1837#else
1838 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1839 if (file_actions_err.Success())
1840 {
1841 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1842 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1843 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1844 }
1845#endif
1846
1847 if (log)
1848 {
1849 StreamString strm;
1850 debugserver_args.Dump (&strm);
1851 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1852 }
1853
1854 error.SetError(::posix_spawnp (&m_debugserver_pid,
1855 debugserver_path,
1856 file_actions_err.Success() ? &file_actions : NULL,
1857 &attr,
1858 debugserver_args.GetArgumentVector(),
1859 (char * const*)inferior_envp),
1860 eErrorTypePOSIX);
1861
Greg Claytone9d0df42010-07-02 01:29:13 +00001862
1863 ::posix_spawnattr_destroy (&attr);
1864
Chris Lattner24943d22010-06-08 16:52:24 +00001865 if (file_actions_err.Success())
1866 ::posix_spawn_file_actions_destroy (&file_actions);
1867
1868 // We have seen some cases where posix_spawnp was returning a valid
1869 // looking pid even when an error was returned, so clear it out
1870 if (error.Fail())
1871 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1872
1873 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001874 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 +00001875
Caroline Ticebd666012010-12-03 18:46:09 +00001876 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00001877 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00001878 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00001879 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00001880 }
Chris Lattner24943d22010-06-08 16:52:24 +00001881 }
1882 else
1883 {
1884 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
1885 }
1886
1887 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1888 StartAsyncThread ();
1889 }
1890 return error;
1891}
1892
1893bool
1894ProcessGDBRemote::MonitorDebugserverProcess
1895(
1896 void *callback_baton,
1897 lldb::pid_t debugserver_pid,
1898 int signo, // Zero for no signal
1899 int exit_status // Exit value of process if signal is zero
1900)
1901{
1902 // We pass in the ProcessGDBRemote inferior process it and name it
1903 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
1904 // pointer value itself, thus we need the double cast...
1905
1906 // "debugserver_pid" argument passed in is the process ID for
1907 // debugserver that we are tracking...
1908
Greg Clayton75ccf502010-08-21 02:22:51 +00001909 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
1910
1911 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00001912 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001913 // Sleep for a half a second to make sure our inferior process has
1914 // time to set its exit status before we set it incorrectly when
1915 // both the debugserver and the inferior process shut down.
1916 usleep (500000);
1917 // If our process hasn't yet exited, debugserver might have died.
1918 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001919 const StateType state = process->GetState();
1920
1921 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
1922 state != eStateInvalid &&
1923 state != eStateUnloaded &&
1924 state != eStateExited &&
1925 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00001926 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001927 char error_str[1024];
1928 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00001929 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001930 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
1931 if (signal_cstr)
1932 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00001933 else
Greg Clayton75ccf502010-08-21 02:22:51 +00001934 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00001935 }
1936 else
1937 {
Greg Clayton75ccf502010-08-21 02:22:51 +00001938 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
Chris Lattner24943d22010-06-08 16:52:24 +00001939 }
Greg Clayton75ccf502010-08-21 02:22:51 +00001940
1941 process->SetExitStatus (-1, error_str);
1942 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001943 // Debugserver has exited we need to let our ProcessGDBRemote
1944 // know that it no longer has a debugserver instance
1945 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1946 // We are returning true to this function below, so we can
1947 // forget about the monitor handle.
1948 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001949 }
1950 return true;
1951}
1952
1953void
1954ProcessGDBRemote::KillDebugserverProcess ()
1955{
1956 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
1957 {
1958 ::kill (m_debugserver_pid, SIGINT);
1959 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1960 }
1961}
1962
1963void
1964ProcessGDBRemote::Initialize()
1965{
1966 static bool g_initialized = false;
1967
1968 if (g_initialized == false)
1969 {
1970 g_initialized = true;
1971 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1972 GetPluginDescriptionStatic(),
1973 CreateInstance);
1974
1975 Log::Callbacks log_callbacks = {
1976 ProcessGDBRemoteLog::DisableLog,
1977 ProcessGDBRemoteLog::EnableLog,
1978 ProcessGDBRemoteLog::ListLogCategories
1979 };
1980
1981 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
1982 }
1983}
1984
1985bool
1986ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
1987{
1988 if (m_curr_tid == tid)
1989 return true;
1990
1991 char packet[32];
1992 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
1993 assert (packet_len + 1 < sizeof(packet));
1994 StringExtractorGDBRemote response;
1995 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
1996 {
1997 if (response.IsOKPacket())
1998 {
1999 m_curr_tid = tid;
2000 return true;
2001 }
2002 }
2003 return false;
2004}
2005
2006bool
2007ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2008{
2009 if (m_curr_tid_run == tid)
2010 return true;
2011
2012 char packet[32];
Greg Claytonc71899e2011-01-18 19:36:39 +00002013 const int packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002014 assert (packet_len + 1 < sizeof(packet));
2015 StringExtractorGDBRemote response;
2016 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2017 {
2018 if (response.IsOKPacket())
2019 {
2020 m_curr_tid_run = tid;
2021 return true;
2022 }
2023 }
2024 return false;
2025}
2026
2027void
2028ProcessGDBRemote::ResetGDBRemoteState ()
2029{
2030 // Reset and GDB remote state
2031 m_curr_tid = LLDB_INVALID_THREAD_ID;
2032 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2033 m_z0_supported = 1;
2034}
2035
2036
2037bool
2038ProcessGDBRemote::StartAsyncThread ()
2039{
2040 ResetGDBRemoteState ();
2041
Greg Claytone005f2c2010-11-06 01:53:30 +00002042 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002043
2044 if (log)
2045 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2046
2047 // Create a thread that watches our internal state and controls which
2048 // events make it to clients (into the DCProcess event queue).
2049 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2050 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2051}
2052
2053void
2054ProcessGDBRemote::StopAsyncThread ()
2055{
Greg Claytone005f2c2010-11-06 01:53:30 +00002056 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002057
2058 if (log)
2059 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2060
2061 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2062
2063 // Stop the stdio thread
2064 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2065 {
2066 Host::ThreadJoin (m_async_thread, NULL, NULL);
2067 }
2068}
2069
2070
2071void *
2072ProcessGDBRemote::AsyncThread (void *arg)
2073{
2074 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2075
Greg Claytone005f2c2010-11-06 01:53:30 +00002076 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002077 if (log)
2078 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2079
2080 Listener listener ("ProcessGDBRemote::AsyncThread");
2081 EventSP event_sp;
2082 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2083 eBroadcastBitAsyncThreadShouldExit;
2084
2085 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2086 {
2087 bool done = false;
2088 while (!done)
2089 {
Caroline Tice926060e2010-10-29 21:48:37 +00002090 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002091 if (log)
2092 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2093 if (listener.WaitForEvent (NULL, event_sp))
2094 {
2095 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002096 if (log)
2097 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2098
Chris Lattner24943d22010-06-08 16:52:24 +00002099 switch (event_type)
2100 {
2101 case eBroadcastBitAsyncContinue:
2102 {
2103 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2104
2105 if (continue_packet)
2106 {
2107 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2108 const size_t continue_cstr_len = continue_packet->GetByteSize ();
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) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2112
2113 process->SetPrivateState(eStateRunning);
2114 StringExtractorGDBRemote response;
2115 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2116
2117 switch (stop_state)
2118 {
2119 case eStateStopped:
2120 case eStateCrashed:
2121 case eStateSuspended:
2122 process->m_last_stop_packet = response;
2123 process->m_last_stop_packet.SetFilePos (0);
2124 process->SetPrivateState (stop_state);
2125 break;
2126
2127 case eStateExited:
2128 process->m_last_stop_packet = response;
2129 process->m_last_stop_packet.SetFilePos (0);
2130 response.SetFilePos(1);
2131 process->SetExitStatus(response.GetHexU8(), NULL);
2132 done = true;
2133 break;
2134
2135 case eStateInvalid:
2136 break;
2137
2138 default:
2139 process->SetPrivateState (stop_state);
2140 break;
2141 }
2142 }
2143 }
2144 break;
2145
2146 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002147 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002148 if (log)
2149 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2150 done = true;
2151 break;
2152
2153 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002154 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002155 if (log)
2156 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2157 done = true;
2158 break;
2159 }
2160 }
2161 else
2162 {
Caroline Tice926060e2010-10-29 21:48:37 +00002163 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002164 if (log)
2165 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2166 done = true;
2167 }
2168 }
2169 }
2170
Caroline Tice926060e2010-10-29 21:48:37 +00002171 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002172 if (log)
2173 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2174
2175 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2176 return NULL;
2177}
2178
Chris Lattner24943d22010-06-08 16:52:24 +00002179const char *
2180ProcessGDBRemote::GetDispatchQueueNameForThread
2181(
2182 addr_t thread_dispatch_qaddr,
2183 std::string &dispatch_queue_name
2184)
2185{
2186 dispatch_queue_name.clear();
2187 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2188 {
2189 // Cache the dispatch_queue_offsets_addr value so we don't always have
2190 // to look it up
2191 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2192 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002193 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2194 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002195 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002196 if (module_sp)
2197 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2198
2199 if (dispatch_queue_offsets_symbol == NULL)
2200 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002201 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002202 if (module_sp)
2203 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2204 }
Chris Lattner24943d22010-06-08 16:52:24 +00002205 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002206 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002207
2208 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2209 return NULL;
2210 }
2211
2212 uint8_t memory_buffer[8];
2213 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2214
2215 // Excerpt from src/queue_private.h
2216 struct dispatch_queue_offsets_s
2217 {
2218 uint16_t dqo_version;
2219 uint16_t dqo_label;
2220 uint16_t dqo_label_size;
2221 } dispatch_queue_offsets;
2222
2223
2224 Error error;
2225 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2226 {
2227 uint32_t data_offset = 0;
2228 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2229 {
2230 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2231 {
2232 data_offset = 0;
2233 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2234 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2235 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2236 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2237 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2238 dispatch_queue_name.erase (bytes_read);
2239 }
2240 }
2241 }
2242 }
2243 if (dispatch_queue_name.empty())
2244 return NULL;
2245 return dispatch_queue_name.c_str();
2246}
2247
Jim Ingham7508e732010-08-09 23:31:02 +00002248uint32_t
2249ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2250{
2251 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2252 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2253 if (m_local_debugserver)
2254 {
2255 return Host::ListProcessesMatchingName (name, matches, pids);
2256 }
2257 else
2258 {
2259 // FIXME: Implement talking to the remote debugserver.
2260 return 0;
2261 }
2262
2263}
Jim Ingham55e01d82011-01-22 01:33:44 +00002264
2265bool
2266ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2267 lldb_private::StoppointCallbackContext *context,
2268 lldb::user_id_t break_id,
2269 lldb::user_id_t break_loc_id)
2270{
2271 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2272 // run so I can stop it if that's what I want to do.
2273 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2274 if (log)
2275 log->Printf("Hit New Thread Notification breakpoint.");
2276 return false;
2277}
2278
2279
2280bool
2281ProcessGDBRemote::StartNoticingNewThreads()
2282{
2283 static const char *bp_names[] =
2284 {
2285 "start_wqthread",
2286 "_pthread_start",
2287 NULL
2288 };
2289
2290 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2291 size_t num_bps = m_thread_observation_bps.size();
2292 if (num_bps != 0)
2293 {
2294 for (int i = 0; i < num_bps; i++)
2295 {
2296 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2297 if (break_sp)
2298 {
2299 if (log)
2300 log->Printf("Enabled noticing new thread breakpoint.");
2301 break_sp->SetEnabled(true);
2302 }
2303 }
2304 }
2305 else
2306 {
2307 for (int i = 0; bp_names[i] != NULL; i++)
2308 {
2309 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2310 if (breakpoint)
2311 {
2312 if (log)
2313 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2314 m_thread_observation_bps.push_back(breakpoint->GetID());
2315 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2316 }
2317 else
2318 {
2319 if (log)
2320 log->Printf("Failed to create new thread notification breakpoint.");
2321 return false;
2322 }
2323 }
2324 }
2325
2326 return true;
2327}
2328
2329bool
2330ProcessGDBRemote::StopNoticingNewThreads()
2331{
2332 size_t num_bps = m_thread_observation_bps.size();
2333 if (num_bps != 0)
2334 {
2335 for (int i = 0; i < num_bps; i++)
2336 {
2337 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2338
2339 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2340 if (break_sp)
2341 {
2342 if (log)
2343 log->Printf ("Disabling new thread notification breakpoint.");
2344 break_sp->SetEnabled(false);
2345 }
2346 }
2347 }
2348 return true;
2349}
2350
2351