blob: afaf3744c0e923cd7020b88f91384a3424e7e55b [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,
Greg Claytonde915be2011-01-23 05:56:20 +0000378 const char *stderr_path,
379 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000380)
381{
Greg Clayton4b407112010-09-30 21:49:03 +0000382 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000383 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
384 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
385 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000386
387 ObjectFile * object_file = module->GetObjectFile();
388 if (object_file)
389 {
390 ArchSpec inferior_arch(module->GetArchitecture());
391 char host_port[128];
392 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
393
Greg Clayton23cf0c72010-11-08 04:29:11 +0000394 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000395 bool start_debugserver_with_inferior_args = false;
396 if (start_debugserver_with_inferior_args)
397 {
398 // We want to launch debugserver with the inferior program and its
399 // arguments on the command line. We should only do this if we
400 // the GDB server we are talking to doesn't support the 'A' packet.
401 error = StartDebugserverProcess (host_port,
402 argv,
403 envp,
Greg Claytonde915be2011-01-23 05:56:20 +0000404 stdin_path,
405 stdout_path,
406 stderr_path,
407 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000408 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000409 LLDB_INVALID_PROCESS_ID,
410 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000411 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000412 inferior_arch);
413 if (error.Fail())
414 return error;
415
416 error = ConnectToDebugserver (host_port);
417 if (error.Success())
418 {
419 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
420 }
421 }
422 else
423 {
424 error = StartDebugserverProcess (host_port,
425 NULL,
426 NULL,
Greg Claytonde915be2011-01-23 05:56:20 +0000427 stdin_path,
428 stdout_path,
429 stderr_path,
430 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000431 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000432 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000433 NULL,
434 false,
Caroline Ticebd666012010-12-03 18:46:09 +0000435 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000436 inferior_arch);
437 if (error.Fail())
438 return error;
439
440 error = ConnectToDebugserver (host_port);
441 if (error.Success())
442 {
443 // Send the environment and the program + arguments after we connect
444 if (envp)
445 {
446 const char *env_entry;
447 for (int i=0; (env_entry = envp[i]); ++i)
448 {
449 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
450 break;
451 }
452 }
453
Greg Clayton960d6a42010-08-03 00:35:52 +0000454 // FIXME: convert this to use the new set/show variables when they are available
455#if 0
456 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
457 {
458 const uint32_t attach_debugserver_secs = 10;
459 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
460 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
461 {
462 printf ("%i\n", attach_debugserver_secs - i);
463 sleep (1);
464 }
465 }
466#endif
467
Chris Lattner24943d22010-06-08 16:52:24 +0000468 const uint32_t arg_timeout_seconds = 10;
469 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
470 if (arg_packet_err == 0)
471 {
472 std::string error_str;
473 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
474 {
475 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
476 }
477 else
478 {
479 error.SetErrorString (error_str.c_str());
480 }
481 }
482 else
483 {
484 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
485 }
486
487 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
488 }
489 }
490
491 if (GetID() == LLDB_INVALID_PROCESS_ID)
492 {
493 KillDebugserverProcess ();
494 return error;
495 }
496
497 StringExtractorGDBRemote response;
498 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
499 SetPrivateState (SetThreadStopInfo (response));
500
501 }
502 else
503 {
504 // Set our user ID to an invalid process ID.
505 SetID(LLDB_INVALID_PROCESS_ID);
506 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
507 }
Chris Lattner24943d22010-06-08 16:52:24 +0000508 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000509
Chris Lattner24943d22010-06-08 16:52:24 +0000510}
511
512
513Error
514ProcessGDBRemote::ConnectToDebugserver (const char *host_port)
515{
516 Error error;
517 // Sleep and wait a bit for debugserver to start to listen...
518 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
519 if (conn_ap.get())
520 {
521 std::string connect_url("connect://");
522 connect_url.append (host_port);
523 const uint32_t max_retry_count = 50;
524 uint32_t retry_count = 0;
525 while (!m_gdb_comm.IsConnected())
526 {
527 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess)
528 {
529 m_gdb_comm.SetConnection (conn_ap.release());
530 break;
531 }
532 retry_count++;
533
534 if (retry_count >= max_retry_count)
535 break;
536
537 usleep (100000);
538 }
539 }
540
541 if (!m_gdb_comm.IsConnected())
542 {
543 if (error.Success())
544 error.SetErrorString("not connected to remote gdb server");
545 return error;
546 }
547
548 m_gdb_comm.SetAckMode (true);
549 if (m_gdb_comm.StartReadThread(&error))
550 {
551 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000552 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000553
554 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000555 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
556 this,
557 m_debugserver_pid,
558 false);
559
Chris Lattner24943d22010-06-08 16:52:24 +0000560 StringExtractorGDBRemote response;
561 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
562 {
563 if (response.IsOKPacket())
564 m_gdb_comm.SetAckMode (false);
565 }
Greg Claytonc71899e2011-01-18 19:36:39 +0000566
567 if (m_gdb_comm.SendPacketAndWaitForResponse("QThreadSuffixSupported", response, 1, false))
568 {
569 if (response.IsOKPacket())
570 m_gdb_comm.SetThreadSuffixSupported (true);
571 }
572
Chris Lattner24943d22010-06-08 16:52:24 +0000573 }
574 return error;
575}
576
577void
578ProcessGDBRemote::DidLaunchOrAttach ()
579{
580 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
581 if (GetID() == LLDB_INVALID_PROCESS_ID)
582 {
583 m_dynamic_loader_ap.reset();
584 }
585 else
586 {
587 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
588
Greg Clayton20d338f2010-11-18 05:57:03 +0000589 BuildDynamicRegisterInfo ();
590
591 m_byte_order = m_gdb_comm.GetByteOrder();
592
Chris Lattner24943d22010-06-08 16:52:24 +0000593 StreamString strm;
594
595 ArchSpec inferior_arch;
596 // See if the GDB server supports the qHostInfo information
597 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
598 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Clayton20d338f2010-11-18 05:57:03 +0000599 ArchSpec arch_spec (GetTarget().GetArchitecture());
Chris Lattner24943d22010-06-08 16:52:24 +0000600
Jim Ingham7508e732010-08-09 23:31:02 +0000601 if (arch_spec.IsValid() && arch_spec == ArchSpec ("arm"))
Chris Lattner24943d22010-06-08 16:52:24 +0000602 {
603 // For ARM we can't trust the arch of the process as it could
604 // have an armv6 object file, but be running on armv7 kernel.
605 inferior_arch = m_gdb_comm.GetHostArchitecture();
606 }
607
608 if (!inferior_arch.IsValid())
Jim Ingham7508e732010-08-09 23:31:02 +0000609 inferior_arch = arch_spec;
Chris Lattner24943d22010-06-08 16:52:24 +0000610
611 if (vendor == NULL)
612 vendor = Host::GetVendorString().AsCString("apple");
613
614 if (os_type == NULL)
615 os_type = Host::GetOSString().AsCString("darwin");
616
617 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
618
619 std::transform (strm.GetString().begin(),
620 strm.GetString().end(),
621 strm.GetString().begin(),
622 ::tolower);
623
624 m_target_triple.SetCString(strm.GetString().c_str());
625 }
626}
627
628void
629ProcessGDBRemote::DidLaunch ()
630{
631 DidLaunchOrAttach ();
632 if (m_dynamic_loader_ap.get())
633 m_dynamic_loader_ap->DidLaunch();
634}
635
636Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000637ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000638{
639 Error error;
640 // Clear out and clean up from any current state
641 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000642 ArchSpec arch_spec = GetTarget().GetArchitecture();
643
Greg Claytone005f2c2010-11-06 01:53:30 +0000644 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000645
646
Chris Lattner24943d22010-06-08 16:52:24 +0000647 if (attach_pid != LLDB_INVALID_PROCESS_ID)
648 {
Chris Lattner24943d22010-06-08 16:52:24 +0000649 char host_port[128];
650 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000651 error = StartDebugserverProcess (host_port, // debugserver_url
652 NULL, // inferior_argv
653 NULL, // inferior_envp
654 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000655 NULL, // stdout_path
656 NULL, // stderr_path
657 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000658 false, // launch_process == false (we are attaching)
659 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
660 NULL, // Don't send any attach by process name option to debugserver
661 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000662 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000663 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000664
665 if (error.Fail())
666 {
667 const char *error_string = error.AsCString();
668 if (error_string == NULL)
669 error_string = "unable to launch " DEBUGSERVER_BASENAME;
670
671 SetExitStatus (-1, error_string);
672 }
673 else
674 {
675 error = ConnectToDebugserver (host_port);
676 if (error.Success())
677 {
678 char packet[64];
679 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
680 StringExtractorGDBRemote response;
681 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
682 packet,
683 packet_len,
684 response);
685 switch (stop_state)
686 {
687 case eStateStopped:
688 case eStateCrashed:
689 case eStateSuspended:
690 SetID (attach_pid);
691 m_last_stop_packet = response;
692 m_last_stop_packet.SetFilePos (0);
693 SetPrivateState (stop_state);
694 break;
695
696 case eStateExited:
697 m_last_stop_packet = response;
698 m_last_stop_packet.SetFilePos (0);
699 response.SetFilePos(1);
700 SetExitStatus(response.GetHexU8(), NULL);
701 break;
702
703 default:
704 SetExitStatus(-1, "unable to attach to process");
705 break;
706 }
707
708 }
709 }
710 }
711
712 lldb::pid_t pid = GetID();
713 if (pid == LLDB_INVALID_PROCESS_ID)
714 {
715 KillDebugserverProcess();
716 }
717 return error;
718}
719
720size_t
721ProcessGDBRemote::AttachInputReaderCallback
722(
723 void *baton,
724 InputReader *reader,
725 lldb::InputReaderAction notification,
726 const char *bytes,
727 size_t bytes_len
728)
729{
730 if (notification == eInputReaderGotToken)
731 {
732 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
733 if (gdb_process->m_waiting_for_attach)
734 gdb_process->m_waiting_for_attach = false;
735 reader->SetIsDone(true);
736 return 1;
737 }
738 return 0;
739}
740
741Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000742ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000743{
744 Error error;
745 // Clear out and clean up from any current state
746 Clear();
747 // HACK: require arch be set correctly at the target level until we can
748 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000749
Greg Claytone005f2c2010-11-06 01:53:30 +0000750 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000751 if (process_name && process_name[0])
752 {
Chris Lattner24943d22010-06-08 16:52:24 +0000753 char host_port[128];
Jim Ingham7508e732010-08-09 23:31:02 +0000754 ArchSpec arch_spec = GetTarget().GetArchitecture();
Chris Lattner24943d22010-06-08 16:52:24 +0000755 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Clayton452bf612010-08-31 18:35:14 +0000756 error = StartDebugserverProcess (host_port, // debugserver_url
757 NULL, // inferior_argv
758 NULL, // inferior_envp
759 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000760 NULL, // stdout_path
761 NULL, // stderr_path
762 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000763 false, // launch_process == false (we are attaching)
764 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
765 NULL, // Don't send any attach by process name option to debugserver
766 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000767 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000768 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000769 if (error.Fail())
770 {
771 const char *error_string = error.AsCString();
772 if (error_string == NULL)
773 error_string = "unable to launch " DEBUGSERVER_BASENAME;
774
775 SetExitStatus (-1, error_string);
776 }
777 else
778 {
779 error = ConnectToDebugserver (host_port);
780 if (error.Success())
781 {
782 StreamString packet;
783
Chris Lattner24943d22010-06-08 16:52:24 +0000784 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000785 packet.PutCString("vAttachWait");
786 else
787 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000788 packet.PutChar(';');
789 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
790 StringExtractorGDBRemote response;
791 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this,
792 packet.GetData(),
793 packet.GetSize(),
794 response);
795 switch (stop_state)
796 {
797 case eStateStopped:
798 case eStateCrashed:
799 case eStateSuspended:
800 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout));
801 m_last_stop_packet = response;
802 m_last_stop_packet.SetFilePos (0);
803 SetPrivateState (stop_state);
804 break;
805
806 case eStateExited:
807 m_last_stop_packet = response;
808 m_last_stop_packet.SetFilePos (0);
809 response.SetFilePos(1);
810 SetExitStatus(response.GetHexU8(), NULL);
811 break;
812
813 default:
814 SetExitStatus(-1, "unable to attach to process");
815 break;
816 }
817 }
818 }
819 }
820
821 lldb::pid_t pid = GetID();
822 if (pid == LLDB_INVALID_PROCESS_ID)
823 {
824 KillDebugserverProcess();
Greg Claytonc1d37752010-10-18 01:45:30 +0000825
826 if (error.Success())
827 error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
Chris Lattner24943d22010-06-08 16:52:24 +0000828 }
Greg Claytonc1d37752010-10-18 01:45:30 +0000829
Chris Lattner24943d22010-06-08 16:52:24 +0000830 return error;
831}
832
833//
834// if (wait_for_launch)
835// {
836// InputReaderSP reader_sp (new InputReader());
837// StreamString instructions;
838// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name);
839// error = reader_sp->Initialize (AttachInputReaderCallback, // callback
840// this, // baton
841// eInputReaderGranularityByte,
842// NULL, // End token
843// false);
844//
845// StringExtractorGDBRemote response;
846// m_waiting_for_attach = true;
847// FILE *reader_out_fh = reader_sp->GetOutputFileHandle();
848// while (m_waiting_for_attach)
849// {
850// // Wait for one second for the stop reply packet
851// if (m_gdb_comm.WaitForPacket(response, 1))
852// {
853// // Got some sort of packet, see if it is the stop reply packet?
854// char ch = response.GetChar(0);
855// if (ch == 'T')
856// {
857// m_waiting_for_attach = false;
858// }
859// }
860// else
861// {
862// // Put a period character every second
863// fputc('.', reader_out_fh);
864// }
865// }
866// }
867// }
868// return GetID();
869//}
870
871void
872ProcessGDBRemote::DidAttach ()
873{
Chris Lattner24943d22010-06-08 16:52:24 +0000874 if (m_dynamic_loader_ap.get())
875 m_dynamic_loader_ap->DidAttach();
Jim Ingham7508e732010-08-09 23:31:02 +0000876 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000877}
878
879Error
880ProcessGDBRemote::WillResume ()
881{
882 m_continue_packet.Clear();
883 // Start the continue packet we will use to run the target. Each thread
884 // will append what it is supposed to be doing to this packet when the
885 // ThreadList::WillResume() is called. If a thread it supposed
886 // to stay stopped, then don't append anything to this string.
887 m_continue_packet.Printf("vCont");
888 return Error();
889}
890
891Error
892ProcessGDBRemote::DoResume ()
893{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000894 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000895 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000896
897 Listener listener ("gdb-remote.resume-packet-sent");
898 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
899 {
900 EventSP event_sp;
901 TimeValue timeout;
902 timeout = TimeValue::Now();
903 timeout.OffsetWithSeconds (5);
904 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
905
906 if (listener.WaitForEvent (&timeout, event_sp) == false)
907 error.SetErrorString("Resume timed out.");
908 }
909
Jim Ingham3ae449a2010-11-17 02:32:00 +0000910 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000911}
912
913size_t
914ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
915{
916 const uint8_t *trap_opcode = NULL;
917 uint32_t trap_opcode_size = 0;
918
919 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
920 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
921 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
922 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
923
Jim Ingham7508e732010-08-09 23:31:02 +0000924 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000925 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000926 {
Greg Claytoncf015052010-06-11 03:25:34 +0000927 case ArchSpec::eCPU_i386:
928 case ArchSpec::eCPU_x86_64:
929 trap_opcode = g_i386_breakpoint_opcode;
930 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
931 break;
932
933 case ArchSpec::eCPU_arm:
934 // TODO: fill this in for ARM. We need to dig up the symbol for
935 // the address in the breakpoint locaiton and figure out if it is
936 // an ARM or Thumb breakpoint.
937 trap_opcode = g_arm_breakpoint_opcode;
938 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
939 break;
940
941 case ArchSpec::eCPU_ppc:
942 case ArchSpec::eCPU_ppc64:
943 trap_opcode = g_ppc_breakpoint_opcode;
944 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
945 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000946
Greg Claytoncf015052010-06-11 03:25:34 +0000947 default:
948 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
949 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000950 }
951
952 if (trap_opcode && trap_opcode_size)
953 {
954 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
955 return trap_opcode_size;
956 }
957 return 0;
958}
959
960uint32_t
961ProcessGDBRemote::UpdateThreadListIfNeeded ()
962{
963 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000964 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000965 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000966 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
967
Greg Clayton5205f0b2010-09-03 17:10:42 +0000968 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000969 const uint32_t stop_id = GetStopID();
970 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
971 {
972 // Update the thread list's stop id immediately so we don't recurse into this function.
973 ThreadList curr_thread_list (this);
974 curr_thread_list.SetStopID(stop_id);
975
976 Error err;
977 StringExtractorGDBRemote response;
978 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
979 response.IsNormalPacket();
980 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
981 {
982 char ch = response.GetChar();
983 if (ch == 'l')
984 break;
985 if (ch == 'm')
986 {
987 do
988 {
989 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
990
991 if (tid != LLDB_INVALID_THREAD_ID)
992 {
993 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +0000994 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000995 thread_sp.reset (new ThreadGDBRemote (*this, tid));
996 curr_thread_list.AddThread(thread_sp);
997 }
998
999 ch = response.GetChar();
1000 } while (ch == ',');
1001 }
1002 }
1003
1004 m_thread_list = curr_thread_list;
1005
1006 SetThreadStopInfo (m_last_stop_packet);
1007 }
1008 return GetThreadList().GetSize(false);
1009}
1010
1011
1012StateType
1013ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1014{
1015 const char stop_type = stop_packet.GetChar();
1016 switch (stop_type)
1017 {
1018 case 'T':
1019 case 'S':
1020 {
1021 // Stop with signal and thread info
1022 const uint8_t signo = stop_packet.GetHexU8();
1023 std::string name;
1024 std::string value;
1025 std::string thread_name;
1026 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001027 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001028 uint32_t tid = LLDB_INVALID_THREAD_ID;
1029 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1030 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001031 ThreadSP thread_sp;
1032
Chris Lattner24943d22010-06-08 16:52:24 +00001033 while (stop_packet.GetNameColonValue(name, value))
1034 {
1035 if (name.compare("metype") == 0)
1036 {
1037 // exception type in big endian hex
1038 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1039 }
1040 else if (name.compare("mecount") == 0)
1041 {
1042 // exception count in big endian hex
1043 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1044 }
1045 else if (name.compare("medata") == 0)
1046 {
1047 // exception data in big endian hex
1048 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1049 }
1050 else if (name.compare("thread") == 0)
1051 {
1052 // thread in big endian hex
1053 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytona875b642011-01-09 21:07:35 +00001054 thread_sp = m_thread_list.FindThreadByID(tid, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001055 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001056 else if (name.compare("hexname") == 0)
1057 {
1058 StringExtractor name_extractor;
1059 // Swap "value" over into "name_extractor"
1060 name_extractor.GetStringRef().swap(value);
1061 // Now convert the HEX bytes into a string value
1062 name_extractor.GetHexByteString (value);
1063 thread_name.swap (value);
1064 }
Chris Lattner24943d22010-06-08 16:52:24 +00001065 else if (name.compare("name") == 0)
1066 {
1067 thread_name.swap (value);
1068 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001069 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001070 {
1071 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1072 }
Greg Claytona875b642011-01-09 21:07:35 +00001073 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1074 {
1075 // We have a register number that contains an expedited
1076 // register value. Lets supply this register to our thread
1077 // so it won't have to go and read it.
1078 if (thread_sp)
1079 {
1080 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1081
1082 if (reg != UINT32_MAX)
1083 {
1084 StringExtractor reg_value_extractor;
1085 // Swap "value" over into "reg_value_extractor"
1086 reg_value_extractor.GetStringRef().swap(value);
1087 static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor);
1088 }
1089 }
1090 }
Chris Lattner24943d22010-06-08 16:52:24 +00001091 }
Chris Lattner24943d22010-06-08 16:52:24 +00001092
1093 if (thread_sp)
1094 {
1095 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1096
1097 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001098 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001099 if (exc_type != 0)
1100 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001101 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001102
1103 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1104 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001105 exc_data_size,
1106 exc_data_size >= 1 ? exc_data[0] : 0,
1107 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001108 }
1109 else if (signo)
1110 {
Greg Clayton643ee732010-08-04 01:40:35 +00001111 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001112 }
1113 else
1114 {
Greg Clayton643ee732010-08-04 01:40:35 +00001115 StopInfoSP invalid_stop_info_sp;
1116 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001117 }
1118 }
1119 return eStateStopped;
1120 }
1121 break;
1122
1123 case 'W':
1124 // process exited
1125 return eStateExited;
1126
1127 default:
1128 break;
1129 }
1130 return eStateInvalid;
1131}
1132
1133void
1134ProcessGDBRemote::RefreshStateAfterStop ()
1135{
Jim Ingham7508e732010-08-09 23:31:02 +00001136 // FIXME - add a variable to tell that we're in the middle of attaching if we
1137 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001138 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001139// if (!GetTarget().GetArchitecture().IsValid())
1140// {
1141// Module *exe_module = GetTarget().GetExecutableModule().get();
1142// if (exe_module)
1143// m_arch_spec = exe_module->GetArchitecture();
1144// }
1145
Chris Lattner24943d22010-06-08 16:52:24 +00001146 // Let all threads recover from stopping and do any clean up based
1147 // on the previous thread state (if any).
1148 m_thread_list.RefreshStateAfterStop();
1149
1150 // Discover new threads:
1151 UpdateThreadListIfNeeded ();
1152}
1153
1154Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001155ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001156{
1157 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001158
Greg Claytona4881d02011-01-22 07:12:45 +00001159 bool timed_out = false;
1160 Mutex::Locker locker;
1161
1162 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
Greg Clayton20d338f2010-11-18 05:57:03 +00001163 {
Greg Claytona4881d02011-01-22 07:12:45 +00001164 if (timed_out)
1165 error.SetErrorString("timed out sending interrupt packet");
1166 else
1167 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton20d338f2010-11-18 05:57:03 +00001168 }
1169
Chris Lattner24943d22010-06-08 16:52:24 +00001170 return error;
1171}
1172
1173Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001174ProcessGDBRemote::InterruptIfRunning
1175(
1176 bool discard_thread_plans,
1177 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001178 EventSP &stop_event_sp
1179)
Chris Lattner24943d22010-06-08 16:52:24 +00001180{
1181 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001182
Greg Clayton2860ba92011-01-23 19:58:49 +00001183 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1184
Greg Clayton68ca8232011-01-25 02:58:48 +00001185 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001186 const bool is_running = m_gdb_comm.IsRunning();
1187 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001188 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001189 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001190 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001191 is_running);
1192
Greg Clayton2860ba92011-01-23 19:58:49 +00001193 if (discard_thread_plans)
1194 {
1195 if (log)
1196 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1197 m_thread_list.DiscardThreadPlans();
1198 }
1199 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001200 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001201 if (catch_stop_event)
1202 {
1203 if (log)
1204 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1205 PausePrivateStateThread();
1206 paused_private_state_thread = true;
1207 }
1208
Greg Clayton4fb400f2010-09-27 21:07:38 +00001209 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001210 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001211 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001212
Greg Clayton72e1c782011-01-22 23:43:18 +00001213 //m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1214 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001215 {
1216 if (timed_out)
1217 error.SetErrorString("timed out sending interrupt packet");
1218 else
1219 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001220 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001221 ResumePrivateStateThread();
1222 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001223 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001224
Greg Clayton72e1c782011-01-22 23:43:18 +00001225 if (catch_stop_event)
1226 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001227 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001228 TimeValue timeout_time;
1229 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001230 timeout_time.OffsetWithSeconds(5);
1231 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001232
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001233 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001234 if (log)
1235 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001236
Greg Clayton2860ba92011-01-23 19:58:49 +00001237 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001238 error.SetErrorString("unable to verify target stopped");
1239 }
1240
Greg Clayton68ca8232011-01-25 02:58:48 +00001241 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001242 {
1243 if (log)
1244 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001245 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001246 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001247 }
Chris Lattner24943d22010-06-08 16:52:24 +00001248 return error;
1249}
1250
Greg Clayton4fb400f2010-09-27 21:07:38 +00001251Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001252ProcessGDBRemote::WillDetach ()
1253{
Greg Clayton2860ba92011-01-23 19:58:49 +00001254 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1255 if (log)
1256 log->Printf ("ProcessGDBRemote::WillDetach()");
1257
Greg Clayton72e1c782011-01-22 23:43:18 +00001258 bool discard_thread_plans = true;
1259 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001260 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001261 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001262}
1263
1264Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001265ProcessGDBRemote::DoDetach()
1266{
1267 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001268 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001269 if (log)
1270 log->Printf ("ProcessGDBRemote::DoDetach()");
1271
1272 DisableAllBreakpointSites ();
1273
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001274 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001275
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001276 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1277 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001278 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001279 if (response_size)
1280 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1281 else
1282 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001283 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001284 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001285 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001286
Greg Clayton4fb400f2010-09-27 21:07:38 +00001287 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001288 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001289
1290 SetPrivateState (eStateDetached);
1291 ResumePrivateStateThread();
1292
1293 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001294 return error;
1295}
Chris Lattner24943d22010-06-08 16:52:24 +00001296
1297Error
1298ProcessGDBRemote::DoDestroy ()
1299{
1300 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001301 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001302 if (log)
1303 log->Printf ("ProcessGDBRemote::DoDestroy()");
1304
1305 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001306 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001307 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001308 StringExtractorGDBRemote response;
1309 bool send_async = true;
Greg Claytoncc3e6402011-01-25 06:55:13 +00001310 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, 2, send_async))
Greg Clayton27a8dd72011-01-25 04:57:42 +00001311 {
1312 char packet_cmd = response.GetChar(0);
1313
1314 if (packet_cmd == 'W' || packet_cmd == 'X')
1315 {
1316 m_last_stop_packet = response;
1317 SetExitStatus(response.GetHexU8(), NULL);
1318 }
1319 }
1320 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001321 {
Greg Claytoncc3e6402011-01-25 06:55:13 +00001322 SetExitStatus(SIGABRT, NULL);
1323 //error.SetErrorString("kill packet failed");
Greg Clayton72e1c782011-01-22 23:43:18 +00001324 }
1325 }
Chris Lattner24943d22010-06-08 16:52:24 +00001326 StopAsyncThread ();
1327 m_gdb_comm.StopReadThread();
1328 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001329 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001330 return error;
1331}
1332
Chris Lattner24943d22010-06-08 16:52:24 +00001333//------------------------------------------------------------------
1334// Process Queries
1335//------------------------------------------------------------------
1336
1337bool
1338ProcessGDBRemote::IsAlive ()
1339{
Greg Clayton58e844b2010-12-08 05:08:21 +00001340 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001341}
1342
1343addr_t
1344ProcessGDBRemote::GetImageInfoAddress()
1345{
1346 if (!m_gdb_comm.IsRunning())
1347 {
1348 StringExtractorGDBRemote response;
1349 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1350 {
1351 if (response.IsNormalPacket())
1352 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1353 }
1354 }
1355 return LLDB_INVALID_ADDRESS;
1356}
1357
1358DynamicLoader *
1359ProcessGDBRemote::GetDynamicLoader()
1360{
1361 return m_dynamic_loader_ap.get();
1362}
1363
1364//------------------------------------------------------------------
1365// Process Memory
1366//------------------------------------------------------------------
1367size_t
1368ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1369{
1370 if (size > m_max_memory_size)
1371 {
1372 // Keep memory read sizes down to a sane limit. This function will be
1373 // called multiple times in order to complete the task by
1374 // lldb_private::Process so it is ok to do this.
1375 size = m_max_memory_size;
1376 }
1377
1378 char packet[64];
1379 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1380 assert (packet_len + 1 < sizeof(packet));
1381 StringExtractorGDBRemote response;
1382 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1383 {
1384 if (response.IsNormalPacket())
1385 {
1386 error.Clear();
1387 return response.GetHexBytes(buf, size, '\xdd');
1388 }
1389 else if (response.IsErrorPacket())
1390 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1391 else if (response.IsUnsupportedPacket())
1392 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1393 else
1394 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1395 }
1396 else
1397 {
1398 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1399 }
1400 return 0;
1401}
1402
1403size_t
1404ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1405{
1406 StreamString packet;
1407 packet.Printf("M%llx,%zx:", addr, size);
1408 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost);
1409 StringExtractorGDBRemote response;
1410 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1411 {
1412 if (response.IsOKPacket())
1413 {
1414 error.Clear();
1415 return size;
1416 }
1417 else if (response.IsErrorPacket())
1418 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1419 else if (response.IsUnsupportedPacket())
1420 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1421 else
1422 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1423 }
1424 else
1425 {
1426 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1427 }
1428 return 0;
1429}
1430
1431lldb::addr_t
1432ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1433{
1434 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1435 if (allocated_addr == LLDB_INVALID_ADDRESS)
1436 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1437 else
1438 error.Clear();
1439 return allocated_addr;
1440}
1441
1442Error
1443ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1444{
1445 Error error;
1446 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1447 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1448 return error;
1449}
1450
1451
1452//------------------------------------------------------------------
1453// Process STDIO
1454//------------------------------------------------------------------
1455
1456size_t
1457ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1458{
1459 Mutex::Locker locker(m_stdio_mutex);
1460 size_t bytes_available = m_stdout_data.size();
1461 if (bytes_available > 0)
1462 {
1463 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1464 if (bytes_available > buf_size)
1465 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001466 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001467 m_stdout_data.erase(0, buf_size);
1468 bytes_available = buf_size;
1469 }
1470 else
1471 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001472 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001473 m_stdout_data.clear();
1474
1475 //ResetEventBits(eBroadcastBitSTDOUT);
1476 }
1477 }
1478 return bytes_available;
1479}
1480
1481size_t
1482ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1483{
1484 // Can we get STDERR through the remote protocol?
1485 return 0;
1486}
1487
1488size_t
1489ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1490{
1491 if (m_stdio_communication.IsConnected())
1492 {
1493 ConnectionStatus status;
1494 m_stdio_communication.Write(src, src_len, status, NULL);
1495 }
1496 return 0;
1497}
1498
1499Error
1500ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1501{
1502 Error error;
1503 assert (bp_site != NULL);
1504
Greg Claytone005f2c2010-11-06 01:53:30 +00001505 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001506 user_id_t site_id = bp_site->GetID();
1507 const addr_t addr = bp_site->GetLoadAddress();
1508 if (log)
1509 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1510
1511 if (bp_site->IsEnabled())
1512 {
1513 if (log)
1514 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1515 return error;
1516 }
1517 else
1518 {
1519 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1520
1521 if (bp_site->HardwarePreferred())
1522 {
1523 // Try and set hardware breakpoint, and if that fails, fall through
1524 // and set a software breakpoint?
1525 }
1526
1527 if (m_z0_supported)
1528 {
1529 char packet[64];
1530 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1531 assert (packet_len + 1 < sizeof(packet));
1532 StringExtractorGDBRemote response;
1533 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1534 {
1535 if (response.IsUnsupportedPacket())
1536 {
1537 // Disable z packet support and try again
1538 m_z0_supported = 0;
1539 return EnableBreakpoint (bp_site);
1540 }
1541 else if (response.IsOKPacket())
1542 {
1543 bp_site->SetEnabled(true);
1544 bp_site->SetType (BreakpointSite::eExternal);
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 EnableSoftwareBreakpoint (bp_site);
1558 }
1559 }
1560
1561 if (log)
1562 {
1563 const char *err_string = error.AsCString();
1564 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1565 bp_site->GetLoadAddress(),
1566 err_string ? err_string : "NULL");
1567 }
1568 // We shouldn't reach here on a successful breakpoint enable...
1569 if (error.Success())
1570 error.SetErrorToGenericError();
1571 return error;
1572}
1573
1574Error
1575ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1576{
1577 Error error;
1578 assert (bp_site != NULL);
1579 addr_t addr = bp_site->GetLoadAddress();
1580 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001581 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001582 if (log)
1583 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1584
1585 if (bp_site->IsEnabled())
1586 {
1587 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1588
1589 if (bp_site->IsHardware())
1590 {
1591 // TODO: disable hardware breakpoint...
1592 }
1593 else
1594 {
1595 if (m_z0_supported)
1596 {
1597 char packet[64];
1598 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1599 assert (packet_len + 1 < sizeof(packet));
1600 StringExtractorGDBRemote response;
1601 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1602 {
1603 if (response.IsUnsupportedPacket())
1604 {
1605 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1606 }
1607 else if (response.IsOKPacket())
1608 {
1609 if (log)
1610 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1611 bp_site->SetEnabled(false);
1612 return error;
1613 }
1614 else
1615 {
1616 uint8_t error_byte = response.GetError();
1617 if (error_byte)
1618 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1619 }
1620 }
1621 }
1622 else
1623 {
1624 return DisableSoftwareBreakpoint (bp_site);
1625 }
1626 }
1627 }
1628 else
1629 {
1630 if (log)
1631 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1632 return error;
1633 }
1634
1635 if (error.Success())
1636 error.SetErrorToGenericError();
1637 return error;
1638}
1639
1640Error
1641ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1642{
1643 Error error;
1644 if (wp)
1645 {
1646 user_id_t watchID = wp->GetID();
1647 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001648 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001649 if (log)
1650 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1651 if (wp->IsEnabled())
1652 {
1653 if (log)
1654 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1655 return error;
1656 }
1657 else
1658 {
1659 // Pass down an appropriate z/Z packet...
1660 error.SetErrorString("watchpoints not supported");
1661 }
1662 }
1663 else
1664 {
1665 error.SetErrorString("Watchpoint location argument was NULL.");
1666 }
1667 if (error.Success())
1668 error.SetErrorToGenericError();
1669 return error;
1670}
1671
1672Error
1673ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1674{
1675 Error error;
1676 if (wp)
1677 {
1678 user_id_t watchID = wp->GetID();
1679
Greg Claytone005f2c2010-11-06 01:53:30 +00001680 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001681
1682 addr_t addr = wp->GetLoadAddress();
1683 if (log)
1684 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1685
1686 if (wp->IsHardware())
1687 {
1688 // Pass down an appropriate z/Z packet...
1689 error.SetErrorString("watchpoints not supported");
1690 }
1691 // TODO: clear software watchpoints if we implement them
1692 }
1693 else
1694 {
1695 error.SetErrorString("Watchpoint location argument was NULL.");
1696 }
1697 if (error.Success())
1698 error.SetErrorToGenericError();
1699 return error;
1700}
1701
1702void
1703ProcessGDBRemote::Clear()
1704{
1705 m_flags = 0;
1706 m_thread_list.Clear();
1707 {
1708 Mutex::Locker locker(m_stdio_mutex);
1709 m_stdout_data.clear();
1710 }
Chris Lattner24943d22010-06-08 16:52:24 +00001711}
1712
1713Error
1714ProcessGDBRemote::DoSignal (int signo)
1715{
1716 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001717 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001718 if (log)
1719 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1720
1721 if (!m_gdb_comm.SendAsyncSignal (signo))
1722 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1723 return error;
1724}
1725
Caroline Tice861efb32010-11-16 05:07:41 +00001726//void
1727//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1728//{
1729// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1730// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1731//}
Chris Lattner24943d22010-06-08 16:52:24 +00001732
Caroline Tice861efb32010-11-16 05:07:41 +00001733//void
1734//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1735//{
1736// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1737// Mutex::Locker locker(m_stdio_mutex);
1738// m_stdout_data.append(s, len);
1739//
1740// // FIXME: Make a real data object for this and put it out.
1741// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1742//}
Chris Lattner24943d22010-06-08 16:52:24 +00001743
1744
1745Error
1746ProcessGDBRemote::StartDebugserverProcess
1747(
1748 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1749 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1750 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Claytonde915be2011-01-23 05:56:20 +00001751 const char *stdin_path,
1752 const char *stdout_path,
1753 const char *stderr_path,
1754 const char *working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001755 bool launch_process, // Set to true if we are going to be launching a the process
1756 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 +00001757 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1758 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001759 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001760 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1761)
1762{
1763 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001764 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1765 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001766 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1767 {
1768 // If we locate debugserver, keep that located version around
1769 static FileSpec g_debugserver_file_spec;
1770
1771 FileSpec debugserver_file_spec;
1772 char debugserver_path[PATH_MAX];
1773
1774 // Always check to see if we have an environment override for the path
1775 // to the debugserver to use and use it if we do.
1776 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1777 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001778 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001779 else
1780 debugserver_file_spec = g_debugserver_file_spec;
1781 bool debugserver_exists = debugserver_file_spec.Exists();
1782 if (!debugserver_exists)
1783 {
1784 // The debugserver binary is in the LLDB.framework/Resources
1785 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001786 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001787 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001788 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001789 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001790 if (debugserver_exists)
1791 {
1792 g_debugserver_file_spec = debugserver_file_spec;
1793 }
1794 else
1795 {
1796 g_debugserver_file_spec.Clear();
1797 debugserver_file_spec.Clear();
1798 }
Chris Lattner24943d22010-06-08 16:52:24 +00001799 }
1800 }
1801
1802 if (debugserver_exists)
1803 {
1804 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1805
1806 m_stdio_communication.Clear();
1807 posix_spawnattr_t attr;
1808
Greg Claytone005f2c2010-11-06 01:53:30 +00001809 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001810
1811 Error local_err; // Errors that don't affect the spawning.
1812 if (log)
1813 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1814 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1815 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001816 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001817 if (error.Fail())
1818 return error;;
1819
1820#if !defined (__arm__)
1821
Greg Clayton24b48ff2010-10-17 22:03:32 +00001822 // We don't need to do this for ARM, and we really shouldn't now
1823 // that we have multiple CPU subtypes and no posix_spawnattr call
1824 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001825 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001826 {
Greg Claytoncf015052010-06-11 03:25:34 +00001827 cpu_type_t cpu = inferior_arch.GetCPUType();
1828 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1829 {
1830 size_t ocount = 0;
1831 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1832 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001833 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 +00001834
Greg Claytoncf015052010-06-11 03:25:34 +00001835 if (error.Fail() != 0 || ocount != 1)
1836 return error;
1837 }
Chris Lattner24943d22010-06-08 16:52:24 +00001838 }
1839
1840#endif
1841
1842 Args debugserver_args;
1843 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001844
Chris Lattner24943d22010-06-08 16:52:24 +00001845 lldb_utility::PseudoTerminal pty;
Greg Claytonde915be2011-01-23 05:56:20 +00001846 const char *stdio_path = NULL;
1847 if (launch_process &&
Caroline Ticee4450f02011-01-28 00:19:58 +00001848 (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) &&
Greg Claytonde915be2011-01-23 05:56:20 +00001849 m_local_debugserver &&
1850 no_stdio == false)
Chris Lattner24943d22010-06-08 16:52:24 +00001851 {
Chris Lattner24943d22010-06-08 16:52:24 +00001852 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Caroline Ticee4450f02011-01-28 00:19:58 +00001853 {
1854 const char *slave_name = pty.GetSlaveName (NULL, 0);
1855 if (stdin_path == NULL
1856 && stdout_path == NULL
1857 && stderr_path == NULL)
1858 stdio_path = slave_name;
1859 else
1860 {
1861 if (stdin_path == NULL)
1862 stdin_path = slave_name;
1863 if (stdout_path == NULL)
1864 stdout_path = slave_name;
1865 if (stderr_path == NULL)
1866 stderr_path = slave_name;
1867 }
1868 }
Chris Lattner24943d22010-06-08 16:52:24 +00001869 }
1870
1871 // Start args with "debugserver /file/path -r --"
1872 debugserver_args.AppendArgument(debugserver_path);
1873 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001874 // use native registers, not the GDB registers
1875 debugserver_args.AppendArgument("--native-regs");
1876 // make debugserver run in its own session so signals generated by
1877 // special terminal key sequences (^C) don't affect debugserver
1878 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001879
Greg Clayton452bf612010-08-31 18:35:14 +00001880 if (disable_aslr)
1881 debugserver_args.AppendArguments("--disable-aslr");
1882
Chris Lattner24943d22010-06-08 16:52:24 +00001883 // Only set the inferior
Greg Claytonde915be2011-01-23 05:56:20 +00001884 if (launch_process)
Chris Lattner24943d22010-06-08 16:52:24 +00001885 {
Greg Claytonde915be2011-01-23 05:56:20 +00001886 if (no_stdio)
1887 debugserver_args.AppendArgument("--no-stdio");
1888 else
1889 {
1890 if (stdin_path && stdout_path && stderr_path &&
1891 strcmp(stdin_path, stdout_path) == 0 &&
1892 strcmp(stdin_path, stderr_path) == 0)
1893 {
1894 stdio_path = stdin_path;
1895 stdin_path = stdout_path = stderr_path = NULL;
1896 }
1897
1898 if (stdio_path)
1899 {
1900 // All file handles to stdin, stdout, stderr are the same...
1901 debugserver_args.AppendArgument("--stdio-path");
1902 debugserver_args.AppendArgument(stdio_path);
1903 }
1904 else
1905 {
1906 if (stdin_path == NULL && (stdout_path || stderr_path))
1907 stdin_path = "/dev/null";
1908
1909 if (stdout_path == NULL && (stdin_path || stderr_path))
1910 stdout_path = "/dev/null";
1911
1912 if (stderr_path == NULL && (stdin_path || stdout_path))
1913 stderr_path = "/dev/null";
1914
1915 if (stdin_path)
1916 {
1917 debugserver_args.AppendArgument("--stdin-path");
1918 debugserver_args.AppendArgument(stdin_path);
1919 }
1920 if (stdout_path)
1921 {
1922 debugserver_args.AppendArgument("--stdout-path");
1923 debugserver_args.AppendArgument(stdout_path);
1924 }
1925 if (stderr_path)
1926 {
1927 debugserver_args.AppendArgument("--stderr-path");
1928 debugserver_args.AppendArgument(stderr_path);
1929 }
1930 }
1931 }
Chris Lattner24943d22010-06-08 16:52:24 +00001932 }
Greg Claytonde915be2011-01-23 05:56:20 +00001933
1934 if (working_dir)
Caroline Ticebd666012010-12-03 18:46:09 +00001935 {
Greg Claytonde915be2011-01-23 05:56:20 +00001936 debugserver_args.AppendArgument("--working-dir");
1937 debugserver_args.AppendArgument(working_dir);
Caroline Ticebd666012010-12-03 18:46:09 +00001938 }
Chris Lattner24943d22010-06-08 16:52:24 +00001939
1940 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1941 if (env_debugserver_log_file)
1942 {
1943 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1944 debugserver_args.AppendArgument(arg_cstr);
1945 }
1946
1947 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1948 if (env_debugserver_log_flags)
1949 {
1950 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1951 debugserver_args.AppendArgument(arg_cstr);
1952 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001953// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
1954// debugserver_args.AppendArgument("--log-flags=0x800e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001955
1956 // Now append the program arguments
1957 if (launch_process)
1958 {
1959 if (inferior_argv)
1960 {
1961 // Terminate the debugserver args so we can now append the inferior args
1962 debugserver_args.AppendArgument("--");
1963
1964 for (int i = 0; inferior_argv[i] != NULL; ++i)
1965 debugserver_args.AppendArgument (inferior_argv[i]);
1966 }
1967 else
1968 {
1969 // Will send environment entries with the 'QEnvironment:' packet
1970 // Will send arguments with the 'A' packet
1971 }
1972 }
1973 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1974 {
1975 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1976 debugserver_args.AppendArgument (arg_cstr);
1977 }
1978 else if (attach_name && attach_name[0])
1979 {
1980 if (wait_for_launch)
1981 debugserver_args.AppendArgument ("--waitfor");
1982 else
1983 debugserver_args.AppendArgument ("--attach");
1984 debugserver_args.AppendArgument (attach_name);
1985 }
1986
1987 Error file_actions_err;
1988 posix_spawn_file_actions_t file_actions;
1989#if DONT_CLOSE_DEBUGSERVER_STDIO
1990 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1991#else
1992 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1993 if (file_actions_err.Success())
1994 {
1995 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1996 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1997 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1998 }
1999#endif
2000
2001 if (log)
2002 {
2003 StreamString strm;
2004 debugserver_args.Dump (&strm);
2005 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2006 }
2007
Greg Clayton72e1c782011-01-22 23:43:18 +00002008 error.SetError (::posix_spawnp (&m_debugserver_pid,
2009 debugserver_path,
2010 file_actions_err.Success() ? &file_actions : NULL,
2011 &attr,
2012 debugserver_args.GetArgumentVector(),
2013 (char * const*)inferior_envp),
2014 eErrorTypePOSIX);
2015
Greg Claytone9d0df42010-07-02 01:29:13 +00002016
2017 ::posix_spawnattr_destroy (&attr);
2018
Chris Lattner24943d22010-06-08 16:52:24 +00002019 if (file_actions_err.Success())
2020 ::posix_spawn_file_actions_destroy (&file_actions);
2021
2022 // We have seen some cases where posix_spawnp was returning a valid
2023 // looking pid even when an error was returned, so clear it out
2024 if (error.Fail())
2025 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2026
2027 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002028 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 +00002029
Caroline Ticebd666012010-12-03 18:46:09 +00002030 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00002031 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00002032 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00002033 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00002034 }
Chris Lattner24943d22010-06-08 16:52:24 +00002035 }
2036 else
2037 {
2038 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2039 }
2040
2041 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2042 StartAsyncThread ();
2043 }
2044 return error;
2045}
2046
2047bool
2048ProcessGDBRemote::MonitorDebugserverProcess
2049(
2050 void *callback_baton,
2051 lldb::pid_t debugserver_pid,
2052 int signo, // Zero for no signal
2053 int exit_status // Exit value of process if signal is zero
2054)
2055{
2056 // We pass in the ProcessGDBRemote inferior process it and name it
2057 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2058 // pointer value itself, thus we need the double cast...
2059
2060 // "debugserver_pid" argument passed in is the process ID for
2061 // debugserver that we are tracking...
2062
Greg Clayton75ccf502010-08-21 02:22:51 +00002063 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002064
2065 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2066 if (log)
2067 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2068
Greg Clayton75ccf502010-08-21 02:22:51 +00002069 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002070 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002071 // Sleep for a half a second to make sure our inferior process has
2072 // time to set its exit status before we set it incorrectly when
2073 // both the debugserver and the inferior process shut down.
2074 usleep (500000);
2075 // If our process hasn't yet exited, debugserver might have died.
2076 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002077 const StateType state = process->GetState();
2078
2079 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2080 state != eStateInvalid &&
2081 state != eStateUnloaded &&
2082 state != eStateExited &&
2083 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002084 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002085 char error_str[1024];
2086 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002087 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002088 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2089 if (signal_cstr)
2090 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002091 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002092 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002093 }
2094 else
2095 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002096 ::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 +00002097 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002098
2099 process->SetExitStatus (-1, error_str);
2100 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002101 // Debugserver has exited we need to let our ProcessGDBRemote
2102 // know that it no longer has a debugserver instance
2103 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2104 // We are returning true to this function below, so we can
2105 // forget about the monitor handle.
2106 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002107 }
2108 return true;
2109}
2110
2111void
2112ProcessGDBRemote::KillDebugserverProcess ()
2113{
2114 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2115 {
2116 ::kill (m_debugserver_pid, SIGINT);
2117 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2118 }
2119}
2120
2121void
2122ProcessGDBRemote::Initialize()
2123{
2124 static bool g_initialized = false;
2125
2126 if (g_initialized == false)
2127 {
2128 g_initialized = true;
2129 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2130 GetPluginDescriptionStatic(),
2131 CreateInstance);
2132
2133 Log::Callbacks log_callbacks = {
2134 ProcessGDBRemoteLog::DisableLog,
2135 ProcessGDBRemoteLog::EnableLog,
2136 ProcessGDBRemoteLog::ListLogCategories
2137 };
2138
2139 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2140 }
2141}
2142
2143bool
2144ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2145{
2146 if (m_curr_tid == tid)
2147 return true;
2148
2149 char packet[32];
2150 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2151 assert (packet_len + 1 < sizeof(packet));
2152 StringExtractorGDBRemote response;
2153 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2154 {
2155 if (response.IsOKPacket())
2156 {
2157 m_curr_tid = tid;
2158 return true;
2159 }
2160 }
2161 return false;
2162}
2163
2164bool
2165ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2166{
2167 if (m_curr_tid_run == tid)
2168 return true;
2169
2170 char packet[32];
Greg Claytonc71899e2011-01-18 19:36:39 +00002171 const int packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002172 assert (packet_len + 1 < sizeof(packet));
2173 StringExtractorGDBRemote response;
2174 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2175 {
2176 if (response.IsOKPacket())
2177 {
2178 m_curr_tid_run = tid;
2179 return true;
2180 }
2181 }
2182 return false;
2183}
2184
2185void
2186ProcessGDBRemote::ResetGDBRemoteState ()
2187{
2188 // Reset and GDB remote state
2189 m_curr_tid = LLDB_INVALID_THREAD_ID;
2190 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2191 m_z0_supported = 1;
2192}
2193
2194
2195bool
2196ProcessGDBRemote::StartAsyncThread ()
2197{
2198 ResetGDBRemoteState ();
2199
Greg Claytone005f2c2010-11-06 01:53:30 +00002200 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002201
2202 if (log)
2203 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2204
2205 // Create a thread that watches our internal state and controls which
2206 // events make it to clients (into the DCProcess event queue).
2207 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2208 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2209}
2210
2211void
2212ProcessGDBRemote::StopAsyncThread ()
2213{
Greg Claytone005f2c2010-11-06 01:53:30 +00002214 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002215
2216 if (log)
2217 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2218
2219 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2220
2221 // Stop the stdio thread
2222 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2223 {
2224 Host::ThreadJoin (m_async_thread, NULL, NULL);
2225 }
2226}
2227
2228
2229void *
2230ProcessGDBRemote::AsyncThread (void *arg)
2231{
2232 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2233
Greg Claytone005f2c2010-11-06 01:53:30 +00002234 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002235 if (log)
2236 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2237
2238 Listener listener ("ProcessGDBRemote::AsyncThread");
2239 EventSP event_sp;
2240 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2241 eBroadcastBitAsyncThreadShouldExit;
2242
2243 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2244 {
2245 bool done = false;
2246 while (!done)
2247 {
Caroline Tice926060e2010-10-29 21:48:37 +00002248 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002249 if (log)
2250 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2251 if (listener.WaitForEvent (NULL, event_sp))
2252 {
2253 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002254 if (log)
2255 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2256
Chris Lattner24943d22010-06-08 16:52:24 +00002257 switch (event_type)
2258 {
2259 case eBroadcastBitAsyncContinue:
2260 {
2261 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2262
2263 if (continue_packet)
2264 {
2265 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2266 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002267 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002268 if (log)
2269 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2270
2271 process->SetPrivateState(eStateRunning);
2272 StringExtractorGDBRemote response;
2273 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2274
2275 switch (stop_state)
2276 {
2277 case eStateStopped:
2278 case eStateCrashed:
2279 case eStateSuspended:
2280 process->m_last_stop_packet = response;
2281 process->m_last_stop_packet.SetFilePos (0);
2282 process->SetPrivateState (stop_state);
2283 break;
2284
2285 case eStateExited:
2286 process->m_last_stop_packet = response;
2287 process->m_last_stop_packet.SetFilePos (0);
2288 response.SetFilePos(1);
2289 process->SetExitStatus(response.GetHexU8(), NULL);
2290 done = true;
2291 break;
2292
2293 case eStateInvalid:
2294 break;
2295
2296 default:
2297 process->SetPrivateState (stop_state);
2298 break;
2299 }
2300 }
2301 }
2302 break;
2303
2304 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002305 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002306 if (log)
2307 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2308 done = true;
2309 break;
2310
2311 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002312 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002313 if (log)
2314 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2315 done = true;
2316 break;
2317 }
2318 }
2319 else
2320 {
Caroline Tice926060e2010-10-29 21:48:37 +00002321 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002322 if (log)
2323 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2324 done = true;
2325 }
2326 }
2327 }
2328
Caroline Tice926060e2010-10-29 21:48:37 +00002329 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002330 if (log)
2331 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2332
2333 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2334 return NULL;
2335}
2336
Chris Lattner24943d22010-06-08 16:52:24 +00002337const char *
2338ProcessGDBRemote::GetDispatchQueueNameForThread
2339(
2340 addr_t thread_dispatch_qaddr,
2341 std::string &dispatch_queue_name
2342)
2343{
2344 dispatch_queue_name.clear();
2345 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2346 {
2347 // Cache the dispatch_queue_offsets_addr value so we don't always have
2348 // to look it up
2349 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2350 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002351 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2352 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002353 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002354 if (module_sp)
2355 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2356
2357 if (dispatch_queue_offsets_symbol == NULL)
2358 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002359 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002360 if (module_sp)
2361 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2362 }
Chris Lattner24943d22010-06-08 16:52:24 +00002363 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002364 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002365
2366 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2367 return NULL;
2368 }
2369
2370 uint8_t memory_buffer[8];
2371 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2372
2373 // Excerpt from src/queue_private.h
2374 struct dispatch_queue_offsets_s
2375 {
2376 uint16_t dqo_version;
2377 uint16_t dqo_label;
2378 uint16_t dqo_label_size;
2379 } dispatch_queue_offsets;
2380
2381
2382 Error error;
2383 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2384 {
2385 uint32_t data_offset = 0;
2386 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2387 {
2388 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2389 {
2390 data_offset = 0;
2391 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2392 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2393 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2394 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2395 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2396 dispatch_queue_name.erase (bytes_read);
2397 }
2398 }
2399 }
2400 }
2401 if (dispatch_queue_name.empty())
2402 return NULL;
2403 return dispatch_queue_name.c_str();
2404}
2405
Jim Ingham7508e732010-08-09 23:31:02 +00002406uint32_t
2407ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2408{
2409 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2410 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2411 if (m_local_debugserver)
2412 {
2413 return Host::ListProcessesMatchingName (name, matches, pids);
2414 }
2415 else
2416 {
2417 // FIXME: Implement talking to the remote debugserver.
2418 return 0;
2419 }
2420
2421}
Jim Ingham55e01d82011-01-22 01:33:44 +00002422
2423bool
2424ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2425 lldb_private::StoppointCallbackContext *context,
2426 lldb::user_id_t break_id,
2427 lldb::user_id_t break_loc_id)
2428{
2429 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2430 // run so I can stop it if that's what I want to do.
2431 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2432 if (log)
2433 log->Printf("Hit New Thread Notification breakpoint.");
2434 return false;
2435}
2436
2437
2438bool
2439ProcessGDBRemote::StartNoticingNewThreads()
2440{
2441 static const char *bp_names[] =
2442 {
2443 "start_wqthread",
2444 "_pthread_start",
2445 NULL
2446 };
2447
2448 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2449 size_t num_bps = m_thread_observation_bps.size();
2450 if (num_bps != 0)
2451 {
2452 for (int i = 0; i < num_bps; i++)
2453 {
2454 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2455 if (break_sp)
2456 {
2457 if (log)
2458 log->Printf("Enabled noticing new thread breakpoint.");
2459 break_sp->SetEnabled(true);
2460 }
2461 }
2462 }
2463 else
2464 {
2465 for (int i = 0; bp_names[i] != NULL; i++)
2466 {
2467 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2468 if (breakpoint)
2469 {
2470 if (log)
2471 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2472 m_thread_observation_bps.push_back(breakpoint->GetID());
2473 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2474 }
2475 else
2476 {
2477 if (log)
2478 log->Printf("Failed to create new thread notification breakpoint.");
2479 return false;
2480 }
2481 }
2482 }
2483
2484 return true;
2485}
2486
2487bool
2488ProcessGDBRemote::StopNoticingNewThreads()
2489{
2490 size_t num_bps = m_thread_observation_bps.size();
2491 if (num_bps != 0)
2492 {
2493 for (int i = 0; i < num_bps; i++)
2494 {
2495 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2496
2497 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2498 if (break_sp)
2499 {
2500 if (log)
2501 log->Printf ("Disabling new thread notification breakpoint.");
2502 break_sp->SetEnabled(false);
2503 }
2504 }
2505 }
2506 return true;
2507}
2508
2509