blob: 2da0de9ac76acbc626a684dbf6ca7bbca3330601 [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
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000187ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000188{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000189 if (!force && m_register_info.GetNumRegisters() > 0)
190 return;
191
192 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000193 m_register_info.Clear();
194 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
195 uint32_t reg_offset = 0;
196 uint32_t reg_num = 0;
197 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
198 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000199 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
200 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000201 StringExtractorGDBRemote response;
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000202 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000203 {
204 packet_type = response.GetType();
205 if (packet_type == StringExtractorGDBRemote::eResponse)
206 {
207 std::string name;
208 std::string value;
209 ConstString reg_name;
210 ConstString alt_name;
211 ConstString set_name;
212 RegisterInfo reg_info = { NULL, // Name
213 NULL, // Alt name
214 0, // byte size
215 reg_offset, // offset
216 eEncodingUint, // encoding
217 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000218 {
219 LLDB_INVALID_REGNUM, // GCC reg num
220 LLDB_INVALID_REGNUM, // DWARF reg num
221 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000222 reg_num, // GDB reg num
223 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000224 }
225 };
226
227 while (response.GetNameColonValue(name, value))
228 {
229 if (name.compare("name") == 0)
230 {
231 reg_name.SetCString(value.c_str());
232 }
233 else if (name.compare("alt-name") == 0)
234 {
235 alt_name.SetCString(value.c_str());
236 }
237 else if (name.compare("bitsize") == 0)
238 {
239 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
240 }
241 else if (name.compare("offset") == 0)
242 {
243 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000244 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000245 {
246 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000247 }
248 }
249 else if (name.compare("encoding") == 0)
250 {
251 if (value.compare("uint") == 0)
252 reg_info.encoding = eEncodingUint;
253 else if (value.compare("sint") == 0)
254 reg_info.encoding = eEncodingSint;
255 else if (value.compare("ieee754") == 0)
256 reg_info.encoding = eEncodingIEEE754;
257 else if (value.compare("vector") == 0)
258 reg_info.encoding = eEncodingVector;
259 }
260 else if (name.compare("format") == 0)
261 {
262 if (value.compare("binary") == 0)
263 reg_info.format = eFormatBinary;
264 else if (value.compare("decimal") == 0)
265 reg_info.format = eFormatDecimal;
266 else if (value.compare("hex") == 0)
267 reg_info.format = eFormatHex;
268 else if (value.compare("float") == 0)
269 reg_info.format = eFormatFloat;
270 else if (value.compare("vector-sint8") == 0)
271 reg_info.format = eFormatVectorOfSInt8;
272 else if (value.compare("vector-uint8") == 0)
273 reg_info.format = eFormatVectorOfUInt8;
274 else if (value.compare("vector-sint16") == 0)
275 reg_info.format = eFormatVectorOfSInt16;
276 else if (value.compare("vector-uint16") == 0)
277 reg_info.format = eFormatVectorOfUInt16;
278 else if (value.compare("vector-sint32") == 0)
279 reg_info.format = eFormatVectorOfSInt32;
280 else if (value.compare("vector-uint32") == 0)
281 reg_info.format = eFormatVectorOfUInt32;
282 else if (value.compare("vector-float32") == 0)
283 reg_info.format = eFormatVectorOfFloat32;
284 else if (value.compare("vector-uint128") == 0)
285 reg_info.format = eFormatVectorOfUInt128;
286 }
287 else if (name.compare("set") == 0)
288 {
289 set_name.SetCString(value.c_str());
290 }
291 else if (name.compare("gcc") == 0)
292 {
293 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
294 }
295 else if (name.compare("dwarf") == 0)
296 {
297 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
298 }
299 else if (name.compare("generic") == 0)
300 {
301 if (value.compare("pc") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
303 else if (value.compare("sp") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
305 else if (value.compare("fp") == 0)
306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
307 else if (value.compare("ra") == 0)
308 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
309 else if (value.compare("flags") == 0)
310 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
311 }
312 }
313
Jason Molenda53d96862010-06-11 23:44:18 +0000314 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000315 assert (reg_info.byte_size != 0);
316 reg_offset += reg_info.byte_size;
317 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
318 }
319 }
320 else
321 {
322 packet_type = StringExtractorGDBRemote::eError;
323 }
324 }
325
326 if (reg_num == 0)
327 {
328 // We didn't get anything. See if we are debugging ARM and fill with
329 // a hard coded register set until we can get an updated debugserver
330 // down on the devices.
331 ArchSpec arm_arch ("arm");
332 if (GetTarget().GetArchitecture() == arm_arch)
333 m_register_info.HardcodeARMRegisters();
334 }
335 m_register_info.Finalize ();
336}
337
338Error
339ProcessGDBRemote::WillLaunch (Module* module)
340{
341 return WillLaunchOrAttach ();
342}
343
344Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000345ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000346{
347 return WillLaunchOrAttach ();
348}
349
350Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000351ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000352{
353 return WillLaunchOrAttach ();
354}
355
356Error
Greg Claytone71e2582011-02-04 01:58:07 +0000357ProcessGDBRemote::DoConnectRemote (const char *remote_url)
358{
359 Error error (WillLaunchOrAttach ());
360
361 if (error.Fail())
362 return error;
363
364 if (strncmp (remote_url, "connect://", strlen ("connect://")) == 0)
365 {
366 error = ConnectToDebugserver (remote_url);
367 }
368 else
369 {
370 error.SetErrorStringWithFormat ("unsupported remote url: %s", remote_url);
371 }
372
373 if (error.Fail())
374 return error;
375 StartAsyncThread ();
376
377 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (m_packet_timeout);
378 if (pid == LLDB_INVALID_PROCESS_ID)
379 {
380 // We don't have a valid process ID, so note that we are connected
381 // and could now request to launch or attach, or get remote process
382 // listings...
383 SetPrivateState (eStateConnected);
384 }
385 else
386 {
387 // We have a valid process
388 SetID (pid);
389 StringExtractorGDBRemote response;
390 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
391 {
392 const StateType state = SetThreadStopInfo (response);
393 if (state == eStateStopped)
394 {
395 SetPrivateState (state);
396 }
397 else
398 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
399 }
400 else
401 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
402 }
403 return error;
404}
405
406Error
Chris Lattner24943d22010-06-08 16:52:24 +0000407ProcessGDBRemote::WillLaunchOrAttach ()
408{
409 Error error;
410 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
411 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
412
413 if (m_dynamic_loader_ap.get() == NULL)
414 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
415 m_stdio_communication.Clear ();
416
417 return error;
418}
419
420//----------------------------------------------------------------------
421// Process Control
422//----------------------------------------------------------------------
423Error
424ProcessGDBRemote::DoLaunch
425(
426 Module* module,
427 char const *argv[],
428 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000429 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000430 const char *stdin_path,
431 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000432 const char *stderr_path,
433 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000434)
435{
Greg Clayton4b407112010-09-30 21:49:03 +0000436 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000437 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
438 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
439 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000440
441 ObjectFile * object_file = module->GetObjectFile();
442 if (object_file)
443 {
444 ArchSpec inferior_arch(module->GetArchitecture());
445 char host_port[128];
446 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000447 char connect_url[128];
448 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000449
Greg Clayton23cf0c72010-11-08 04:29:11 +0000450 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000451 bool start_debugserver_with_inferior_args = false;
452 if (start_debugserver_with_inferior_args)
453 {
454 // We want to launch debugserver with the inferior program and its
455 // arguments on the command line. We should only do this if we
456 // the GDB server we are talking to doesn't support the 'A' packet.
457 error = StartDebugserverProcess (host_port,
458 argv,
459 envp,
Greg Claytonde915be2011-01-23 05:56:20 +0000460 stdin_path,
461 stdout_path,
462 stderr_path,
463 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000464 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000465 LLDB_INVALID_PROCESS_ID,
466 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000467 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000468 inferior_arch);
469 if (error.Fail())
470 return error;
471
Greg Claytone71e2582011-02-04 01:58:07 +0000472 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000473 if (error.Success())
474 {
475 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
476 }
477 }
478 else
479 {
480 error = StartDebugserverProcess (host_port,
481 NULL,
482 NULL,
Greg Claytonde915be2011-01-23 05:56:20 +0000483 stdin_path,
484 stdout_path,
485 stderr_path,
486 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000487 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000488 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000489 NULL,
490 false,
Caroline Ticebd666012010-12-03 18:46:09 +0000491 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000492 inferior_arch);
493 if (error.Fail())
494 return error;
495
Greg Claytone71e2582011-02-04 01:58:07 +0000496 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000497 if (error.Success())
498 {
499 // Send the environment and the program + arguments after we connect
500 if (envp)
501 {
502 const char *env_entry;
503 for (int i=0; (env_entry = envp[i]); ++i)
504 {
505 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
506 break;
507 }
508 }
509
Greg Clayton960d6a42010-08-03 00:35:52 +0000510 // FIXME: convert this to use the new set/show variables when they are available
511#if 0
512 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
513 {
514 const uint32_t attach_debugserver_secs = 10;
515 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
516 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
517 {
518 printf ("%i\n", attach_debugserver_secs - i);
519 sleep (1);
520 }
521 }
522#endif
523
Chris Lattner24943d22010-06-08 16:52:24 +0000524 const uint32_t arg_timeout_seconds = 10;
525 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
526 if (arg_packet_err == 0)
527 {
528 std::string error_str;
529 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
530 {
531 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
532 }
533 else
534 {
535 error.SetErrorString (error_str.c_str());
536 }
537 }
538 else
539 {
540 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
541 }
542
543 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
544 }
545 }
546
547 if (GetID() == LLDB_INVALID_PROCESS_ID)
548 {
549 KillDebugserverProcess ();
550 return error;
551 }
552
553 StringExtractorGDBRemote response;
554 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
555 SetPrivateState (SetThreadStopInfo (response));
556
557 }
558 else
559 {
560 // Set our user ID to an invalid process ID.
561 SetID(LLDB_INVALID_PROCESS_ID);
562 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
563 }
Chris Lattner24943d22010-06-08 16:52:24 +0000564 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000565
Chris Lattner24943d22010-06-08 16:52:24 +0000566}
567
568
569Error
Greg Claytone71e2582011-02-04 01:58:07 +0000570ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000571{
572 Error error;
573 // Sleep and wait a bit for debugserver to start to listen...
574 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
575 if (conn_ap.get())
576 {
Chris Lattner24943d22010-06-08 16:52:24 +0000577 const uint32_t max_retry_count = 50;
578 uint32_t retry_count = 0;
579 while (!m_gdb_comm.IsConnected())
580 {
Greg Claytone71e2582011-02-04 01:58:07 +0000581 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000582 {
583 m_gdb_comm.SetConnection (conn_ap.release());
584 break;
585 }
586 retry_count++;
587
588 if (retry_count >= max_retry_count)
589 break;
590
591 usleep (100000);
592 }
593 }
594
595 if (!m_gdb_comm.IsConnected())
596 {
597 if (error.Success())
598 error.SetErrorString("not connected to remote gdb server");
599 return error;
600 }
601
602 m_gdb_comm.SetAckMode (true);
603 if (m_gdb_comm.StartReadThread(&error))
604 {
605 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000606 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000607
608 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000609 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
610 this,
611 m_debugserver_pid,
612 false);
613
Chris Lattner24943d22010-06-08 16:52:24 +0000614 StringExtractorGDBRemote response;
615 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false))
616 {
617 if (response.IsOKPacket())
618 m_gdb_comm.SetAckMode (false);
619 }
Greg Claytonc71899e2011-01-18 19:36:39 +0000620
621 if (m_gdb_comm.SendPacketAndWaitForResponse("QThreadSuffixSupported", response, 1, false))
622 {
623 if (response.IsOKPacket())
624 m_gdb_comm.SetThreadSuffixSupported (true);
625 }
626
Chris Lattner24943d22010-06-08 16:52:24 +0000627 }
628 return error;
629}
630
631void
632ProcessGDBRemote::DidLaunchOrAttach ()
633{
634 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()");
635 if (GetID() == LLDB_INVALID_PROCESS_ID)
636 {
637 m_dynamic_loader_ap.reset();
638 }
639 else
640 {
641 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
642
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000643 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000644
645 m_byte_order = m_gdb_comm.GetByteOrder();
646
Chris Lattner24943d22010-06-08 16:52:24 +0000647 StreamString strm;
648
Greg Claytone71e2582011-02-04 01:58:07 +0000649 ArchSpec inferior_arch (m_gdb_comm.GetHostArchitecture());
650
Chris Lattner24943d22010-06-08 16:52:24 +0000651 // See if the GDB server supports the qHostInfo information
652 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
653 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Claytone71e2582011-02-04 01:58:07 +0000654 const ArchSpec target_arch (GetTarget().GetArchitecture());
655 const ArchSpec arm_any("arm");
656 bool set_target_arch = true;
657 if (target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000658 {
Greg Claytone71e2582011-02-04 01:58:07 +0000659 if (inferior_arch == arm_any)
660 {
661 // For ARM we can't trust the arch of the process as it could
662 // have an armv6 object file, but be running on armv7 kernel.
663 // So we only set the ARM architecture if the target isn't set
664 // to ARM already...
665 if (target_arch == arm_any)
666 {
667 inferior_arch = target_arch;
668 set_target_arch = false;
669 }
670 }
Chris Lattner24943d22010-06-08 16:52:24 +0000671 }
Greg Claytone71e2582011-02-04 01:58:07 +0000672 if (set_target_arch)
673 GetTarget().SetArchitecture (inferior_arch);
Chris Lattner24943d22010-06-08 16:52:24 +0000674
675 if (vendor == NULL)
676 vendor = Host::GetVendorString().AsCString("apple");
677
678 if (os_type == NULL)
679 os_type = Host::GetOSString().AsCString("darwin");
680
681 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type);
682
683 std::transform (strm.GetString().begin(),
684 strm.GetString().end(),
685 strm.GetString().begin(),
686 ::tolower);
687
688 m_target_triple.SetCString(strm.GetString().c_str());
689 }
690}
691
692void
693ProcessGDBRemote::DidLaunch ()
694{
695 DidLaunchOrAttach ();
696 if (m_dynamic_loader_ap.get())
697 m_dynamic_loader_ap->DidLaunch();
698}
699
700Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000701ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000702{
703 Error error;
704 // Clear out and clean up from any current state
705 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000706 ArchSpec arch_spec = GetTarget().GetArchitecture();
707
Greg Claytone005f2c2010-11-06 01:53:30 +0000708 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Jim Ingham7508e732010-08-09 23:31:02 +0000709
710
Chris Lattner24943d22010-06-08 16:52:24 +0000711 if (attach_pid != LLDB_INVALID_PROCESS_ID)
712 {
Chris Lattner24943d22010-06-08 16:52:24 +0000713 char host_port[128];
714 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000715 char connect_url[128];
716 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
717
Greg Clayton452bf612010-08-31 18:35:14 +0000718 error = StartDebugserverProcess (host_port, // debugserver_url
719 NULL, // inferior_argv
720 NULL, // inferior_envp
721 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000722 NULL, // stdout_path
723 NULL, // stderr_path
724 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000725 false, // launch_process == false (we are attaching)
726 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
727 NULL, // Don't send any attach by process name option to debugserver
728 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000729 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000730 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000731
732 if (error.Fail())
733 {
734 const char *error_string = error.AsCString();
735 if (error_string == NULL)
736 error_string = "unable to launch " DEBUGSERVER_BASENAME;
737
738 SetExitStatus (-1, error_string);
739 }
740 else
741 {
Greg Claytone71e2582011-02-04 01:58:07 +0000742 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000743 if (error.Success())
744 {
745 char packet[64];
746 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000747
748 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000749 }
750 }
751 }
Chris Lattner24943d22010-06-08 16:52:24 +0000752 return error;
753}
754
755size_t
756ProcessGDBRemote::AttachInputReaderCallback
757(
758 void *baton,
759 InputReader *reader,
760 lldb::InputReaderAction notification,
761 const char *bytes,
762 size_t bytes_len
763)
764{
765 if (notification == eInputReaderGotToken)
766 {
767 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
768 if (gdb_process->m_waiting_for_attach)
769 gdb_process->m_waiting_for_attach = false;
770 reader->SetIsDone(true);
771 return 1;
772 }
773 return 0;
774}
775
776Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000777ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000778{
779 Error error;
780 // Clear out and clean up from any current state
781 Clear();
782 // HACK: require arch be set correctly at the target level until we can
783 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000784
Greg Claytone005f2c2010-11-06 01:53:30 +0000785 //LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000786 if (process_name && process_name[0])
787 {
Jim Ingham7508e732010-08-09 23:31:02 +0000788 ArchSpec arch_spec = GetTarget().GetArchitecture();
Greg Claytone71e2582011-02-04 01:58:07 +0000789
790 char host_port[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000791 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000792 char connect_url[128];
793 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
794
Greg Clayton452bf612010-08-31 18:35:14 +0000795 error = StartDebugserverProcess (host_port, // debugserver_url
796 NULL, // inferior_argv
797 NULL, // inferior_envp
798 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000799 NULL, // stdout_path
800 NULL, // stderr_path
801 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000802 false, // launch_process == false (we are attaching)
803 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
804 NULL, // Don't send any attach by process name option to debugserver
805 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000806 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000807 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000808 if (error.Fail())
809 {
810 const char *error_string = error.AsCString();
811 if (error_string == NULL)
812 error_string = "unable to launch " DEBUGSERVER_BASENAME;
813
814 SetExitStatus (-1, error_string);
815 }
816 else
817 {
Greg Claytone71e2582011-02-04 01:58:07 +0000818 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000819 if (error.Success())
820 {
821 StreamString packet;
822
Chris Lattner24943d22010-06-08 16:52:24 +0000823 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000824 packet.PutCString("vAttachWait");
825 else
826 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000827 packet.PutChar(';');
Greg Claytoncd548032011-02-01 01:31:41 +0000828 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000829
830 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
Chris Lattner24943d22010-06-08 16:52:24 +0000831
Chris Lattner24943d22010-06-08 16:52:24 +0000832 }
833 }
834 }
Chris Lattner24943d22010-06-08 16:52:24 +0000835 return error;
836}
837
Chris Lattner24943d22010-06-08 16:52:24 +0000838
839void
840ProcessGDBRemote::DidAttach ()
841{
Greg Claytone71e2582011-02-04 01:58:07 +0000842 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000843 if (m_dynamic_loader_ap.get())
844 m_dynamic_loader_ap->DidAttach();
845}
846
847Error
848ProcessGDBRemote::WillResume ()
849{
850 m_continue_packet.Clear();
851 // Start the continue packet we will use to run the target. Each thread
852 // will append what it is supposed to be doing to this packet when the
853 // ThreadList::WillResume() is called. If a thread it supposed
854 // to stay stopped, then don't append anything to this string.
855 m_continue_packet.Printf("vCont");
856 return Error();
857}
858
859Error
860ProcessGDBRemote::DoResume ()
861{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000862 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000863 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000864
865 Listener listener ("gdb-remote.resume-packet-sent");
866 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
867 {
868 EventSP event_sp;
869 TimeValue timeout;
870 timeout = TimeValue::Now();
871 timeout.OffsetWithSeconds (5);
872 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize()));
873
874 if (listener.WaitForEvent (&timeout, event_sp) == false)
875 error.SetErrorString("Resume timed out.");
876 }
877
Jim Ingham3ae449a2010-11-17 02:32:00 +0000878 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000879}
880
881size_t
882ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
883{
884 const uint8_t *trap_opcode = NULL;
885 uint32_t trap_opcode_size = 0;
886
887 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
888 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
889 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
890 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
891
Jim Ingham7508e732010-08-09 23:31:02 +0000892 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +0000893 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +0000894 {
Greg Claytoncf015052010-06-11 03:25:34 +0000895 case ArchSpec::eCPU_i386:
896 case ArchSpec::eCPU_x86_64:
897 trap_opcode = g_i386_breakpoint_opcode;
898 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
899 break;
900
901 case ArchSpec::eCPU_arm:
902 // TODO: fill this in for ARM. We need to dig up the symbol for
903 // the address in the breakpoint locaiton and figure out if it is
904 // an ARM or Thumb breakpoint.
905 trap_opcode = g_arm_breakpoint_opcode;
906 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
907 break;
908
909 case ArchSpec::eCPU_ppc:
910 case ArchSpec::eCPU_ppc64:
911 trap_opcode = g_ppc_breakpoint_opcode;
912 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
913 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000914
Greg Claytoncf015052010-06-11 03:25:34 +0000915 default:
916 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
917 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000918 }
919
920 if (trap_opcode && trap_opcode_size)
921 {
922 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
923 return trap_opcode_size;
924 }
925 return 0;
926}
927
928uint32_t
929ProcessGDBRemote::UpdateThreadListIfNeeded ()
930{
931 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +0000932 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +0000933 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +0000934 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
935
Greg Clayton5205f0b2010-09-03 17:10:42 +0000936 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +0000937 const uint32_t stop_id = GetStopID();
938 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
939 {
940 // Update the thread list's stop id immediately so we don't recurse into this function.
941 ThreadList curr_thread_list (this);
942 curr_thread_list.SetStopID(stop_id);
943
944 Error err;
945 StringExtractorGDBRemote response;
946 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
947 response.IsNormalPacket();
948 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
949 {
950 char ch = response.GetChar();
951 if (ch == 'l')
952 break;
953 if (ch == 'm')
954 {
955 do
956 {
957 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
958
959 if (tid != LLDB_INVALID_THREAD_ID)
960 {
961 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +0000962 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000963 thread_sp.reset (new ThreadGDBRemote (*this, tid));
964 curr_thread_list.AddThread(thread_sp);
965 }
966
967 ch = response.GetChar();
968 } while (ch == ',');
969 }
970 }
971
972 m_thread_list = curr_thread_list;
973
974 SetThreadStopInfo (m_last_stop_packet);
975 }
976 return GetThreadList().GetSize(false);
977}
978
979
980StateType
981ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
982{
983 const char stop_type = stop_packet.GetChar();
984 switch (stop_type)
985 {
986 case 'T':
987 case 'S':
988 {
989 // Stop with signal and thread info
990 const uint8_t signo = stop_packet.GetHexU8();
991 std::string name;
992 std::string value;
993 std::string thread_name;
994 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +0000995 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +0000996 uint32_t tid = LLDB_INVALID_THREAD_ID;
997 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
998 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +0000999 ThreadSP thread_sp;
1000
Chris Lattner24943d22010-06-08 16:52:24 +00001001 while (stop_packet.GetNameColonValue(name, value))
1002 {
1003 if (name.compare("metype") == 0)
1004 {
1005 // exception type in big endian hex
1006 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1007 }
1008 else if (name.compare("mecount") == 0)
1009 {
1010 // exception count in big endian hex
1011 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1012 }
1013 else if (name.compare("medata") == 0)
1014 {
1015 // exception data in big endian hex
1016 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1017 }
1018 else if (name.compare("thread") == 0)
1019 {
1020 // thread in big endian hex
1021 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytona875b642011-01-09 21:07:35 +00001022 thread_sp = m_thread_list.FindThreadByID(tid, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001023 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001024 else if (name.compare("hexname") == 0)
1025 {
1026 StringExtractor name_extractor;
1027 // Swap "value" over into "name_extractor"
1028 name_extractor.GetStringRef().swap(value);
1029 // Now convert the HEX bytes into a string value
1030 name_extractor.GetHexByteString (value);
1031 thread_name.swap (value);
1032 }
Chris Lattner24943d22010-06-08 16:52:24 +00001033 else if (name.compare("name") == 0)
1034 {
1035 thread_name.swap (value);
1036 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001037 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001038 {
1039 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1040 }
Greg Claytona875b642011-01-09 21:07:35 +00001041 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1042 {
1043 // We have a register number that contains an expedited
1044 // register value. Lets supply this register to our thread
1045 // so it won't have to go and read it.
1046 if (thread_sp)
1047 {
1048 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1049
1050 if (reg != UINT32_MAX)
1051 {
1052 StringExtractor reg_value_extractor;
1053 // Swap "value" over into "reg_value_extractor"
1054 reg_value_extractor.GetStringRef().swap(value);
1055 static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor);
1056 }
1057 }
1058 }
Chris Lattner24943d22010-06-08 16:52:24 +00001059 }
Chris Lattner24943d22010-06-08 16:52:24 +00001060
1061 if (thread_sp)
1062 {
1063 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1064
1065 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001066 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001067 if (exc_type != 0)
1068 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001069 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001070
1071 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1072 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001073 exc_data_size,
1074 exc_data_size >= 1 ? exc_data[0] : 0,
1075 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001076 }
1077 else if (signo)
1078 {
Greg Clayton643ee732010-08-04 01:40:35 +00001079 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001080 }
1081 else
1082 {
Greg Clayton643ee732010-08-04 01:40:35 +00001083 StopInfoSP invalid_stop_info_sp;
1084 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001085 }
1086 }
1087 return eStateStopped;
1088 }
1089 break;
1090
1091 case 'W':
1092 // process exited
1093 return eStateExited;
1094
1095 default:
1096 break;
1097 }
1098 return eStateInvalid;
1099}
1100
1101void
1102ProcessGDBRemote::RefreshStateAfterStop ()
1103{
Jim Ingham7508e732010-08-09 23:31:02 +00001104 // FIXME - add a variable to tell that we're in the middle of attaching if we
1105 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001106 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001107// if (!GetTarget().GetArchitecture().IsValid())
1108// {
1109// Module *exe_module = GetTarget().GetExecutableModule().get();
1110// if (exe_module)
1111// m_arch_spec = exe_module->GetArchitecture();
1112// }
1113
Chris Lattner24943d22010-06-08 16:52:24 +00001114 // Let all threads recover from stopping and do any clean up based
1115 // on the previous thread state (if any).
1116 m_thread_list.RefreshStateAfterStop();
1117
1118 // Discover new threads:
1119 UpdateThreadListIfNeeded ();
1120}
1121
1122Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001123ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001124{
1125 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001126
Greg Claytona4881d02011-01-22 07:12:45 +00001127 bool timed_out = false;
1128 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001129
1130 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001131 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001132 // We are being asked to halt during an attach. We need to just close
1133 // our file handle and debugserver will go away, and we can be done...
1134 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001135 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001136 else
1137 {
1138 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1139 {
1140 if (timed_out)
1141 error.SetErrorString("timed out sending interrupt packet");
1142 else
1143 error.SetErrorString("unknown error sending interrupt packet");
1144 }
1145 }
Chris Lattner24943d22010-06-08 16:52:24 +00001146 return error;
1147}
1148
1149Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001150ProcessGDBRemote::InterruptIfRunning
1151(
1152 bool discard_thread_plans,
1153 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001154 EventSP &stop_event_sp
1155)
Chris Lattner24943d22010-06-08 16:52:24 +00001156{
1157 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001158
Greg Clayton2860ba92011-01-23 19:58:49 +00001159 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1160
Greg Clayton68ca8232011-01-25 02:58:48 +00001161 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001162 const bool is_running = m_gdb_comm.IsRunning();
1163 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001164 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001165 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001166 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001167 is_running);
1168
Greg Clayton2860ba92011-01-23 19:58:49 +00001169 if (discard_thread_plans)
1170 {
1171 if (log)
1172 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1173 m_thread_list.DiscardThreadPlans();
1174 }
1175 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001176 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001177 if (catch_stop_event)
1178 {
1179 if (log)
1180 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1181 PausePrivateStateThread();
1182 paused_private_state_thread = true;
1183 }
1184
Greg Clayton4fb400f2010-09-27 21:07:38 +00001185 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001186 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001187 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001188
Greg Clayton72e1c782011-01-22 23:43:18 +00001189 //m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1190 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001191 {
1192 if (timed_out)
1193 error.SetErrorString("timed out sending interrupt packet");
1194 else
1195 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001196 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001197 ResumePrivateStateThread();
1198 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001199 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001200
Greg Clayton72e1c782011-01-22 23:43:18 +00001201 if (catch_stop_event)
1202 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001203 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001204 TimeValue timeout_time;
1205 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001206 timeout_time.OffsetWithSeconds(5);
1207 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001208
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001209 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001210 if (log)
1211 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001212
Greg Clayton2860ba92011-01-23 19:58:49 +00001213 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001214 error.SetErrorString("unable to verify target stopped");
1215 }
1216
Greg Clayton68ca8232011-01-25 02:58:48 +00001217 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001218 {
1219 if (log)
1220 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001221 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001222 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001223 }
Chris Lattner24943d22010-06-08 16:52:24 +00001224 return error;
1225}
1226
Greg Clayton4fb400f2010-09-27 21:07:38 +00001227Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001228ProcessGDBRemote::WillDetach ()
1229{
Greg Clayton2860ba92011-01-23 19:58:49 +00001230 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1231 if (log)
1232 log->Printf ("ProcessGDBRemote::WillDetach()");
1233
Greg Clayton72e1c782011-01-22 23:43:18 +00001234 bool discard_thread_plans = true;
1235 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001236 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001237 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001238}
1239
1240Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001241ProcessGDBRemote::DoDetach()
1242{
1243 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001244 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001245 if (log)
1246 log->Printf ("ProcessGDBRemote::DoDetach()");
1247
1248 DisableAllBreakpointSites ();
1249
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001250 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001251
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001252 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1253 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001254 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001255 if (response_size)
1256 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1257 else
1258 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001259 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001260 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001261 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001262
Greg Clayton4fb400f2010-09-27 21:07:38 +00001263 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001264 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001265
1266 SetPrivateState (eStateDetached);
1267 ResumePrivateStateThread();
1268
1269 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001270 return error;
1271}
Chris Lattner24943d22010-06-08 16:52:24 +00001272
1273Error
1274ProcessGDBRemote::DoDestroy ()
1275{
1276 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001277 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001278 if (log)
1279 log->Printf ("ProcessGDBRemote::DoDestroy()");
1280
1281 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001282 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001283 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001284 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001285 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001286 // We are being asked to halt during an attach. We need to just close
1287 // our file handle and debugserver will go away, and we can be done...
1288 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001289 }
1290 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001291 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001292
1293 StringExtractorGDBRemote response;
1294 bool send_async = true;
1295 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, 2, send_async))
1296 {
1297 char packet_cmd = response.GetChar(0);
1298
1299 if (packet_cmd == 'W' || packet_cmd == 'X')
1300 {
1301 m_last_stop_packet = response;
1302 SetExitStatus(response.GetHexU8(), NULL);
1303 }
1304 }
1305 else
1306 {
1307 SetExitStatus(SIGABRT, NULL);
1308 //error.SetErrorString("kill packet failed");
1309 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001310 }
1311 }
Chris Lattner24943d22010-06-08 16:52:24 +00001312 StopAsyncThread ();
1313 m_gdb_comm.StopReadThread();
1314 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001315 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001316 return error;
1317}
1318
Chris Lattner24943d22010-06-08 16:52:24 +00001319//------------------------------------------------------------------
1320// Process Queries
1321//------------------------------------------------------------------
1322
1323bool
1324ProcessGDBRemote::IsAlive ()
1325{
Greg Clayton58e844b2010-12-08 05:08:21 +00001326 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001327}
1328
1329addr_t
1330ProcessGDBRemote::GetImageInfoAddress()
1331{
1332 if (!m_gdb_comm.IsRunning())
1333 {
1334 StringExtractorGDBRemote response;
1335 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1336 {
1337 if (response.IsNormalPacket())
1338 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1339 }
1340 }
1341 return LLDB_INVALID_ADDRESS;
1342}
1343
1344DynamicLoader *
1345ProcessGDBRemote::GetDynamicLoader()
1346{
1347 return m_dynamic_loader_ap.get();
1348}
1349
1350//------------------------------------------------------------------
1351// Process Memory
1352//------------------------------------------------------------------
1353size_t
1354ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1355{
1356 if (size > m_max_memory_size)
1357 {
1358 // Keep memory read sizes down to a sane limit. This function will be
1359 // called multiple times in order to complete the task by
1360 // lldb_private::Process so it is ok to do this.
1361 size = m_max_memory_size;
1362 }
1363
1364 char packet[64];
1365 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1366 assert (packet_len + 1 < sizeof(packet));
1367 StringExtractorGDBRemote response;
1368 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1369 {
1370 if (response.IsNormalPacket())
1371 {
1372 error.Clear();
1373 return response.GetHexBytes(buf, size, '\xdd');
1374 }
1375 else if (response.IsErrorPacket())
1376 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1377 else if (response.IsUnsupportedPacket())
1378 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1379 else
1380 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1381 }
1382 else
1383 {
1384 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1385 }
1386 return 0;
1387}
1388
1389size_t
1390ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1391{
1392 StreamString packet;
1393 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001394 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001395 StringExtractorGDBRemote response;
1396 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1397 {
1398 if (response.IsOKPacket())
1399 {
1400 error.Clear();
1401 return size;
1402 }
1403 else if (response.IsErrorPacket())
1404 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1405 else if (response.IsUnsupportedPacket())
1406 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1407 else
1408 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1409 }
1410 else
1411 {
1412 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1413 }
1414 return 0;
1415}
1416
1417lldb::addr_t
1418ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1419{
1420 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1421 if (allocated_addr == LLDB_INVALID_ADDRESS)
1422 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1423 else
1424 error.Clear();
1425 return allocated_addr;
1426}
1427
1428Error
1429ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1430{
1431 Error error;
1432 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1433 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1434 return error;
1435}
1436
1437
1438//------------------------------------------------------------------
1439// Process STDIO
1440//------------------------------------------------------------------
1441
1442size_t
1443ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1444{
1445 Mutex::Locker locker(m_stdio_mutex);
1446 size_t bytes_available = m_stdout_data.size();
1447 if (bytes_available > 0)
1448 {
1449 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
1450 if (bytes_available > buf_size)
1451 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001452 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001453 m_stdout_data.erase(0, buf_size);
1454 bytes_available = buf_size;
1455 }
1456 else
1457 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001458 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001459 m_stdout_data.clear();
1460
1461 //ResetEventBits(eBroadcastBitSTDOUT);
1462 }
1463 }
1464 return bytes_available;
1465}
1466
1467size_t
1468ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1469{
1470 // Can we get STDERR through the remote protocol?
1471 return 0;
1472}
1473
1474size_t
1475ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1476{
1477 if (m_stdio_communication.IsConnected())
1478 {
1479 ConnectionStatus status;
1480 m_stdio_communication.Write(src, src_len, status, NULL);
1481 }
1482 return 0;
1483}
1484
1485Error
1486ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1487{
1488 Error error;
1489 assert (bp_site != NULL);
1490
Greg Claytone005f2c2010-11-06 01:53:30 +00001491 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001492 user_id_t site_id = bp_site->GetID();
1493 const addr_t addr = bp_site->GetLoadAddress();
1494 if (log)
1495 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1496
1497 if (bp_site->IsEnabled())
1498 {
1499 if (log)
1500 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1501 return error;
1502 }
1503 else
1504 {
1505 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1506
1507 if (bp_site->HardwarePreferred())
1508 {
1509 // Try and set hardware breakpoint, and if that fails, fall through
1510 // and set a software breakpoint?
1511 }
1512
1513 if (m_z0_supported)
1514 {
1515 char packet[64];
1516 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1517 assert (packet_len + 1 < sizeof(packet));
1518 StringExtractorGDBRemote response;
1519 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1520 {
1521 if (response.IsUnsupportedPacket())
1522 {
1523 // Disable z packet support and try again
1524 m_z0_supported = 0;
1525 return EnableBreakpoint (bp_site);
1526 }
1527 else if (response.IsOKPacket())
1528 {
1529 bp_site->SetEnabled(true);
1530 bp_site->SetType (BreakpointSite::eExternal);
1531 return error;
1532 }
1533 else
1534 {
1535 uint8_t error_byte = response.GetError();
1536 if (error_byte)
1537 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1538 }
1539 }
1540 }
1541 else
1542 {
1543 return EnableSoftwareBreakpoint (bp_site);
1544 }
1545 }
1546
1547 if (log)
1548 {
1549 const char *err_string = error.AsCString();
1550 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1551 bp_site->GetLoadAddress(),
1552 err_string ? err_string : "NULL");
1553 }
1554 // We shouldn't reach here on a successful breakpoint enable...
1555 if (error.Success())
1556 error.SetErrorToGenericError();
1557 return error;
1558}
1559
1560Error
1561ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1562{
1563 Error error;
1564 assert (bp_site != NULL);
1565 addr_t addr = bp_site->GetLoadAddress();
1566 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001567 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001568 if (log)
1569 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1570
1571 if (bp_site->IsEnabled())
1572 {
1573 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1574
1575 if (bp_site->IsHardware())
1576 {
1577 // TODO: disable hardware breakpoint...
1578 }
1579 else
1580 {
1581 if (m_z0_supported)
1582 {
1583 char packet[64];
1584 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1585 assert (packet_len + 1 < sizeof(packet));
1586 StringExtractorGDBRemote response;
1587 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1588 {
1589 if (response.IsUnsupportedPacket())
1590 {
1591 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1592 }
1593 else if (response.IsOKPacket())
1594 {
1595 if (log)
1596 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1597 bp_site->SetEnabled(false);
1598 return error;
1599 }
1600 else
1601 {
1602 uint8_t error_byte = response.GetError();
1603 if (error_byte)
1604 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1605 }
1606 }
1607 }
1608 else
1609 {
1610 return DisableSoftwareBreakpoint (bp_site);
1611 }
1612 }
1613 }
1614 else
1615 {
1616 if (log)
1617 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1618 return error;
1619 }
1620
1621 if (error.Success())
1622 error.SetErrorToGenericError();
1623 return error;
1624}
1625
1626Error
1627ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1628{
1629 Error error;
1630 if (wp)
1631 {
1632 user_id_t watchID = wp->GetID();
1633 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001634 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001635 if (log)
1636 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1637 if (wp->IsEnabled())
1638 {
1639 if (log)
1640 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1641 return error;
1642 }
1643 else
1644 {
1645 // Pass down an appropriate z/Z packet...
1646 error.SetErrorString("watchpoints not supported");
1647 }
1648 }
1649 else
1650 {
1651 error.SetErrorString("Watchpoint location argument was NULL.");
1652 }
1653 if (error.Success())
1654 error.SetErrorToGenericError();
1655 return error;
1656}
1657
1658Error
1659ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1660{
1661 Error error;
1662 if (wp)
1663 {
1664 user_id_t watchID = wp->GetID();
1665
Greg Claytone005f2c2010-11-06 01:53:30 +00001666 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001667
1668 addr_t addr = wp->GetLoadAddress();
1669 if (log)
1670 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1671
1672 if (wp->IsHardware())
1673 {
1674 // Pass down an appropriate z/Z packet...
1675 error.SetErrorString("watchpoints not supported");
1676 }
1677 // TODO: clear software watchpoints if we implement them
1678 }
1679 else
1680 {
1681 error.SetErrorString("Watchpoint location argument was NULL.");
1682 }
1683 if (error.Success())
1684 error.SetErrorToGenericError();
1685 return error;
1686}
1687
1688void
1689ProcessGDBRemote::Clear()
1690{
1691 m_flags = 0;
1692 m_thread_list.Clear();
1693 {
1694 Mutex::Locker locker(m_stdio_mutex);
1695 m_stdout_data.clear();
1696 }
Chris Lattner24943d22010-06-08 16:52:24 +00001697}
1698
1699Error
1700ProcessGDBRemote::DoSignal (int signo)
1701{
1702 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001703 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001704 if (log)
1705 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1706
1707 if (!m_gdb_comm.SendAsyncSignal (signo))
1708 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1709 return error;
1710}
1711
Caroline Tice861efb32010-11-16 05:07:41 +00001712//void
1713//ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1714//{
1715// ProcessGDBRemote *process = (ProcessGDBRemote *)baton;
1716// process->AppendSTDOUT(static_cast<const char *>(src), src_len);
1717//}
Chris Lattner24943d22010-06-08 16:52:24 +00001718
Caroline Tice861efb32010-11-16 05:07:41 +00001719//void
1720//ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len)
1721//{
1722// ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s);
1723// Mutex::Locker locker(m_stdio_mutex);
1724// m_stdout_data.append(s, len);
1725//
1726// // FIXME: Make a real data object for this and put it out.
1727// BroadcastEventIfUnique (eBroadcastBitSTDOUT);
1728//}
Chris Lattner24943d22010-06-08 16:52:24 +00001729
1730
1731Error
1732ProcessGDBRemote::StartDebugserverProcess
1733(
1734 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1735 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1736 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Claytonde915be2011-01-23 05:56:20 +00001737 const char *stdin_path,
1738 const char *stdout_path,
1739 const char *stderr_path,
1740 const char *working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001741 bool launch_process, // Set to true if we are going to be launching a the process
1742 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 +00001743 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1744 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001745 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001746 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1747)
1748{
1749 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001750 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1751 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001752 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1753 {
1754 // If we locate debugserver, keep that located version around
1755 static FileSpec g_debugserver_file_spec;
1756
1757 FileSpec debugserver_file_spec;
1758 char debugserver_path[PATH_MAX];
1759
1760 // Always check to see if we have an environment override for the path
1761 // to the debugserver to use and use it if we do.
1762 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1763 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001764 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001765 else
1766 debugserver_file_spec = g_debugserver_file_spec;
1767 bool debugserver_exists = debugserver_file_spec.Exists();
1768 if (!debugserver_exists)
1769 {
1770 // The debugserver binary is in the LLDB.framework/Resources
1771 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001772 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001773 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001774 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001775 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001776 if (debugserver_exists)
1777 {
1778 g_debugserver_file_spec = debugserver_file_spec;
1779 }
1780 else
1781 {
1782 g_debugserver_file_spec.Clear();
1783 debugserver_file_spec.Clear();
1784 }
Chris Lattner24943d22010-06-08 16:52:24 +00001785 }
1786 }
1787
1788 if (debugserver_exists)
1789 {
1790 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1791
1792 m_stdio_communication.Clear();
1793 posix_spawnattr_t attr;
1794
Greg Claytone005f2c2010-11-06 01:53:30 +00001795 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001796
1797 Error local_err; // Errors that don't affect the spawning.
1798 if (log)
1799 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1800 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1801 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001802 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001803 if (error.Fail())
1804 return error;;
1805
1806#if !defined (__arm__)
1807
Greg Clayton24b48ff2010-10-17 22:03:32 +00001808 // We don't need to do this for ARM, and we really shouldn't now
1809 // that we have multiple CPU subtypes and no posix_spawnattr call
1810 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001811 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001812 {
Greg Claytoncf015052010-06-11 03:25:34 +00001813 cpu_type_t cpu = inferior_arch.GetCPUType();
1814 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1815 {
1816 size_t ocount = 0;
1817 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1818 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001819 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 +00001820
Greg Claytoncf015052010-06-11 03:25:34 +00001821 if (error.Fail() != 0 || ocount != 1)
1822 return error;
1823 }
Chris Lattner24943d22010-06-08 16:52:24 +00001824 }
1825
1826#endif
1827
1828 Args debugserver_args;
1829 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001830
Chris Lattner24943d22010-06-08 16:52:24 +00001831 lldb_utility::PseudoTerminal pty;
Greg Claytonde915be2011-01-23 05:56:20 +00001832 const char *stdio_path = NULL;
1833 if (launch_process &&
Caroline Ticee4450f02011-01-28 00:19:58 +00001834 (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) &&
Greg Claytonde915be2011-01-23 05:56:20 +00001835 m_local_debugserver &&
1836 no_stdio == false)
Chris Lattner24943d22010-06-08 16:52:24 +00001837 {
Chris Lattner24943d22010-06-08 16:52:24 +00001838 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Caroline Ticee4450f02011-01-28 00:19:58 +00001839 {
1840 const char *slave_name = pty.GetSlaveName (NULL, 0);
1841 if (stdin_path == NULL
1842 && stdout_path == NULL
1843 && stderr_path == NULL)
1844 stdio_path = slave_name;
1845 else
1846 {
1847 if (stdin_path == NULL)
1848 stdin_path = slave_name;
1849 if (stdout_path == NULL)
1850 stdout_path = slave_name;
1851 if (stderr_path == NULL)
1852 stderr_path = slave_name;
1853 }
1854 }
Chris Lattner24943d22010-06-08 16:52:24 +00001855 }
1856
1857 // Start args with "debugserver /file/path -r --"
1858 debugserver_args.AppendArgument(debugserver_path);
1859 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001860 // use native registers, not the GDB registers
1861 debugserver_args.AppendArgument("--native-regs");
1862 // make debugserver run in its own session so signals generated by
1863 // special terminal key sequences (^C) don't affect debugserver
1864 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001865
Greg Clayton452bf612010-08-31 18:35:14 +00001866 if (disable_aslr)
1867 debugserver_args.AppendArguments("--disable-aslr");
1868
Chris Lattner24943d22010-06-08 16:52:24 +00001869 // Only set the inferior
Greg Claytonde915be2011-01-23 05:56:20 +00001870 if (launch_process)
Chris Lattner24943d22010-06-08 16:52:24 +00001871 {
Greg Claytonde915be2011-01-23 05:56:20 +00001872 if (no_stdio)
1873 debugserver_args.AppendArgument("--no-stdio");
1874 else
1875 {
1876 if (stdin_path && stdout_path && stderr_path &&
1877 strcmp(stdin_path, stdout_path) == 0 &&
1878 strcmp(stdin_path, stderr_path) == 0)
1879 {
1880 stdio_path = stdin_path;
1881 stdin_path = stdout_path = stderr_path = NULL;
1882 }
1883
1884 if (stdio_path)
1885 {
1886 // All file handles to stdin, stdout, stderr are the same...
1887 debugserver_args.AppendArgument("--stdio-path");
1888 debugserver_args.AppendArgument(stdio_path);
1889 }
1890 else
1891 {
1892 if (stdin_path == NULL && (stdout_path || stderr_path))
1893 stdin_path = "/dev/null";
1894
1895 if (stdout_path == NULL && (stdin_path || stderr_path))
1896 stdout_path = "/dev/null";
1897
1898 if (stderr_path == NULL && (stdin_path || stdout_path))
1899 stderr_path = "/dev/null";
1900
1901 if (stdin_path)
1902 {
1903 debugserver_args.AppendArgument("--stdin-path");
1904 debugserver_args.AppendArgument(stdin_path);
1905 }
1906 if (stdout_path)
1907 {
1908 debugserver_args.AppendArgument("--stdout-path");
1909 debugserver_args.AppendArgument(stdout_path);
1910 }
1911 if (stderr_path)
1912 {
1913 debugserver_args.AppendArgument("--stderr-path");
1914 debugserver_args.AppendArgument(stderr_path);
1915 }
1916 }
1917 }
Chris Lattner24943d22010-06-08 16:52:24 +00001918 }
Greg Claytonde915be2011-01-23 05:56:20 +00001919
1920 if (working_dir)
Caroline Ticebd666012010-12-03 18:46:09 +00001921 {
Greg Claytonde915be2011-01-23 05:56:20 +00001922 debugserver_args.AppendArgument("--working-dir");
1923 debugserver_args.AppendArgument(working_dir);
Caroline Ticebd666012010-12-03 18:46:09 +00001924 }
Chris Lattner24943d22010-06-08 16:52:24 +00001925
1926 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1927 if (env_debugserver_log_file)
1928 {
1929 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1930 debugserver_args.AppendArgument(arg_cstr);
1931 }
1932
1933 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1934 if (env_debugserver_log_flags)
1935 {
1936 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1937 debugserver_args.AppendArgument(arg_cstr);
1938 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001939// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001940// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00001941
1942 // Now append the program arguments
1943 if (launch_process)
1944 {
1945 if (inferior_argv)
1946 {
1947 // Terminate the debugserver args so we can now append the inferior args
1948 debugserver_args.AppendArgument("--");
1949
1950 for (int i = 0; inferior_argv[i] != NULL; ++i)
1951 debugserver_args.AppendArgument (inferior_argv[i]);
1952 }
1953 else
1954 {
1955 // Will send environment entries with the 'QEnvironment:' packet
1956 // Will send arguments with the 'A' packet
1957 }
1958 }
1959 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1960 {
1961 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
1962 debugserver_args.AppendArgument (arg_cstr);
1963 }
1964 else if (attach_name && attach_name[0])
1965 {
1966 if (wait_for_launch)
1967 debugserver_args.AppendArgument ("--waitfor");
1968 else
1969 debugserver_args.AppendArgument ("--attach");
1970 debugserver_args.AppendArgument (attach_name);
1971 }
1972
1973 Error file_actions_err;
1974 posix_spawn_file_actions_t file_actions;
1975#if DONT_CLOSE_DEBUGSERVER_STDIO
1976 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
1977#else
1978 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1979 if (file_actions_err.Success())
1980 {
1981 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
1982 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
1983 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
1984 }
1985#endif
1986
1987 if (log)
1988 {
1989 StreamString strm;
1990 debugserver_args.Dump (&strm);
1991 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
1992 }
1993
Greg Clayton72e1c782011-01-22 23:43:18 +00001994 error.SetError (::posix_spawnp (&m_debugserver_pid,
1995 debugserver_path,
1996 file_actions_err.Success() ? &file_actions : NULL,
1997 &attr,
1998 debugserver_args.GetArgumentVector(),
1999 (char * const*)inferior_envp),
2000 eErrorTypePOSIX);
2001
Greg Claytone9d0df42010-07-02 01:29:13 +00002002
2003 ::posix_spawnattr_destroy (&attr);
2004
Chris Lattner24943d22010-06-08 16:52:24 +00002005 if (file_actions_err.Success())
2006 ::posix_spawn_file_actions_destroy (&file_actions);
2007
2008 // We have seen some cases where posix_spawnp was returning a valid
2009 // looking pid even when an error was returned, so clear it out
2010 if (error.Fail())
2011 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2012
2013 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002014 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 +00002015
Caroline Ticebd666012010-12-03 18:46:09 +00002016 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00002017 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00002018 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00002019 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00002020 }
Chris Lattner24943d22010-06-08 16:52:24 +00002021 }
2022 else
2023 {
2024 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2025 }
2026
2027 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2028 StartAsyncThread ();
2029 }
2030 return error;
2031}
2032
2033bool
2034ProcessGDBRemote::MonitorDebugserverProcess
2035(
2036 void *callback_baton,
2037 lldb::pid_t debugserver_pid,
2038 int signo, // Zero for no signal
2039 int exit_status // Exit value of process if signal is zero
2040)
2041{
2042 // We pass in the ProcessGDBRemote inferior process it and name it
2043 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2044 // pointer value itself, thus we need the double cast...
2045
2046 // "debugserver_pid" argument passed in is the process ID for
2047 // debugserver that we are tracking...
2048
Greg Clayton75ccf502010-08-21 02:22:51 +00002049 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002050
2051 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2052 if (log)
2053 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2054
Greg Clayton75ccf502010-08-21 02:22:51 +00002055 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002056 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002057 // Sleep for a half a second to make sure our inferior process has
2058 // time to set its exit status before we set it incorrectly when
2059 // both the debugserver and the inferior process shut down.
2060 usleep (500000);
2061 // If our process hasn't yet exited, debugserver might have died.
2062 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002063 const StateType state = process->GetState();
2064
2065 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2066 state != eStateInvalid &&
2067 state != eStateUnloaded &&
2068 state != eStateExited &&
2069 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002070 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002071 char error_str[1024];
2072 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002073 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002074 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2075 if (signal_cstr)
2076 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002077 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002078 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002079 }
2080 else
2081 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002082 ::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 +00002083 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002084
2085 process->SetExitStatus (-1, error_str);
2086 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002087 // Debugserver has exited we need to let our ProcessGDBRemote
2088 // know that it no longer has a debugserver instance
2089 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2090 // We are returning true to this function below, so we can
2091 // forget about the monitor handle.
2092 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002093 }
2094 return true;
2095}
2096
2097void
2098ProcessGDBRemote::KillDebugserverProcess ()
2099{
2100 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2101 {
2102 ::kill (m_debugserver_pid, SIGINT);
2103 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2104 }
2105}
2106
2107void
2108ProcessGDBRemote::Initialize()
2109{
2110 static bool g_initialized = false;
2111
2112 if (g_initialized == false)
2113 {
2114 g_initialized = true;
2115 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2116 GetPluginDescriptionStatic(),
2117 CreateInstance);
2118
2119 Log::Callbacks log_callbacks = {
2120 ProcessGDBRemoteLog::DisableLog,
2121 ProcessGDBRemoteLog::EnableLog,
2122 ProcessGDBRemoteLog::ListLogCategories
2123 };
2124
2125 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2126 }
2127}
2128
2129bool
2130ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2131{
2132 if (m_curr_tid == tid)
2133 return true;
2134
2135 char packet[32];
2136 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
2137 assert (packet_len + 1 < sizeof(packet));
2138 StringExtractorGDBRemote response;
2139 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2140 {
2141 if (response.IsOKPacket())
2142 {
2143 m_curr_tid = tid;
2144 return true;
2145 }
2146 }
2147 return false;
2148}
2149
2150bool
2151ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2152{
2153 if (m_curr_tid_run == tid)
2154 return true;
2155
2156 char packet[32];
Greg Claytonc71899e2011-01-18 19:36:39 +00002157 const int packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002158 assert (packet_len + 1 < sizeof(packet));
2159 StringExtractorGDBRemote response;
2160 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2161 {
2162 if (response.IsOKPacket())
2163 {
2164 m_curr_tid_run = tid;
2165 return true;
2166 }
2167 }
2168 return false;
2169}
2170
2171void
2172ProcessGDBRemote::ResetGDBRemoteState ()
2173{
2174 // Reset and GDB remote state
2175 m_curr_tid = LLDB_INVALID_THREAD_ID;
2176 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2177 m_z0_supported = 1;
2178}
2179
2180
2181bool
2182ProcessGDBRemote::StartAsyncThread ()
2183{
2184 ResetGDBRemoteState ();
2185
Greg Claytone005f2c2010-11-06 01:53:30 +00002186 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002187
2188 if (log)
2189 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2190
2191 // Create a thread that watches our internal state and controls which
2192 // events make it to clients (into the DCProcess event queue).
2193 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2194 return m_async_thread != LLDB_INVALID_HOST_THREAD;
2195}
2196
2197void
2198ProcessGDBRemote::StopAsyncThread ()
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 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2206
2207 // Stop the stdio thread
2208 if (m_async_thread != LLDB_INVALID_HOST_THREAD)
2209 {
2210 Host::ThreadJoin (m_async_thread, NULL, NULL);
2211 }
2212}
2213
2214
2215void *
2216ProcessGDBRemote::AsyncThread (void *arg)
2217{
2218 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2219
Greg Claytone005f2c2010-11-06 01:53:30 +00002220 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002221 if (log)
2222 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2223
2224 Listener listener ("ProcessGDBRemote::AsyncThread");
2225 EventSP event_sp;
2226 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2227 eBroadcastBitAsyncThreadShouldExit;
2228
2229 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2230 {
2231 bool done = false;
2232 while (!done)
2233 {
Caroline Tice926060e2010-10-29 21:48:37 +00002234 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) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2237 if (listener.WaitForEvent (NULL, event_sp))
2238 {
2239 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002240 if (log)
2241 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2242
Chris Lattner24943d22010-06-08 16:52:24 +00002243 switch (event_type)
2244 {
2245 case eBroadcastBitAsyncContinue:
2246 {
2247 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2248
2249 if (continue_packet)
2250 {
2251 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2252 const size_t continue_cstr_len = continue_packet->GetByteSize ();
Caroline Tice926060e2010-10-29 21:48:37 +00002253 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002254 if (log)
2255 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2256
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002257 if (::strstr (continue_cstr, "vAttach") == NULL)
2258 process->SetPrivateState(eStateRunning);
Chris Lattner24943d22010-06-08 16:52:24 +00002259 StringExtractorGDBRemote response;
2260 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2261
2262 switch (stop_state)
2263 {
2264 case eStateStopped:
2265 case eStateCrashed:
2266 case eStateSuspended:
2267 process->m_last_stop_packet = response;
2268 process->m_last_stop_packet.SetFilePos (0);
2269 process->SetPrivateState (stop_state);
2270 break;
2271
2272 case eStateExited:
2273 process->m_last_stop_packet = response;
2274 process->m_last_stop_packet.SetFilePos (0);
2275 response.SetFilePos(1);
2276 process->SetExitStatus(response.GetHexU8(), NULL);
2277 done = true;
2278 break;
2279
2280 case eStateInvalid:
2281 break;
2282
2283 default:
2284 process->SetPrivateState (stop_state);
2285 break;
2286 }
2287 }
2288 }
2289 break;
2290
2291 case eBroadcastBitAsyncThreadShouldExit:
Caroline Tice926060e2010-10-29 21:48:37 +00002292 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002293 if (log)
2294 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2295 done = true;
2296 break;
2297
2298 default:
Caroline Tice926060e2010-10-29 21:48:37 +00002299 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002300 if (log)
2301 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2302 done = true;
2303 break;
2304 }
2305 }
2306 else
2307 {
Caroline Tice926060e2010-10-29 21:48:37 +00002308 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002309 if (log)
2310 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2311 done = true;
2312 }
2313 }
2314 }
2315
Caroline Tice926060e2010-10-29 21:48:37 +00002316 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002317 if (log)
2318 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2319
2320 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2321 return NULL;
2322}
2323
Chris Lattner24943d22010-06-08 16:52:24 +00002324const char *
2325ProcessGDBRemote::GetDispatchQueueNameForThread
2326(
2327 addr_t thread_dispatch_qaddr,
2328 std::string &dispatch_queue_name
2329)
2330{
2331 dispatch_queue_name.clear();
2332 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2333 {
2334 // Cache the dispatch_queue_offsets_addr value so we don't always have
2335 // to look it up
2336 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2337 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002338 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2339 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002340 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002341 if (module_sp)
2342 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2343
2344 if (dispatch_queue_offsets_symbol == NULL)
2345 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002346 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002347 if (module_sp)
2348 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2349 }
Chris Lattner24943d22010-06-08 16:52:24 +00002350 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002351 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002352
2353 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2354 return NULL;
2355 }
2356
2357 uint8_t memory_buffer[8];
2358 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2359
2360 // Excerpt from src/queue_private.h
2361 struct dispatch_queue_offsets_s
2362 {
2363 uint16_t dqo_version;
2364 uint16_t dqo_label;
2365 uint16_t dqo_label_size;
2366 } dispatch_queue_offsets;
2367
2368
2369 Error error;
2370 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2371 {
2372 uint32_t data_offset = 0;
2373 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2374 {
2375 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2376 {
2377 data_offset = 0;
2378 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2379 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2380 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2381 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2382 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2383 dispatch_queue_name.erase (bytes_read);
2384 }
2385 }
2386 }
2387 }
2388 if (dispatch_queue_name.empty())
2389 return NULL;
2390 return dispatch_queue_name.c_str();
2391}
2392
Jim Ingham7508e732010-08-09 23:31:02 +00002393uint32_t
2394ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2395{
2396 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2397 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2398 if (m_local_debugserver)
2399 {
2400 return Host::ListProcessesMatchingName (name, matches, pids);
2401 }
2402 else
2403 {
2404 // FIXME: Implement talking to the remote debugserver.
2405 return 0;
2406 }
2407
2408}
Jim Ingham55e01d82011-01-22 01:33:44 +00002409
2410bool
2411ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2412 lldb_private::StoppointCallbackContext *context,
2413 lldb::user_id_t break_id,
2414 lldb::user_id_t break_loc_id)
2415{
2416 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2417 // run so I can stop it if that's what I want to do.
2418 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2419 if (log)
2420 log->Printf("Hit New Thread Notification breakpoint.");
2421 return false;
2422}
2423
2424
2425bool
2426ProcessGDBRemote::StartNoticingNewThreads()
2427{
2428 static const char *bp_names[] =
2429 {
2430 "start_wqthread",
2431 "_pthread_start",
2432 NULL
2433 };
2434
2435 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2436 size_t num_bps = m_thread_observation_bps.size();
2437 if (num_bps != 0)
2438 {
2439 for (int i = 0; i < num_bps; i++)
2440 {
2441 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2442 if (break_sp)
2443 {
2444 if (log)
2445 log->Printf("Enabled noticing new thread breakpoint.");
2446 break_sp->SetEnabled(true);
2447 }
2448 }
2449 }
2450 else
2451 {
2452 for (int i = 0; bp_names[i] != NULL; i++)
2453 {
2454 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2455 if (breakpoint)
2456 {
2457 if (log)
2458 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2459 m_thread_observation_bps.push_back(breakpoint->GetID());
2460 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2461 }
2462 else
2463 {
2464 if (log)
2465 log->Printf("Failed to create new thread notification breakpoint.");
2466 return false;
2467 }
2468 }
2469 }
2470
2471 return true;
2472}
2473
2474bool
2475ProcessGDBRemote::StopNoticingNewThreads()
2476{
2477 size_t num_bps = m_thread_observation_bps.size();
2478 if (num_bps != 0)
2479 {
2480 for (int i = 0; i < num_bps; i++)
2481 {
2482 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2483
2484 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2485 if (break_sp)
2486 {
2487 if (log)
2488 log->Printf ("Disabling new thread notification breakpoint.");
2489 break_sp->SetEnabled(false);
2490 }
2491 }
2492 }
2493 return true;
2494}
2495
2496