blob: cba0ca162fe3cae37999df4538790a3997008da0 [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"
Greg Clayton5f54ac32011-02-08 05:05:52 +000027#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#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),
Greg Claytonc1f45872011-02-12 06:28:37 +0000117 m_continue_c_tids (),
118 m_continue_C_tids (),
119 m_continue_s_tids (),
120 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000121 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000122 m_packet_timeout (1),
123 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000124 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000125 m_local_debugserver (true),
126 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000127{
128}
129
130//----------------------------------------------------------------------
131// Destructor
132//----------------------------------------------------------------------
133ProcessGDBRemote::~ProcessGDBRemote()
134{
Greg Claytonff5cac22010-12-13 18:11:18 +0000135 m_dynamic_loader_ap.reset();
136
Greg Clayton09c81ef2011-02-08 01:34:25 +0000137 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000138 {
139 Host::ThreadCancel (m_debugserver_thread, NULL);
140 thread_result_t thread_result;
141 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
142 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
143 }
Chris Lattner24943d22010-06-08 16:52:24 +0000144 // m_mach_process.UnregisterNotificationCallbacks (this);
145 Clear();
146}
147
148//----------------------------------------------------------------------
149// PluginInterface
150//----------------------------------------------------------------------
151const char *
152ProcessGDBRemote::GetPluginName()
153{
154 return "Process debugging plug-in that uses the GDB remote protocol";
155}
156
157const char *
158ProcessGDBRemote::GetShortPluginName()
159{
160 return GetPluginNameStatic();
161}
162
163uint32_t
164ProcessGDBRemote::GetPluginVersion()
165{
166 return 1;
167}
168
169void
170ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
171{
172 strm->Printf("TODO: fill this in\n");
173}
174
175Error
176ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
177{
178 Error error;
179 error.SetErrorString("No plug-in commands are currently supported.");
180 return error;
181}
182
183Log *
184ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
185{
186 return NULL;
187}
188
189void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000190ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000191{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000192 if (!force && m_register_info.GetNumRegisters() > 0)
193 return;
194
195 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000196 m_register_info.Clear();
197 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
198 uint32_t reg_offset = 0;
199 uint32_t reg_num = 0;
200 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
201 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000202 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
203 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000204 StringExtractorGDBRemote response;
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000205 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000206 {
207 packet_type = response.GetType();
208 if (packet_type == StringExtractorGDBRemote::eResponse)
209 {
210 std::string name;
211 std::string value;
212 ConstString reg_name;
213 ConstString alt_name;
214 ConstString set_name;
215 RegisterInfo reg_info = { NULL, // Name
216 NULL, // Alt name
217 0, // byte size
218 reg_offset, // offset
219 eEncodingUint, // encoding
220 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000221 {
222 LLDB_INVALID_REGNUM, // GCC reg num
223 LLDB_INVALID_REGNUM, // DWARF reg num
224 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000225 reg_num, // GDB reg num
226 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000227 }
228 };
229
230 while (response.GetNameColonValue(name, value))
231 {
232 if (name.compare("name") == 0)
233 {
234 reg_name.SetCString(value.c_str());
235 }
236 else if (name.compare("alt-name") == 0)
237 {
238 alt_name.SetCString(value.c_str());
239 }
240 else if (name.compare("bitsize") == 0)
241 {
242 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
243 }
244 else if (name.compare("offset") == 0)
245 {
246 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000247 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000248 {
249 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000250 }
251 }
252 else if (name.compare("encoding") == 0)
253 {
254 if (value.compare("uint") == 0)
255 reg_info.encoding = eEncodingUint;
256 else if (value.compare("sint") == 0)
257 reg_info.encoding = eEncodingSint;
258 else if (value.compare("ieee754") == 0)
259 reg_info.encoding = eEncodingIEEE754;
260 else if (value.compare("vector") == 0)
261 reg_info.encoding = eEncodingVector;
262 }
263 else if (name.compare("format") == 0)
264 {
265 if (value.compare("binary") == 0)
266 reg_info.format = eFormatBinary;
267 else if (value.compare("decimal") == 0)
268 reg_info.format = eFormatDecimal;
269 else if (value.compare("hex") == 0)
270 reg_info.format = eFormatHex;
271 else if (value.compare("float") == 0)
272 reg_info.format = eFormatFloat;
273 else if (value.compare("vector-sint8") == 0)
274 reg_info.format = eFormatVectorOfSInt8;
275 else if (value.compare("vector-uint8") == 0)
276 reg_info.format = eFormatVectorOfUInt8;
277 else if (value.compare("vector-sint16") == 0)
278 reg_info.format = eFormatVectorOfSInt16;
279 else if (value.compare("vector-uint16") == 0)
280 reg_info.format = eFormatVectorOfUInt16;
281 else if (value.compare("vector-sint32") == 0)
282 reg_info.format = eFormatVectorOfSInt32;
283 else if (value.compare("vector-uint32") == 0)
284 reg_info.format = eFormatVectorOfUInt32;
285 else if (value.compare("vector-float32") == 0)
286 reg_info.format = eFormatVectorOfFloat32;
287 else if (value.compare("vector-uint128") == 0)
288 reg_info.format = eFormatVectorOfUInt128;
289 }
290 else if (name.compare("set") == 0)
291 {
292 set_name.SetCString(value.c_str());
293 }
294 else if (name.compare("gcc") == 0)
295 {
296 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
297 }
298 else if (name.compare("dwarf") == 0)
299 {
300 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
301 }
302 else if (name.compare("generic") == 0)
303 {
304 if (value.compare("pc") == 0)
305 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
306 else if (value.compare("sp") == 0)
307 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
308 else if (value.compare("fp") == 0)
309 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
310 else if (value.compare("ra") == 0)
311 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
312 else if (value.compare("flags") == 0)
313 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
314 }
315 }
316
Jason Molenda53d96862010-06-11 23:44:18 +0000317 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000318 assert (reg_info.byte_size != 0);
319 reg_offset += reg_info.byte_size;
320 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
321 }
322 }
323 else
324 {
325 packet_type = StringExtractorGDBRemote::eError;
326 }
327 }
328
329 if (reg_num == 0)
330 {
331 // We didn't get anything. See if we are debugging ARM and fill with
332 // a hard coded register set until we can get an updated debugserver
333 // down on the devices.
334 ArchSpec arm_arch ("arm");
335 if (GetTarget().GetArchitecture() == arm_arch)
336 m_register_info.HardcodeARMRegisters();
337 }
338 m_register_info.Finalize ();
339}
340
341Error
342ProcessGDBRemote::WillLaunch (Module* module)
343{
344 return WillLaunchOrAttach ();
345}
346
347Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000348ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000349{
350 return WillLaunchOrAttach ();
351}
352
353Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000354ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000355{
356 return WillLaunchOrAttach ();
357}
358
359Error
Greg Claytone71e2582011-02-04 01:58:07 +0000360ProcessGDBRemote::DoConnectRemote (const char *remote_url)
361{
362 Error error (WillLaunchOrAttach ());
363
364 if (error.Fail())
365 return error;
366
367 if (strncmp (remote_url, "connect://", strlen ("connect://")) == 0)
368 {
369 error = ConnectToDebugserver (remote_url);
370 }
371 else
372 {
373 error.SetErrorStringWithFormat ("unsupported remote url: %s", remote_url);
374 }
375
376 if (error.Fail())
377 return error;
378 StartAsyncThread ();
379
380 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (m_packet_timeout);
381 if (pid == LLDB_INVALID_PROCESS_ID)
382 {
383 // We don't have a valid process ID, so note that we are connected
384 // and could now request to launch or attach, or get remote process
385 // listings...
386 SetPrivateState (eStateConnected);
387 }
388 else
389 {
390 // We have a valid process
391 SetID (pid);
392 StringExtractorGDBRemote response;
393 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
394 {
395 const StateType state = SetThreadStopInfo (response);
396 if (state == eStateStopped)
397 {
398 SetPrivateState (state);
399 }
400 else
401 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
402 }
403 else
404 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
405 }
406 return error;
407}
408
409Error
Chris Lattner24943d22010-06-08 16:52:24 +0000410ProcessGDBRemote::WillLaunchOrAttach ()
411{
412 Error error;
413 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic
414 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld"));
415
416 if (m_dynamic_loader_ap.get() == NULL)
417 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'");
418 m_stdio_communication.Clear ();
419
420 return error;
421}
422
423//----------------------------------------------------------------------
424// Process Control
425//----------------------------------------------------------------------
426Error
427ProcessGDBRemote::DoLaunch
428(
429 Module* module,
430 char const *argv[],
431 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000432 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000433 const char *stdin_path,
434 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000435 const char *stderr_path,
436 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000437)
438{
Greg Clayton4b407112010-09-30 21:49:03 +0000439 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000440 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
441 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
442 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000443
444 ObjectFile * object_file = module->GetObjectFile();
445 if (object_file)
446 {
447 ArchSpec inferior_arch(module->GetArchitecture());
448 char host_port[128];
449 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000450 char connect_url[128];
451 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000452
Greg Clayton23cf0c72010-11-08 04:29:11 +0000453 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000454 bool start_debugserver_with_inferior_args = false;
455 if (start_debugserver_with_inferior_args)
456 {
457 // We want to launch debugserver with the inferior program and its
458 // arguments on the command line. We should only do this if we
459 // the GDB server we are talking to doesn't support the 'A' packet.
460 error = StartDebugserverProcess (host_port,
461 argv,
462 envp,
Greg Claytonde915be2011-01-23 05:56:20 +0000463 stdin_path,
464 stdout_path,
465 stderr_path,
466 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000467 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000468 LLDB_INVALID_PROCESS_ID,
469 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000470 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000471 inferior_arch);
472 if (error.Fail())
473 return error;
474
Greg Claytone71e2582011-02-04 01:58:07 +0000475 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000476 if (error.Success())
477 {
478 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
479 }
480 }
481 else
482 {
483 error = StartDebugserverProcess (host_port,
484 NULL,
485 NULL,
Greg Claytonde915be2011-01-23 05:56:20 +0000486 stdin_path,
487 stdout_path,
488 stderr_path,
489 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000490 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000491 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000492 NULL,
493 false,
Caroline Ticebd666012010-12-03 18:46:09 +0000494 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000495 inferior_arch);
496 if (error.Fail())
497 return error;
498
Greg Claytone71e2582011-02-04 01:58:07 +0000499 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000500 if (error.Success())
501 {
502 // Send the environment and the program + arguments after we connect
503 if (envp)
504 {
505 const char *env_entry;
506 for (int i=0; (env_entry = envp[i]); ++i)
507 {
508 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
509 break;
510 }
511 }
512
Greg Clayton960d6a42010-08-03 00:35:52 +0000513 // FIXME: convert this to use the new set/show variables when they are available
514#if 0
515 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
516 {
517 const uint32_t attach_debugserver_secs = 10;
518 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
519 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
520 {
521 printf ("%i\n", attach_debugserver_secs - i);
522 sleep (1);
523 }
524 }
525#endif
526
Chris Lattner24943d22010-06-08 16:52:24 +0000527 const uint32_t arg_timeout_seconds = 10;
528 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
529 if (arg_packet_err == 0)
530 {
531 std::string error_str;
532 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
533 {
534 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
535 }
536 else
537 {
538 error.SetErrorString (error_str.c_str());
539 }
540 }
541 else
542 {
543 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
544 }
545
546 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
547 }
548 }
549
550 if (GetID() == LLDB_INVALID_PROCESS_ID)
551 {
552 KillDebugserverProcess ();
553 return error;
554 }
555
556 StringExtractorGDBRemote response;
557 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
558 SetPrivateState (SetThreadStopInfo (response));
559
560 }
561 else
562 {
563 // Set our user ID to an invalid process ID.
564 SetID(LLDB_INVALID_PROCESS_ID);
565 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
566 }
Chris Lattner24943d22010-06-08 16:52:24 +0000567 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000568
Chris Lattner24943d22010-06-08 16:52:24 +0000569}
570
571
572Error
Greg Claytone71e2582011-02-04 01:58:07 +0000573ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000574{
575 Error error;
576 // Sleep and wait a bit for debugserver to start to listen...
577 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
578 if (conn_ap.get())
579 {
Chris Lattner24943d22010-06-08 16:52:24 +0000580 const uint32_t max_retry_count = 50;
581 uint32_t retry_count = 0;
582 while (!m_gdb_comm.IsConnected())
583 {
Greg Claytone71e2582011-02-04 01:58:07 +0000584 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000585 {
586 m_gdb_comm.SetConnection (conn_ap.release());
587 break;
588 }
589 retry_count++;
590
591 if (retry_count >= max_retry_count)
592 break;
593
594 usleep (100000);
595 }
596 }
597
598 if (!m_gdb_comm.IsConnected())
599 {
600 if (error.Success())
601 error.SetErrorString("not connected to remote gdb server");
602 return error;
603 }
604
Chris Lattner24943d22010-06-08 16:52:24 +0000605 if (m_gdb_comm.StartReadThread(&error))
606 {
607 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000608 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000609
610 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000611 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
612 this,
613 m_debugserver_pid,
614 false);
615
Greg Claytonc1f45872011-02-12 06:28:37 +0000616 m_gdb_comm.ResetDiscoverableSettings();
617 m_gdb_comm.GetSendAcks ();
618 m_gdb_comm.GetThreadSuffixSupported ();
619 m_gdb_comm.GetHostInfo ();
620 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000621 }
622 return error;
623}
624
625void
626ProcessGDBRemote::DidLaunchOrAttach ()
627{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000628 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
629 if (log)
630 log->Printf ("ProcessGDBRemote::DidLaunch()");
Chris Lattner24943d22010-06-08 16:52:24 +0000631 if (GetID() == LLDB_INVALID_PROCESS_ID)
632 {
633 m_dynamic_loader_ap.reset();
634 }
635 else
636 {
637 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
638
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000639 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000640
Greg Clayton395fc332011-02-15 21:59:32 +0000641 m_target.GetArchitecture().SetByteOrder (m_gdb_comm.GetByteOrder());
Greg Clayton20d338f2010-11-18 05:57:03 +0000642
Chris Lattner24943d22010-06-08 16:52:24 +0000643 StreamString strm;
644
Chris Lattner24943d22010-06-08 16:52:24 +0000645 // See if the GDB server supports the qHostInfo information
646 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
647 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Claytonfc7920f2011-02-09 03:09:55 +0000648 ArchSpec target_arch (GetTarget().GetArchitecture());
649 ArchSpec gdb_remote_arch (m_gdb_comm.GetHostArchitecture());
650
Greg Claytonc62176d2011-02-09 03:12:09 +0000651 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytonfc7920f2011-02-09 03:09:55 +0000652 // ARM executables and shared libraries can have mixed ARM architectures.
653 // You can have an armv6 executable, and if the host is armv7, then the
654 // system will load the best possible architecture for all shared libraries
655 // it has, so we really need to take the remote host architecture as our
656 // defacto architecture in this case.
657
658 if (gdb_remote_arch == ArchSpec ("arm") &&
Greg Clayton395fc332011-02-15 21:59:32 +0000659 vendor && ::strcmp(vendor, "apple") == 0)
Greg Claytonfc7920f2011-02-09 03:09:55 +0000660 {
661 GetTarget().SetArchitecture (gdb_remote_arch);
662 target_arch = gdb_remote_arch;
663 }
664
Greg Clayton395fc332011-02-15 21:59:32 +0000665 if (vendor)
666 m_target.GetArchitecture().GetTriple().setVendorName(vendor);
667 if (os_type)
668 m_target.GetArchitecture().GetTriple().setOSName(os_type);
Chris Lattner24943d22010-06-08 16:52:24 +0000669 }
670}
671
672void
673ProcessGDBRemote::DidLaunch ()
674{
675 DidLaunchOrAttach ();
676 if (m_dynamic_loader_ap.get())
677 m_dynamic_loader_ap->DidLaunch();
678}
679
680Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000681ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000682{
683 Error error;
684 // Clear out and clean up from any current state
685 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000686 ArchSpec arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000687
Chris Lattner24943d22010-06-08 16:52:24 +0000688 if (attach_pid != LLDB_INVALID_PROCESS_ID)
689 {
Chris Lattner24943d22010-06-08 16:52:24 +0000690 char host_port[128];
691 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000692 char connect_url[128];
693 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
694
Greg Clayton452bf612010-08-31 18:35:14 +0000695 error = StartDebugserverProcess (host_port, // debugserver_url
696 NULL, // inferior_argv
697 NULL, // inferior_envp
698 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000699 NULL, // stdout_path
700 NULL, // stderr_path
701 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000702 false, // launch_process == false (we are attaching)
703 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
704 NULL, // Don't send any attach by process name option to debugserver
705 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000706 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000707 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000708
709 if (error.Fail())
710 {
711 const char *error_string = error.AsCString();
712 if (error_string == NULL)
713 error_string = "unable to launch " DEBUGSERVER_BASENAME;
714
715 SetExitStatus (-1, error_string);
716 }
717 else
718 {
Greg Claytone71e2582011-02-04 01:58:07 +0000719 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000720 if (error.Success())
721 {
722 char packet[64];
723 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000724
725 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000726 }
727 }
728 }
Chris Lattner24943d22010-06-08 16:52:24 +0000729 return error;
730}
731
732size_t
733ProcessGDBRemote::AttachInputReaderCallback
734(
735 void *baton,
736 InputReader *reader,
737 lldb::InputReaderAction notification,
738 const char *bytes,
739 size_t bytes_len
740)
741{
742 if (notification == eInputReaderGotToken)
743 {
744 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
745 if (gdb_process->m_waiting_for_attach)
746 gdb_process->m_waiting_for_attach = false;
747 reader->SetIsDone(true);
748 return 1;
749 }
750 return 0;
751}
752
753Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000754ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000755{
756 Error error;
757 // Clear out and clean up from any current state
758 Clear();
759 // HACK: require arch be set correctly at the target level until we can
760 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000761
Chris Lattner24943d22010-06-08 16:52:24 +0000762 if (process_name && process_name[0])
763 {
Jim Ingham7508e732010-08-09 23:31:02 +0000764 ArchSpec arch_spec = GetTarget().GetArchitecture();
Greg Claytone71e2582011-02-04 01:58:07 +0000765
766 char host_port[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000767 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000768 char connect_url[128];
769 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
770
Greg Clayton452bf612010-08-31 18:35:14 +0000771 error = StartDebugserverProcess (host_port, // debugserver_url
772 NULL, // inferior_argv
773 NULL, // inferior_envp
774 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000775 NULL, // stdout_path
776 NULL, // stderr_path
777 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000778 false, // launch_process == false (we are attaching)
779 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
780 NULL, // Don't send any attach by process name option to debugserver
781 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000782 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000783 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000784 if (error.Fail())
785 {
786 const char *error_string = error.AsCString();
787 if (error_string == NULL)
788 error_string = "unable to launch " DEBUGSERVER_BASENAME;
789
790 SetExitStatus (-1, error_string);
791 }
792 else
793 {
Greg Claytone71e2582011-02-04 01:58:07 +0000794 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000795 if (error.Success())
796 {
797 StreamString packet;
798
Chris Lattner24943d22010-06-08 16:52:24 +0000799 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000800 packet.PutCString("vAttachWait");
801 else
802 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000803 packet.PutChar(';');
Greg Claytoncd548032011-02-01 01:31:41 +0000804 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000805
806 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
Chris Lattner24943d22010-06-08 16:52:24 +0000807
Chris Lattner24943d22010-06-08 16:52:24 +0000808 }
809 }
810 }
Chris Lattner24943d22010-06-08 16:52:24 +0000811 return error;
812}
813
Chris Lattner24943d22010-06-08 16:52:24 +0000814
815void
816ProcessGDBRemote::DidAttach ()
817{
Greg Claytone71e2582011-02-04 01:58:07 +0000818 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000819 if (m_dynamic_loader_ap.get())
820 m_dynamic_loader_ap->DidAttach();
821}
822
823Error
824ProcessGDBRemote::WillResume ()
825{
Greg Claytonc1f45872011-02-12 06:28:37 +0000826 m_continue_c_tids.clear();
827 m_continue_C_tids.clear();
828 m_continue_s_tids.clear();
829 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000830 return Error();
831}
832
833Error
834ProcessGDBRemote::DoResume ()
835{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000836 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000837 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
838 if (log)
839 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000840
841 Listener listener ("gdb-remote.resume-packet-sent");
842 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
843 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000844 StreamString continue_packet;
845 bool continue_packet_error = false;
846 if (m_gdb_comm.HasAnyVContSupport ())
847 {
848 continue_packet.PutCString ("vCont");
849
850 if (!m_continue_c_tids.empty())
851 {
852 if (m_gdb_comm.GetVContSupported ('c'))
853 {
854 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos)
855 continue_packet.Printf(";c:%4.4x", *t_pos);
856 }
857 else
858 continue_packet_error = true;
859 }
860
861 if (!continue_packet_error && !m_continue_C_tids.empty())
862 {
863 if (m_gdb_comm.GetVContSupported ('C'))
864 {
865 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos)
866 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
867 }
868 else
869 continue_packet_error = true;
870 }
Greg Claytonb749a262010-12-03 06:02:24 +0000871
Greg Claytonc1f45872011-02-12 06:28:37 +0000872 if (!continue_packet_error && !m_continue_s_tids.empty())
873 {
874 if (m_gdb_comm.GetVContSupported ('s'))
875 {
876 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos)
877 continue_packet.Printf(";s:%4.4x", *t_pos);
878 }
879 else
880 continue_packet_error = true;
881 }
882
883 if (!continue_packet_error && !m_continue_S_tids.empty())
884 {
885 if (m_gdb_comm.GetVContSupported ('S'))
886 {
887 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos)
888 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
889 }
890 else
891 continue_packet_error = true;
892 }
893
894 if (continue_packet_error)
895 continue_packet.GetString().clear();
896 }
897 else
898 continue_packet_error = true;
899
900 if (continue_packet_error)
901 {
902 continue_packet_error = false;
903 // Either no vCont support, or we tried to use part of the vCont
904 // packet that wasn't supported by the remote GDB server.
905 // We need to try and make a simple packet that can do our continue
906 const size_t num_threads = GetThreadList().GetSize();
907 const size_t num_continue_c_tids = m_continue_c_tids.size();
908 const size_t num_continue_C_tids = m_continue_C_tids.size();
909 const size_t num_continue_s_tids = m_continue_s_tids.size();
910 const size_t num_continue_S_tids = m_continue_S_tids.size();
911 if (num_continue_c_tids > 0)
912 {
913 if (num_continue_c_tids == num_threads)
914 {
915 // All threads are resuming...
916 SetCurrentGDBRemoteThreadForRun (-1);
917 continue_packet.PutChar ('c');
918 }
919 else if (num_continue_c_tids == 1 &&
920 num_continue_C_tids == 0 &&
921 num_continue_s_tids == 0 &&
922 num_continue_S_tids == 0 )
923 {
924 // Only one thread is continuing
925 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
926 continue_packet.PutChar ('c');
927 }
928 else
929 {
930 // We can't represent this continue packet....
931 continue_packet_error = true;
932 }
933 }
934
935 if (!continue_packet_error && num_continue_C_tids > 0)
936 {
937 if (num_continue_C_tids == num_threads)
938 {
939 const int continue_signo = m_continue_C_tids.front().second;
940 if (num_continue_C_tids > 1)
941 {
942 for (size_t i=1; i<num_threads; ++i)
943 {
944 if (m_continue_C_tids[i].second != continue_signo)
945 continue_packet_error = true;
946 }
947 }
948 if (!continue_packet_error)
949 {
950 // Add threads continuing with the same signo...
951 SetCurrentGDBRemoteThreadForRun (-1);
952 continue_packet.Printf("C%2.2x", continue_signo);
953 }
954 }
955 else if (num_continue_c_tids == 0 &&
956 num_continue_C_tids == 1 &&
957 num_continue_s_tids == 0 &&
958 num_continue_S_tids == 0 )
959 {
960 // Only one thread is continuing with signal
961 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
962 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
963 }
964 else
965 {
966 // We can't represent this continue packet....
967 continue_packet_error = true;
968 }
969 }
970
971 if (!continue_packet_error && num_continue_s_tids > 0)
972 {
973 if (num_continue_s_tids == num_threads)
974 {
975 // All threads are resuming...
976 SetCurrentGDBRemoteThreadForRun (-1);
977 continue_packet.PutChar ('s');
978 }
979 else if (num_continue_c_tids == 0 &&
980 num_continue_C_tids == 0 &&
981 num_continue_s_tids == 1 &&
982 num_continue_S_tids == 0 )
983 {
984 // Only one thread is stepping
985 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
986 continue_packet.PutChar ('s');
987 }
988 else
989 {
990 // We can't represent this continue packet....
991 continue_packet_error = true;
992 }
993 }
994
995 if (!continue_packet_error && num_continue_S_tids > 0)
996 {
997 if (num_continue_S_tids == num_threads)
998 {
999 const int step_signo = m_continue_S_tids.front().second;
1000 // Are all threads trying to step with the same signal?
1001 if (num_continue_S_tids > 1)
1002 {
1003 for (size_t i=1; i<num_threads; ++i)
1004 {
1005 if (m_continue_S_tids[i].second != step_signo)
1006 continue_packet_error = true;
1007 }
1008 }
1009 if (!continue_packet_error)
1010 {
1011 // Add threads stepping with the same signo...
1012 SetCurrentGDBRemoteThreadForRun (-1);
1013 continue_packet.Printf("S%2.2x", step_signo);
1014 }
1015 }
1016 else if (num_continue_c_tids == 0 &&
1017 num_continue_C_tids == 0 &&
1018 num_continue_s_tids == 0 &&
1019 num_continue_S_tids == 1 )
1020 {
1021 // Only one thread is stepping with signal
1022 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1023 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1024 }
1025 else
1026 {
1027 // We can't represent this continue packet....
1028 continue_packet_error = true;
1029 }
1030 }
1031 }
1032
1033 if (continue_packet_error)
1034 {
1035 error.SetErrorString ("can't make continue packet for this resume");
1036 }
1037 else
1038 {
1039 EventSP event_sp;
1040 TimeValue timeout;
1041 timeout = TimeValue::Now();
1042 timeout.OffsetWithSeconds (5);
1043 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1044
1045 if (listener.WaitForEvent (&timeout, event_sp) == false)
1046 error.SetErrorString("Resume timed out.");
1047 }
Greg Claytonb749a262010-12-03 06:02:24 +00001048 }
1049
Jim Ingham3ae449a2010-11-17 02:32:00 +00001050 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001051}
1052
1053size_t
1054ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1055{
1056 const uint8_t *trap_opcode = NULL;
1057 uint32_t trap_opcode_size = 0;
1058
1059 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
1060 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
1061 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
1062 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
1063
Jim Ingham7508e732010-08-09 23:31:02 +00001064 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +00001065 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +00001066 {
Greg Claytoncf015052010-06-11 03:25:34 +00001067 case ArchSpec::eCPU_i386:
1068 case ArchSpec::eCPU_x86_64:
1069 trap_opcode = g_i386_breakpoint_opcode;
1070 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
1071 break;
1072
1073 case ArchSpec::eCPU_arm:
1074 // TODO: fill this in for ARM. We need to dig up the symbol for
1075 // the address in the breakpoint locaiton and figure out if it is
1076 // an ARM or Thumb breakpoint.
1077 trap_opcode = g_arm_breakpoint_opcode;
1078 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1079 break;
1080
1081 case ArchSpec::eCPU_ppc:
1082 case ArchSpec::eCPU_ppc64:
1083 trap_opcode = g_ppc_breakpoint_opcode;
1084 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
1085 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001086
Greg Claytoncf015052010-06-11 03:25:34 +00001087 default:
1088 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
1089 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001090 }
1091
1092 if (trap_opcode && trap_opcode_size)
1093 {
1094 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1095 return trap_opcode_size;
1096 }
1097 return 0;
1098}
1099
1100uint32_t
1101ProcessGDBRemote::UpdateThreadListIfNeeded ()
1102{
1103 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001104 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001105 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001106 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1107
Greg Clayton5205f0b2010-09-03 17:10:42 +00001108 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001109 const uint32_t stop_id = GetStopID();
1110 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1111 {
1112 // Update the thread list's stop id immediately so we don't recurse into this function.
1113 ThreadList curr_thread_list (this);
1114 curr_thread_list.SetStopID(stop_id);
1115
1116 Error err;
1117 StringExtractorGDBRemote response;
1118 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
1119 response.IsNormalPacket();
1120 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
1121 {
1122 char ch = response.GetChar();
1123 if (ch == 'l')
1124 break;
1125 if (ch == 'm')
1126 {
1127 do
1128 {
1129 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1130
1131 if (tid != LLDB_INVALID_THREAD_ID)
1132 {
1133 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001134 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001135 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1136 curr_thread_list.AddThread(thread_sp);
1137 }
1138
1139 ch = response.GetChar();
1140 } while (ch == ',');
1141 }
1142 }
1143
1144 m_thread_list = curr_thread_list;
1145
1146 SetThreadStopInfo (m_last_stop_packet);
1147 }
1148 return GetThreadList().GetSize(false);
1149}
1150
1151
1152StateType
1153ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1154{
1155 const char stop_type = stop_packet.GetChar();
1156 switch (stop_type)
1157 {
1158 case 'T':
1159 case 'S':
1160 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001161 if (GetStopID() == 0)
1162 {
1163 // Our first stop, make sure we have a process ID, and also make
1164 // sure we know about our registers
1165 if (GetID() == LLDB_INVALID_PROCESS_ID)
1166 {
1167 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (1);
1168 if (pid != LLDB_INVALID_PROCESS_ID)
1169 SetID (pid);
1170 }
1171 BuildDynamicRegisterInfo (true);
1172 }
Chris Lattner24943d22010-06-08 16:52:24 +00001173 // Stop with signal and thread info
1174 const uint8_t signo = stop_packet.GetHexU8();
1175 std::string name;
1176 std::string value;
1177 std::string thread_name;
1178 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001179 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001180 uint32_t tid = LLDB_INVALID_THREAD_ID;
1181 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1182 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001183 ThreadSP thread_sp;
1184
Chris Lattner24943d22010-06-08 16:52:24 +00001185 while (stop_packet.GetNameColonValue(name, value))
1186 {
1187 if (name.compare("metype") == 0)
1188 {
1189 // exception type in big endian hex
1190 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1191 }
1192 else if (name.compare("mecount") == 0)
1193 {
1194 // exception count in big endian hex
1195 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1196 }
1197 else if (name.compare("medata") == 0)
1198 {
1199 // exception data in big endian hex
1200 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1201 }
1202 else if (name.compare("thread") == 0)
1203 {
1204 // thread in big endian hex
1205 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001206 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001207 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001208 if (!thread_sp)
1209 {
1210 // Create the thread if we need to
1211 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1212 m_thread_list.AddThread(thread_sp);
1213 }
Chris Lattner24943d22010-06-08 16:52:24 +00001214 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001215 else if (name.compare("hexname") == 0)
1216 {
1217 StringExtractor name_extractor;
1218 // Swap "value" over into "name_extractor"
1219 name_extractor.GetStringRef().swap(value);
1220 // Now convert the HEX bytes into a string value
1221 name_extractor.GetHexByteString (value);
1222 thread_name.swap (value);
1223 }
Chris Lattner24943d22010-06-08 16:52:24 +00001224 else if (name.compare("name") == 0)
1225 {
1226 thread_name.swap (value);
1227 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001228 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001229 {
1230 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1231 }
Greg Claytona875b642011-01-09 21:07:35 +00001232 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1233 {
1234 // We have a register number that contains an expedited
1235 // register value. Lets supply this register to our thread
1236 // so it won't have to go and read it.
1237 if (thread_sp)
1238 {
1239 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1240
1241 if (reg != UINT32_MAX)
1242 {
1243 StringExtractor reg_value_extractor;
1244 // Swap "value" over into "reg_value_extractor"
1245 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001246 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1247 {
1248 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1249 name.c_str(),
1250 reg,
1251 reg,
1252 reg_value_extractor.GetStringRef().c_str(),
1253 stop_packet.GetStringRef().c_str());
1254 }
Greg Claytona875b642011-01-09 21:07:35 +00001255 }
1256 }
1257 }
Chris Lattner24943d22010-06-08 16:52:24 +00001258 }
Chris Lattner24943d22010-06-08 16:52:24 +00001259
1260 if (thread_sp)
1261 {
1262 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1263
1264 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001265 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001266 if (exc_type != 0)
1267 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001268 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001269
1270 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1271 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001272 exc_data_size,
1273 exc_data_size >= 1 ? exc_data[0] : 0,
1274 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001275 }
1276 else if (signo)
1277 {
Greg Clayton643ee732010-08-04 01:40:35 +00001278 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001279 }
1280 else
1281 {
Greg Clayton643ee732010-08-04 01:40:35 +00001282 StopInfoSP invalid_stop_info_sp;
1283 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001284 }
1285 }
1286 return eStateStopped;
1287 }
1288 break;
1289
1290 case 'W':
1291 // process exited
1292 return eStateExited;
1293
1294 default:
1295 break;
1296 }
1297 return eStateInvalid;
1298}
1299
1300void
1301ProcessGDBRemote::RefreshStateAfterStop ()
1302{
Jim Ingham7508e732010-08-09 23:31:02 +00001303 // FIXME - add a variable to tell that we're in the middle of attaching if we
1304 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001305 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001306// if (!GetTarget().GetArchitecture().IsValid())
1307// {
1308// Module *exe_module = GetTarget().GetExecutableModule().get();
1309// if (exe_module)
1310// m_arch_spec = exe_module->GetArchitecture();
1311// }
1312
Chris Lattner24943d22010-06-08 16:52:24 +00001313 // Let all threads recover from stopping and do any clean up based
1314 // on the previous thread state (if any).
1315 m_thread_list.RefreshStateAfterStop();
1316
1317 // Discover new threads:
1318 UpdateThreadListIfNeeded ();
1319}
1320
1321Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001322ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001323{
1324 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001325
Greg Claytona4881d02011-01-22 07:12:45 +00001326 bool timed_out = false;
1327 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001328
1329 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001330 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001331 // We are being asked to halt during an attach. We need to just close
1332 // our file handle and debugserver will go away, and we can be done...
1333 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001334 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001335 else
1336 {
1337 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1338 {
1339 if (timed_out)
1340 error.SetErrorString("timed out sending interrupt packet");
1341 else
1342 error.SetErrorString("unknown error sending interrupt packet");
1343 }
1344 }
Chris Lattner24943d22010-06-08 16:52:24 +00001345 return error;
1346}
1347
1348Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001349ProcessGDBRemote::InterruptIfRunning
1350(
1351 bool discard_thread_plans,
1352 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001353 EventSP &stop_event_sp
1354)
Chris Lattner24943d22010-06-08 16:52:24 +00001355{
1356 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001357
Greg Clayton2860ba92011-01-23 19:58:49 +00001358 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1359
Greg Clayton68ca8232011-01-25 02:58:48 +00001360 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001361 const bool is_running = m_gdb_comm.IsRunning();
1362 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001363 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001364 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001365 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001366 is_running);
1367
Greg Clayton2860ba92011-01-23 19:58:49 +00001368 if (discard_thread_plans)
1369 {
1370 if (log)
1371 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1372 m_thread_list.DiscardThreadPlans();
1373 }
1374 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001375 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001376 if (catch_stop_event)
1377 {
1378 if (log)
1379 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1380 PausePrivateStateThread();
1381 paused_private_state_thread = true;
1382 }
1383
Greg Clayton4fb400f2010-09-27 21:07:38 +00001384 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001385 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001386 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001387
Greg Clayton72e1c782011-01-22 23:43:18 +00001388 //m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1389 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001390 {
1391 if (timed_out)
1392 error.SetErrorString("timed out sending interrupt packet");
1393 else
1394 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001395 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001396 ResumePrivateStateThread();
1397 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001398 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001399
Greg Clayton72e1c782011-01-22 23:43:18 +00001400 if (catch_stop_event)
1401 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001402 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001403 TimeValue timeout_time;
1404 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001405 timeout_time.OffsetWithSeconds(5);
1406 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001407
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001408 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001409 if (log)
1410 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001411
Greg Clayton2860ba92011-01-23 19:58:49 +00001412 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001413 error.SetErrorString("unable to verify target stopped");
1414 }
1415
Greg Clayton68ca8232011-01-25 02:58:48 +00001416 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001417 {
1418 if (log)
1419 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001420 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001421 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001422 }
Chris Lattner24943d22010-06-08 16:52:24 +00001423 return error;
1424}
1425
Greg Clayton4fb400f2010-09-27 21:07:38 +00001426Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001427ProcessGDBRemote::WillDetach ()
1428{
Greg Clayton2860ba92011-01-23 19:58:49 +00001429 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1430 if (log)
1431 log->Printf ("ProcessGDBRemote::WillDetach()");
1432
Greg Clayton72e1c782011-01-22 23:43:18 +00001433 bool discard_thread_plans = true;
1434 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001435 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001436 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001437}
1438
1439Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001440ProcessGDBRemote::DoDetach()
1441{
1442 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001443 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001444 if (log)
1445 log->Printf ("ProcessGDBRemote::DoDetach()");
1446
1447 DisableAllBreakpointSites ();
1448
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001449 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001450
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001451 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1452 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001453 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001454 if (response_size)
1455 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1456 else
1457 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001458 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001459 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001460 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001461
Greg Clayton4fb400f2010-09-27 21:07:38 +00001462 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001463 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001464
1465 SetPrivateState (eStateDetached);
1466 ResumePrivateStateThread();
1467
1468 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001469 return error;
1470}
Chris Lattner24943d22010-06-08 16:52:24 +00001471
1472Error
1473ProcessGDBRemote::DoDestroy ()
1474{
1475 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001476 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001477 if (log)
1478 log->Printf ("ProcessGDBRemote::DoDestroy()");
1479
1480 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001481 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001482 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001483 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001484 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001485 // We are being asked to halt during an attach. We need to just close
1486 // our file handle and debugserver will go away, and we can be done...
1487 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001488 }
1489 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001490 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001491
1492 StringExtractorGDBRemote response;
1493 bool send_async = true;
1494 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, 2, send_async))
1495 {
1496 char packet_cmd = response.GetChar(0);
1497
1498 if (packet_cmd == 'W' || packet_cmd == 'X')
1499 {
1500 m_last_stop_packet = response;
1501 SetExitStatus(response.GetHexU8(), NULL);
1502 }
1503 }
1504 else
1505 {
1506 SetExitStatus(SIGABRT, NULL);
1507 //error.SetErrorString("kill packet failed");
1508 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001509 }
1510 }
Chris Lattner24943d22010-06-08 16:52:24 +00001511 StopAsyncThread ();
1512 m_gdb_comm.StopReadThread();
1513 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001514 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001515 return error;
1516}
1517
Chris Lattner24943d22010-06-08 16:52:24 +00001518//------------------------------------------------------------------
1519// Process Queries
1520//------------------------------------------------------------------
1521
1522bool
1523ProcessGDBRemote::IsAlive ()
1524{
Greg Clayton58e844b2010-12-08 05:08:21 +00001525 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001526}
1527
1528addr_t
1529ProcessGDBRemote::GetImageInfoAddress()
1530{
1531 if (!m_gdb_comm.IsRunning())
1532 {
1533 StringExtractorGDBRemote response;
1534 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1535 {
1536 if (response.IsNormalPacket())
1537 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1538 }
1539 }
1540 return LLDB_INVALID_ADDRESS;
1541}
1542
1543DynamicLoader *
1544ProcessGDBRemote::GetDynamicLoader()
1545{
1546 return m_dynamic_loader_ap.get();
1547}
1548
1549//------------------------------------------------------------------
1550// Process Memory
1551//------------------------------------------------------------------
1552size_t
1553ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1554{
1555 if (size > m_max_memory_size)
1556 {
1557 // Keep memory read sizes down to a sane limit. This function will be
1558 // called multiple times in order to complete the task by
1559 // lldb_private::Process so it is ok to do this.
1560 size = m_max_memory_size;
1561 }
1562
1563 char packet[64];
1564 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1565 assert (packet_len + 1 < sizeof(packet));
1566 StringExtractorGDBRemote response;
1567 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1568 {
1569 if (response.IsNormalPacket())
1570 {
1571 error.Clear();
1572 return response.GetHexBytes(buf, size, '\xdd');
1573 }
1574 else if (response.IsErrorPacket())
1575 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1576 else if (response.IsUnsupportedPacket())
1577 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1578 else
1579 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1580 }
1581 else
1582 {
1583 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1584 }
1585 return 0;
1586}
1587
1588size_t
1589ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1590{
1591 StreamString packet;
1592 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001593 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001594 StringExtractorGDBRemote response;
1595 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1596 {
1597 if (response.IsOKPacket())
1598 {
1599 error.Clear();
1600 return size;
1601 }
1602 else if (response.IsErrorPacket())
1603 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1604 else if (response.IsUnsupportedPacket())
1605 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1606 else
1607 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1608 }
1609 else
1610 {
1611 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1612 }
1613 return 0;
1614}
1615
1616lldb::addr_t
1617ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1618{
1619 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1620 if (allocated_addr == LLDB_INVALID_ADDRESS)
1621 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1622 else
1623 error.Clear();
1624 return allocated_addr;
1625}
1626
1627Error
1628ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1629{
1630 Error error;
1631 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1632 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1633 return error;
1634}
1635
1636
1637//------------------------------------------------------------------
1638// Process STDIO
1639//------------------------------------------------------------------
1640
1641size_t
1642ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1643{
1644 Mutex::Locker locker(m_stdio_mutex);
1645 size_t bytes_available = m_stdout_data.size();
1646 if (bytes_available > 0)
1647 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001648 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1649 if (log)
1650 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001651 if (bytes_available > buf_size)
1652 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001653 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001654 m_stdout_data.erase(0, buf_size);
1655 bytes_available = buf_size;
1656 }
1657 else
1658 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001659 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001660 m_stdout_data.clear();
1661
1662 //ResetEventBits(eBroadcastBitSTDOUT);
1663 }
1664 }
1665 return bytes_available;
1666}
1667
1668size_t
1669ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1670{
1671 // Can we get STDERR through the remote protocol?
1672 return 0;
1673}
1674
1675size_t
1676ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1677{
1678 if (m_stdio_communication.IsConnected())
1679 {
1680 ConnectionStatus status;
1681 m_stdio_communication.Write(src, src_len, status, NULL);
1682 }
1683 return 0;
1684}
1685
1686Error
1687ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1688{
1689 Error error;
1690 assert (bp_site != NULL);
1691
Greg Claytone005f2c2010-11-06 01:53:30 +00001692 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001693 user_id_t site_id = bp_site->GetID();
1694 const addr_t addr = bp_site->GetLoadAddress();
1695 if (log)
1696 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1697
1698 if (bp_site->IsEnabled())
1699 {
1700 if (log)
1701 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1702 return error;
1703 }
1704 else
1705 {
1706 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1707
1708 if (bp_site->HardwarePreferred())
1709 {
1710 // Try and set hardware breakpoint, and if that fails, fall through
1711 // and set a software breakpoint?
1712 }
1713
1714 if (m_z0_supported)
1715 {
1716 char packet[64];
1717 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1718 assert (packet_len + 1 < sizeof(packet));
1719 StringExtractorGDBRemote response;
1720 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1721 {
1722 if (response.IsUnsupportedPacket())
1723 {
1724 // Disable z packet support and try again
1725 m_z0_supported = 0;
1726 return EnableBreakpoint (bp_site);
1727 }
1728 else if (response.IsOKPacket())
1729 {
1730 bp_site->SetEnabled(true);
1731 bp_site->SetType (BreakpointSite::eExternal);
1732 return error;
1733 }
1734 else
1735 {
1736 uint8_t error_byte = response.GetError();
1737 if (error_byte)
1738 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1739 }
1740 }
1741 }
1742 else
1743 {
1744 return EnableSoftwareBreakpoint (bp_site);
1745 }
1746 }
1747
1748 if (log)
1749 {
1750 const char *err_string = error.AsCString();
1751 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1752 bp_site->GetLoadAddress(),
1753 err_string ? err_string : "NULL");
1754 }
1755 // We shouldn't reach here on a successful breakpoint enable...
1756 if (error.Success())
1757 error.SetErrorToGenericError();
1758 return error;
1759}
1760
1761Error
1762ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1763{
1764 Error error;
1765 assert (bp_site != NULL);
1766 addr_t addr = bp_site->GetLoadAddress();
1767 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001768 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001769 if (log)
1770 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1771
1772 if (bp_site->IsEnabled())
1773 {
1774 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1775
1776 if (bp_site->IsHardware())
1777 {
1778 // TODO: disable hardware breakpoint...
1779 }
1780 else
1781 {
1782 if (m_z0_supported)
1783 {
1784 char packet[64];
1785 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1786 assert (packet_len + 1 < sizeof(packet));
1787 StringExtractorGDBRemote response;
1788 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1789 {
1790 if (response.IsUnsupportedPacket())
1791 {
1792 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1793 }
1794 else if (response.IsOKPacket())
1795 {
1796 if (log)
1797 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1798 bp_site->SetEnabled(false);
1799 return error;
1800 }
1801 else
1802 {
1803 uint8_t error_byte = response.GetError();
1804 if (error_byte)
1805 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1806 }
1807 }
1808 }
1809 else
1810 {
1811 return DisableSoftwareBreakpoint (bp_site);
1812 }
1813 }
1814 }
1815 else
1816 {
1817 if (log)
1818 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1819 return error;
1820 }
1821
1822 if (error.Success())
1823 error.SetErrorToGenericError();
1824 return error;
1825}
1826
1827Error
1828ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1829{
1830 Error error;
1831 if (wp)
1832 {
1833 user_id_t watchID = wp->GetID();
1834 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001835 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001836 if (log)
1837 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1838 if (wp->IsEnabled())
1839 {
1840 if (log)
1841 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1842 return error;
1843 }
1844 else
1845 {
1846 // Pass down an appropriate z/Z packet...
1847 error.SetErrorString("watchpoints not supported");
1848 }
1849 }
1850 else
1851 {
1852 error.SetErrorString("Watchpoint location argument was NULL.");
1853 }
1854 if (error.Success())
1855 error.SetErrorToGenericError();
1856 return error;
1857}
1858
1859Error
1860ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1861{
1862 Error error;
1863 if (wp)
1864 {
1865 user_id_t watchID = wp->GetID();
1866
Greg Claytone005f2c2010-11-06 01:53:30 +00001867 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001868
1869 addr_t addr = wp->GetLoadAddress();
1870 if (log)
1871 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1872
1873 if (wp->IsHardware())
1874 {
1875 // Pass down an appropriate z/Z packet...
1876 error.SetErrorString("watchpoints not supported");
1877 }
1878 // TODO: clear software watchpoints if we implement them
1879 }
1880 else
1881 {
1882 error.SetErrorString("Watchpoint location argument was NULL.");
1883 }
1884 if (error.Success())
1885 error.SetErrorToGenericError();
1886 return error;
1887}
1888
1889void
1890ProcessGDBRemote::Clear()
1891{
1892 m_flags = 0;
1893 m_thread_list.Clear();
1894 {
1895 Mutex::Locker locker(m_stdio_mutex);
1896 m_stdout_data.clear();
1897 }
Chris Lattner24943d22010-06-08 16:52:24 +00001898}
1899
1900Error
1901ProcessGDBRemote::DoSignal (int signo)
1902{
1903 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001904 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001905 if (log)
1906 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1907
1908 if (!m_gdb_comm.SendAsyncSignal (signo))
1909 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1910 return error;
1911}
1912
Chris Lattner24943d22010-06-08 16:52:24 +00001913Error
1914ProcessGDBRemote::StartDebugserverProcess
1915(
1916 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1917 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1918 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Claytonde915be2011-01-23 05:56:20 +00001919 const char *stdin_path,
1920 const char *stdout_path,
1921 const char *stderr_path,
1922 const char *working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001923 bool launch_process, // Set to true if we are going to be launching a the process
1924 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 +00001925 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1926 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001927 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001928 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1929)
1930{
1931 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001932 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1933 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001934 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1935 {
1936 // If we locate debugserver, keep that located version around
1937 static FileSpec g_debugserver_file_spec;
1938
1939 FileSpec debugserver_file_spec;
1940 char debugserver_path[PATH_MAX];
1941
1942 // Always check to see if we have an environment override for the path
1943 // to the debugserver to use and use it if we do.
1944 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1945 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001946 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001947 else
1948 debugserver_file_spec = g_debugserver_file_spec;
1949 bool debugserver_exists = debugserver_file_spec.Exists();
1950 if (!debugserver_exists)
1951 {
1952 // The debugserver binary is in the LLDB.framework/Resources
1953 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001954 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001955 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001956 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001957 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001958 if (debugserver_exists)
1959 {
1960 g_debugserver_file_spec = debugserver_file_spec;
1961 }
1962 else
1963 {
1964 g_debugserver_file_spec.Clear();
1965 debugserver_file_spec.Clear();
1966 }
Chris Lattner24943d22010-06-08 16:52:24 +00001967 }
1968 }
1969
1970 if (debugserver_exists)
1971 {
1972 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1973
1974 m_stdio_communication.Clear();
1975 posix_spawnattr_t attr;
1976
Greg Claytone005f2c2010-11-06 01:53:30 +00001977 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001978
1979 Error local_err; // Errors that don't affect the spawning.
1980 if (log)
1981 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1982 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1983 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001984 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001985 if (error.Fail())
1986 return error;;
1987
1988#if !defined (__arm__)
1989
Greg Clayton24b48ff2010-10-17 22:03:32 +00001990 // We don't need to do this for ARM, and we really shouldn't now
1991 // that we have multiple CPU subtypes and no posix_spawnattr call
1992 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001993 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001994 {
Greg Claytoncf015052010-06-11 03:25:34 +00001995 cpu_type_t cpu = inferior_arch.GetCPUType();
1996 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1997 {
1998 size_t ocount = 0;
1999 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
2000 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002001 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 +00002002
Greg Claytoncf015052010-06-11 03:25:34 +00002003 if (error.Fail() != 0 || ocount != 1)
2004 return error;
2005 }
Chris Lattner24943d22010-06-08 16:52:24 +00002006 }
2007
2008#endif
2009
2010 Args debugserver_args;
2011 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002012
Chris Lattner24943d22010-06-08 16:52:24 +00002013 lldb_utility::PseudoTerminal pty;
Greg Claytonde915be2011-01-23 05:56:20 +00002014 const char *stdio_path = NULL;
2015 if (launch_process &&
Caroline Ticee4450f02011-01-28 00:19:58 +00002016 (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) &&
Greg Claytonde915be2011-01-23 05:56:20 +00002017 m_local_debugserver &&
2018 no_stdio == false)
Chris Lattner24943d22010-06-08 16:52:24 +00002019 {
Chris Lattner24943d22010-06-08 16:52:24 +00002020 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Caroline Ticee4450f02011-01-28 00:19:58 +00002021 {
2022 const char *slave_name = pty.GetSlaveName (NULL, 0);
2023 if (stdin_path == NULL
2024 && stdout_path == NULL
2025 && stderr_path == NULL)
2026 stdio_path = slave_name;
2027 else
2028 {
2029 if (stdin_path == NULL)
2030 stdin_path = slave_name;
2031 if (stdout_path == NULL)
2032 stdout_path = slave_name;
2033 if (stderr_path == NULL)
2034 stderr_path = slave_name;
2035 }
2036 }
Chris Lattner24943d22010-06-08 16:52:24 +00002037 }
2038
2039 // Start args with "debugserver /file/path -r --"
2040 debugserver_args.AppendArgument(debugserver_path);
2041 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002042 // use native registers, not the GDB registers
2043 debugserver_args.AppendArgument("--native-regs");
2044 // make debugserver run in its own session so signals generated by
2045 // special terminal key sequences (^C) don't affect debugserver
2046 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002047
Greg Clayton452bf612010-08-31 18:35:14 +00002048 if (disable_aslr)
2049 debugserver_args.AppendArguments("--disable-aslr");
2050
Chris Lattner24943d22010-06-08 16:52:24 +00002051 // Only set the inferior
Greg Claytonde915be2011-01-23 05:56:20 +00002052 if (launch_process)
Chris Lattner24943d22010-06-08 16:52:24 +00002053 {
Greg Claytonde915be2011-01-23 05:56:20 +00002054 if (no_stdio)
2055 debugserver_args.AppendArgument("--no-stdio");
2056 else
2057 {
2058 if (stdin_path && stdout_path && stderr_path &&
2059 strcmp(stdin_path, stdout_path) == 0 &&
2060 strcmp(stdin_path, stderr_path) == 0)
2061 {
2062 stdio_path = stdin_path;
2063 stdin_path = stdout_path = stderr_path = NULL;
2064 }
2065
2066 if (stdio_path)
2067 {
2068 // All file handles to stdin, stdout, stderr are the same...
2069 debugserver_args.AppendArgument("--stdio-path");
2070 debugserver_args.AppendArgument(stdio_path);
2071 }
2072 else
2073 {
2074 if (stdin_path == NULL && (stdout_path || stderr_path))
2075 stdin_path = "/dev/null";
2076
2077 if (stdout_path == NULL && (stdin_path || stderr_path))
2078 stdout_path = "/dev/null";
2079
2080 if (stderr_path == NULL && (stdin_path || stdout_path))
2081 stderr_path = "/dev/null";
2082
2083 if (stdin_path)
2084 {
2085 debugserver_args.AppendArgument("--stdin-path");
2086 debugserver_args.AppendArgument(stdin_path);
2087 }
2088 if (stdout_path)
2089 {
2090 debugserver_args.AppendArgument("--stdout-path");
2091 debugserver_args.AppendArgument(stdout_path);
2092 }
2093 if (stderr_path)
2094 {
2095 debugserver_args.AppendArgument("--stderr-path");
2096 debugserver_args.AppendArgument(stderr_path);
2097 }
2098 }
2099 }
Chris Lattner24943d22010-06-08 16:52:24 +00002100 }
Greg Claytonde915be2011-01-23 05:56:20 +00002101
2102 if (working_dir)
Caroline Ticebd666012010-12-03 18:46:09 +00002103 {
Greg Claytonde915be2011-01-23 05:56:20 +00002104 debugserver_args.AppendArgument("--working-dir");
2105 debugserver_args.AppendArgument(working_dir);
Caroline Ticebd666012010-12-03 18:46:09 +00002106 }
Chris Lattner24943d22010-06-08 16:52:24 +00002107
2108 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2109 if (env_debugserver_log_file)
2110 {
2111 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2112 debugserver_args.AppendArgument(arg_cstr);
2113 }
2114
2115 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2116 if (env_debugserver_log_flags)
2117 {
2118 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2119 debugserver_args.AppendArgument(arg_cstr);
2120 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002121// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002122// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002123
2124 // Now append the program arguments
2125 if (launch_process)
2126 {
2127 if (inferior_argv)
2128 {
2129 // Terminate the debugserver args so we can now append the inferior args
2130 debugserver_args.AppendArgument("--");
2131
2132 for (int i = 0; inferior_argv[i] != NULL; ++i)
2133 debugserver_args.AppendArgument (inferior_argv[i]);
2134 }
2135 else
2136 {
2137 // Will send environment entries with the 'QEnvironment:' packet
2138 // Will send arguments with the 'A' packet
2139 }
2140 }
2141 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2142 {
2143 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2144 debugserver_args.AppendArgument (arg_cstr);
2145 }
2146 else if (attach_name && attach_name[0])
2147 {
2148 if (wait_for_launch)
2149 debugserver_args.AppendArgument ("--waitfor");
2150 else
2151 debugserver_args.AppendArgument ("--attach");
2152 debugserver_args.AppendArgument (attach_name);
2153 }
2154
2155 Error file_actions_err;
2156 posix_spawn_file_actions_t file_actions;
2157#if DONT_CLOSE_DEBUGSERVER_STDIO
2158 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
2159#else
2160 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
2161 if (file_actions_err.Success())
2162 {
2163 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
2164 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
2165 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
2166 }
2167#endif
2168
2169 if (log)
2170 {
2171 StreamString strm;
2172 debugserver_args.Dump (&strm);
2173 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2174 }
2175
Greg Clayton72e1c782011-01-22 23:43:18 +00002176 error.SetError (::posix_spawnp (&m_debugserver_pid,
2177 debugserver_path,
2178 file_actions_err.Success() ? &file_actions : NULL,
2179 &attr,
2180 debugserver_args.GetArgumentVector(),
2181 (char * const*)inferior_envp),
2182 eErrorTypePOSIX);
2183
Greg Claytone9d0df42010-07-02 01:29:13 +00002184
2185 ::posix_spawnattr_destroy (&attr);
2186
Chris Lattner24943d22010-06-08 16:52:24 +00002187 if (file_actions_err.Success())
2188 ::posix_spawn_file_actions_destroy (&file_actions);
2189
2190 // We have seen some cases where posix_spawnp was returning a valid
2191 // looking pid even when an error was returned, so clear it out
2192 if (error.Fail())
2193 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2194
2195 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002196 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 +00002197
Caroline Ticebd666012010-12-03 18:46:09 +00002198 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00002199 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00002200 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00002201 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00002202 }
Chris Lattner24943d22010-06-08 16:52:24 +00002203 }
2204 else
2205 {
2206 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2207 }
2208
2209 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2210 StartAsyncThread ();
2211 }
2212 return error;
2213}
2214
2215bool
2216ProcessGDBRemote::MonitorDebugserverProcess
2217(
2218 void *callback_baton,
2219 lldb::pid_t debugserver_pid,
2220 int signo, // Zero for no signal
2221 int exit_status // Exit value of process if signal is zero
2222)
2223{
2224 // We pass in the ProcessGDBRemote inferior process it and name it
2225 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2226 // pointer value itself, thus we need the double cast...
2227
2228 // "debugserver_pid" argument passed in is the process ID for
2229 // debugserver that we are tracking...
2230
Greg Clayton75ccf502010-08-21 02:22:51 +00002231 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002232
2233 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2234 if (log)
2235 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2236
Greg Clayton75ccf502010-08-21 02:22:51 +00002237 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002238 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002239 // Sleep for a half a second to make sure our inferior process has
2240 // time to set its exit status before we set it incorrectly when
2241 // both the debugserver and the inferior process shut down.
2242 usleep (500000);
2243 // If our process hasn't yet exited, debugserver might have died.
2244 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002245 const StateType state = process->GetState();
2246
2247 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2248 state != eStateInvalid &&
2249 state != eStateUnloaded &&
2250 state != eStateExited &&
2251 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002252 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002253 char error_str[1024];
2254 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002255 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002256 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2257 if (signal_cstr)
2258 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002259 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002260 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002261 }
2262 else
2263 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002264 ::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 +00002265 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002266
2267 process->SetExitStatus (-1, error_str);
2268 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002269 // Debugserver has exited we need to let our ProcessGDBRemote
2270 // know that it no longer has a debugserver instance
2271 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2272 // We are returning true to this function below, so we can
2273 // forget about the monitor handle.
2274 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002275 }
2276 return true;
2277}
2278
2279void
2280ProcessGDBRemote::KillDebugserverProcess ()
2281{
2282 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2283 {
2284 ::kill (m_debugserver_pid, SIGINT);
2285 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2286 }
2287}
2288
2289void
2290ProcessGDBRemote::Initialize()
2291{
2292 static bool g_initialized = false;
2293
2294 if (g_initialized == false)
2295 {
2296 g_initialized = true;
2297 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2298 GetPluginDescriptionStatic(),
2299 CreateInstance);
2300
2301 Log::Callbacks log_callbacks = {
2302 ProcessGDBRemoteLog::DisableLog,
2303 ProcessGDBRemoteLog::EnableLog,
2304 ProcessGDBRemoteLog::ListLogCategories
2305 };
2306
2307 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2308 }
2309}
2310
2311bool
2312ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2313{
2314 if (m_curr_tid == tid)
2315 return true;
2316
2317 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002318 int packet_len;
2319 if (tid <= 0)
2320 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2321 else
2322 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002323 assert (packet_len + 1 < sizeof(packet));
2324 StringExtractorGDBRemote response;
2325 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2326 {
2327 if (response.IsOKPacket())
2328 {
2329 m_curr_tid = tid;
2330 return true;
2331 }
2332 }
2333 return false;
2334}
2335
2336bool
2337ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2338{
2339 if (m_curr_tid_run == tid)
2340 return true;
2341
2342 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002343 int packet_len;
2344 if (tid <= 0)
2345 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2346 else
2347 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2348
Chris Lattner24943d22010-06-08 16:52:24 +00002349 assert (packet_len + 1 < sizeof(packet));
2350 StringExtractorGDBRemote response;
2351 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2352 {
2353 if (response.IsOKPacket())
2354 {
2355 m_curr_tid_run = tid;
2356 return true;
2357 }
2358 }
2359 return false;
2360}
2361
2362void
2363ProcessGDBRemote::ResetGDBRemoteState ()
2364{
2365 // Reset and GDB remote state
2366 m_curr_tid = LLDB_INVALID_THREAD_ID;
2367 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2368 m_z0_supported = 1;
2369}
2370
2371
2372bool
2373ProcessGDBRemote::StartAsyncThread ()
2374{
2375 ResetGDBRemoteState ();
2376
Greg Claytone005f2c2010-11-06 01:53:30 +00002377 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002378
2379 if (log)
2380 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2381
2382 // Create a thread that watches our internal state and controls which
2383 // events make it to clients (into the DCProcess event queue).
2384 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002385 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002386}
2387
2388void
2389ProcessGDBRemote::StopAsyncThread ()
2390{
Greg Claytone005f2c2010-11-06 01:53:30 +00002391 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002392
2393 if (log)
2394 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2395
2396 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2397
2398 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002399 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002400 {
2401 Host::ThreadJoin (m_async_thread, NULL, NULL);
2402 }
2403}
2404
2405
2406void *
2407ProcessGDBRemote::AsyncThread (void *arg)
2408{
2409 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2410
Greg Claytone005f2c2010-11-06 01:53:30 +00002411 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002412 if (log)
2413 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2414
2415 Listener listener ("ProcessGDBRemote::AsyncThread");
2416 EventSP event_sp;
2417 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2418 eBroadcastBitAsyncThreadShouldExit;
2419
2420 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2421 {
2422 bool done = false;
2423 while (!done)
2424 {
2425 if (log)
2426 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2427 if (listener.WaitForEvent (NULL, event_sp))
2428 {
2429 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002430 if (log)
2431 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2432
Chris Lattner24943d22010-06-08 16:52:24 +00002433 switch (event_type)
2434 {
2435 case eBroadcastBitAsyncContinue:
2436 {
2437 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2438
2439 if (continue_packet)
2440 {
2441 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2442 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2443 if (log)
2444 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2445
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002446 if (::strstr (continue_cstr, "vAttach") == NULL)
2447 process->SetPrivateState(eStateRunning);
Chris Lattner24943d22010-06-08 16:52:24 +00002448 StringExtractorGDBRemote response;
2449 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2450
2451 switch (stop_state)
2452 {
2453 case eStateStopped:
2454 case eStateCrashed:
2455 case eStateSuspended:
2456 process->m_last_stop_packet = response;
2457 process->m_last_stop_packet.SetFilePos (0);
2458 process->SetPrivateState (stop_state);
2459 break;
2460
2461 case eStateExited:
2462 process->m_last_stop_packet = response;
2463 process->m_last_stop_packet.SetFilePos (0);
2464 response.SetFilePos(1);
2465 process->SetExitStatus(response.GetHexU8(), NULL);
2466 done = true;
2467 break;
2468
2469 case eStateInvalid:
2470 break;
2471
2472 default:
2473 process->SetPrivateState (stop_state);
2474 break;
2475 }
2476 }
2477 }
2478 break;
2479
2480 case eBroadcastBitAsyncThreadShouldExit:
2481 if (log)
2482 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2483 done = true;
2484 break;
2485
2486 default:
2487 if (log)
2488 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2489 done = true;
2490 break;
2491 }
2492 }
2493 else
2494 {
2495 if (log)
2496 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2497 done = true;
2498 }
2499 }
2500 }
2501
2502 if (log)
2503 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2504
2505 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2506 return NULL;
2507}
2508
Chris Lattner24943d22010-06-08 16:52:24 +00002509const char *
2510ProcessGDBRemote::GetDispatchQueueNameForThread
2511(
2512 addr_t thread_dispatch_qaddr,
2513 std::string &dispatch_queue_name
2514)
2515{
2516 dispatch_queue_name.clear();
2517 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2518 {
2519 // Cache the dispatch_queue_offsets_addr value so we don't always have
2520 // to look it up
2521 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2522 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002523 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2524 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002525 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002526 if (module_sp)
2527 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2528
2529 if (dispatch_queue_offsets_symbol == NULL)
2530 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002531 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002532 if (module_sp)
2533 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2534 }
Chris Lattner24943d22010-06-08 16:52:24 +00002535 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002536 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002537
2538 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2539 return NULL;
2540 }
2541
2542 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002543 DataExtractor data (memory_buffer,
2544 sizeof(memory_buffer),
2545 m_target.GetArchitecture().GetByteOrder(),
2546 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002547
2548 // Excerpt from src/queue_private.h
2549 struct dispatch_queue_offsets_s
2550 {
2551 uint16_t dqo_version;
2552 uint16_t dqo_label;
2553 uint16_t dqo_label_size;
2554 } dispatch_queue_offsets;
2555
2556
2557 Error error;
2558 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2559 {
2560 uint32_t data_offset = 0;
2561 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2562 {
2563 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2564 {
2565 data_offset = 0;
2566 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2567 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2568 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2569 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2570 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2571 dispatch_queue_name.erase (bytes_read);
2572 }
2573 }
2574 }
2575 }
2576 if (dispatch_queue_name.empty())
2577 return NULL;
2578 return dispatch_queue_name.c_str();
2579}
2580
Jim Ingham7508e732010-08-09 23:31:02 +00002581uint32_t
2582ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2583{
2584 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2585 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2586 if (m_local_debugserver)
2587 {
2588 return Host::ListProcessesMatchingName (name, matches, pids);
2589 }
2590 else
2591 {
2592 // FIXME: Implement talking to the remote debugserver.
2593 return 0;
2594 }
2595
2596}
Jim Ingham55e01d82011-01-22 01:33:44 +00002597
2598bool
2599ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2600 lldb_private::StoppointCallbackContext *context,
2601 lldb::user_id_t break_id,
2602 lldb::user_id_t break_loc_id)
2603{
2604 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2605 // run so I can stop it if that's what I want to do.
2606 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2607 if (log)
2608 log->Printf("Hit New Thread Notification breakpoint.");
2609 return false;
2610}
2611
2612
2613bool
2614ProcessGDBRemote::StartNoticingNewThreads()
2615{
2616 static const char *bp_names[] =
2617 {
2618 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002619 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002620 "_pthread_start",
2621 NULL
2622 };
2623
2624 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2625 size_t num_bps = m_thread_observation_bps.size();
2626 if (num_bps != 0)
2627 {
2628 for (int i = 0; i < num_bps; i++)
2629 {
2630 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2631 if (break_sp)
2632 {
2633 if (log)
2634 log->Printf("Enabled noticing new thread breakpoint.");
2635 break_sp->SetEnabled(true);
2636 }
2637 }
2638 }
2639 else
2640 {
2641 for (int i = 0; bp_names[i] != NULL; i++)
2642 {
2643 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2644 if (breakpoint)
2645 {
2646 if (log)
2647 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2648 m_thread_observation_bps.push_back(breakpoint->GetID());
2649 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2650 }
2651 else
2652 {
2653 if (log)
2654 log->Printf("Failed to create new thread notification breakpoint.");
2655 return false;
2656 }
2657 }
2658 }
2659
2660 return true;
2661}
2662
2663bool
2664ProcessGDBRemote::StopNoticingNewThreads()
2665{
Jim Inghamff276fe2011-02-08 05:19:01 +00002666 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2667 if (log)
2668 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002669 size_t num_bps = m_thread_observation_bps.size();
2670 if (num_bps != 0)
2671 {
2672 for (int i = 0; i < num_bps; i++)
2673 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002674
2675 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2676 if (break_sp)
2677 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002678 break_sp->SetEnabled(false);
2679 }
2680 }
2681 }
2682 return true;
2683}
2684
2685