blob: cee2d3d1dee260592417902be6540088ab571c8c [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
641 m_byte_order = m_gdb_comm.GetByteOrder();
642
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") &&
659 vendor != NULL &&
660 strcmp(vendor, "apple") == 0)
661 {
662 GetTarget().SetArchitecture (gdb_remote_arch);
663 target_arch = gdb_remote_arch;
664 }
665
666 if (!target_arch.IsValid())
667 target_arch = gdb_remote_arch;
668
Greg Claytone71e2582011-02-04 01:58:07 +0000669 if (target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000670 {
Greg Claytonfc7920f2011-02-09 03:09:55 +0000671 if (vendor == NULL)
672 vendor = Host::GetVendorString().AsCString("apple");
673
674 if (os_type == NULL)
675 os_type = Host::GetOSString().AsCString("darwin");
676
677 strm.Printf ("%s-%s-%s", target_arch.AsCString(), vendor, os_type);
678
679 std::transform (strm.GetString().begin(),
680 strm.GetString().end(),
681 strm.GetString().begin(),
682 ::tolower);
683
684 m_target_triple.SetCString(strm.GetString().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000685 }
Chris Lattner24943d22010-06-08 16:52:24 +0000686 }
687}
688
689void
690ProcessGDBRemote::DidLaunch ()
691{
692 DidLaunchOrAttach ();
693 if (m_dynamic_loader_ap.get())
694 m_dynamic_loader_ap->DidLaunch();
695}
696
697Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000698ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000699{
700 Error error;
701 // Clear out and clean up from any current state
702 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000703 ArchSpec arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000704
Chris Lattner24943d22010-06-08 16:52:24 +0000705 if (attach_pid != LLDB_INVALID_PROCESS_ID)
706 {
Chris Lattner24943d22010-06-08 16:52:24 +0000707 char host_port[128];
708 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000709 char connect_url[128];
710 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
711
Greg Clayton452bf612010-08-31 18:35:14 +0000712 error = StartDebugserverProcess (host_port, // debugserver_url
713 NULL, // inferior_argv
714 NULL, // inferior_envp
715 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000716 NULL, // stdout_path
717 NULL, // stderr_path
718 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000719 false, // launch_process == false (we are attaching)
720 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
721 NULL, // Don't send any attach by process name option to debugserver
722 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000723 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000724 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000725
726 if (error.Fail())
727 {
728 const char *error_string = error.AsCString();
729 if (error_string == NULL)
730 error_string = "unable to launch " DEBUGSERVER_BASENAME;
731
732 SetExitStatus (-1, error_string);
733 }
734 else
735 {
Greg Claytone71e2582011-02-04 01:58:07 +0000736 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000737 if (error.Success())
738 {
739 char packet[64];
740 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000741
742 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000743 }
744 }
745 }
Chris Lattner24943d22010-06-08 16:52:24 +0000746 return error;
747}
748
749size_t
750ProcessGDBRemote::AttachInputReaderCallback
751(
752 void *baton,
753 InputReader *reader,
754 lldb::InputReaderAction notification,
755 const char *bytes,
756 size_t bytes_len
757)
758{
759 if (notification == eInputReaderGotToken)
760 {
761 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
762 if (gdb_process->m_waiting_for_attach)
763 gdb_process->m_waiting_for_attach = false;
764 reader->SetIsDone(true);
765 return 1;
766 }
767 return 0;
768}
769
770Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000771ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000772{
773 Error error;
774 // Clear out and clean up from any current state
775 Clear();
776 // HACK: require arch be set correctly at the target level until we can
777 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000778
Chris Lattner24943d22010-06-08 16:52:24 +0000779 if (process_name && process_name[0])
780 {
Jim Ingham7508e732010-08-09 23:31:02 +0000781 ArchSpec arch_spec = GetTarget().GetArchitecture();
Greg Claytone71e2582011-02-04 01:58:07 +0000782
783 char host_port[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000784 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000785 char connect_url[128];
786 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
787
Greg Clayton452bf612010-08-31 18:35:14 +0000788 error = StartDebugserverProcess (host_port, // debugserver_url
789 NULL, // inferior_argv
790 NULL, // inferior_envp
791 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000792 NULL, // stdout_path
793 NULL, // stderr_path
794 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000795 false, // launch_process == false (we are attaching)
796 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
797 NULL, // Don't send any attach by process name option to debugserver
798 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000799 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000800 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000801 if (error.Fail())
802 {
803 const char *error_string = error.AsCString();
804 if (error_string == NULL)
805 error_string = "unable to launch " DEBUGSERVER_BASENAME;
806
807 SetExitStatus (-1, error_string);
808 }
809 else
810 {
Greg Claytone71e2582011-02-04 01:58:07 +0000811 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000812 if (error.Success())
813 {
814 StreamString packet;
815
Chris Lattner24943d22010-06-08 16:52:24 +0000816 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000817 packet.PutCString("vAttachWait");
818 else
819 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000820 packet.PutChar(';');
Greg Claytoncd548032011-02-01 01:31:41 +0000821 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000822
823 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
Chris Lattner24943d22010-06-08 16:52:24 +0000824
Chris Lattner24943d22010-06-08 16:52:24 +0000825 }
826 }
827 }
Chris Lattner24943d22010-06-08 16:52:24 +0000828 return error;
829}
830
Chris Lattner24943d22010-06-08 16:52:24 +0000831
832void
833ProcessGDBRemote::DidAttach ()
834{
Greg Claytone71e2582011-02-04 01:58:07 +0000835 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000836 if (m_dynamic_loader_ap.get())
837 m_dynamic_loader_ap->DidAttach();
838}
839
840Error
841ProcessGDBRemote::WillResume ()
842{
Greg Claytonc1f45872011-02-12 06:28:37 +0000843 m_continue_c_tids.clear();
844 m_continue_C_tids.clear();
845 m_continue_s_tids.clear();
846 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000847 return Error();
848}
849
850Error
851ProcessGDBRemote::DoResume ()
852{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000853 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000854 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
855 if (log)
856 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000857
858 Listener listener ("gdb-remote.resume-packet-sent");
859 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
860 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000861 StreamString continue_packet;
862 bool continue_packet_error = false;
863 if (m_gdb_comm.HasAnyVContSupport ())
864 {
865 continue_packet.PutCString ("vCont");
866
867 if (!m_continue_c_tids.empty())
868 {
869 if (m_gdb_comm.GetVContSupported ('c'))
870 {
871 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)
872 continue_packet.Printf(";c:%4.4x", *t_pos);
873 }
874 else
875 continue_packet_error = true;
876 }
877
878 if (!continue_packet_error && !m_continue_C_tids.empty())
879 {
880 if (m_gdb_comm.GetVContSupported ('C'))
881 {
882 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)
883 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
884 }
885 else
886 continue_packet_error = true;
887 }
Greg Claytonb749a262010-12-03 06:02:24 +0000888
Greg Claytonc1f45872011-02-12 06:28:37 +0000889 if (!continue_packet_error && !m_continue_s_tids.empty())
890 {
891 if (m_gdb_comm.GetVContSupported ('s'))
892 {
893 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)
894 continue_packet.Printf(";s:%4.4x", *t_pos);
895 }
896 else
897 continue_packet_error = true;
898 }
899
900 if (!continue_packet_error && !m_continue_S_tids.empty())
901 {
902 if (m_gdb_comm.GetVContSupported ('S'))
903 {
904 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)
905 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
906 }
907 else
908 continue_packet_error = true;
909 }
910
911 if (continue_packet_error)
912 continue_packet.GetString().clear();
913 }
914 else
915 continue_packet_error = true;
916
917 if (continue_packet_error)
918 {
919 continue_packet_error = false;
920 // Either no vCont support, or we tried to use part of the vCont
921 // packet that wasn't supported by the remote GDB server.
922 // We need to try and make a simple packet that can do our continue
923 const size_t num_threads = GetThreadList().GetSize();
924 const size_t num_continue_c_tids = m_continue_c_tids.size();
925 const size_t num_continue_C_tids = m_continue_C_tids.size();
926 const size_t num_continue_s_tids = m_continue_s_tids.size();
927 const size_t num_continue_S_tids = m_continue_S_tids.size();
928 if (num_continue_c_tids > 0)
929 {
930 if (num_continue_c_tids == num_threads)
931 {
932 // All threads are resuming...
933 SetCurrentGDBRemoteThreadForRun (-1);
934 continue_packet.PutChar ('c');
935 }
936 else if (num_continue_c_tids == 1 &&
937 num_continue_C_tids == 0 &&
938 num_continue_s_tids == 0 &&
939 num_continue_S_tids == 0 )
940 {
941 // Only one thread is continuing
942 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
943 continue_packet.PutChar ('c');
944 }
945 else
946 {
947 // We can't represent this continue packet....
948 continue_packet_error = true;
949 }
950 }
951
952 if (!continue_packet_error && num_continue_C_tids > 0)
953 {
954 if (num_continue_C_tids == num_threads)
955 {
956 const int continue_signo = m_continue_C_tids.front().second;
957 if (num_continue_C_tids > 1)
958 {
959 for (size_t i=1; i<num_threads; ++i)
960 {
961 if (m_continue_C_tids[i].second != continue_signo)
962 continue_packet_error = true;
963 }
964 }
965 if (!continue_packet_error)
966 {
967 // Add threads continuing with the same signo...
968 SetCurrentGDBRemoteThreadForRun (-1);
969 continue_packet.Printf("C%2.2x", continue_signo);
970 }
971 }
972 else if (num_continue_c_tids == 0 &&
973 num_continue_C_tids == 1 &&
974 num_continue_s_tids == 0 &&
975 num_continue_S_tids == 0 )
976 {
977 // Only one thread is continuing with signal
978 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
979 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
980 }
981 else
982 {
983 // We can't represent this continue packet....
984 continue_packet_error = true;
985 }
986 }
987
988 if (!continue_packet_error && num_continue_s_tids > 0)
989 {
990 if (num_continue_s_tids == num_threads)
991 {
992 // All threads are resuming...
993 SetCurrentGDBRemoteThreadForRun (-1);
994 continue_packet.PutChar ('s');
995 }
996 else if (num_continue_c_tids == 0 &&
997 num_continue_C_tids == 0 &&
998 num_continue_s_tids == 1 &&
999 num_continue_S_tids == 0 )
1000 {
1001 // Only one thread is stepping
1002 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
1003 continue_packet.PutChar ('s');
1004 }
1005 else
1006 {
1007 // We can't represent this continue packet....
1008 continue_packet_error = true;
1009 }
1010 }
1011
1012 if (!continue_packet_error && num_continue_S_tids > 0)
1013 {
1014 if (num_continue_S_tids == num_threads)
1015 {
1016 const int step_signo = m_continue_S_tids.front().second;
1017 // Are all threads trying to step with the same signal?
1018 if (num_continue_S_tids > 1)
1019 {
1020 for (size_t i=1; i<num_threads; ++i)
1021 {
1022 if (m_continue_S_tids[i].second != step_signo)
1023 continue_packet_error = true;
1024 }
1025 }
1026 if (!continue_packet_error)
1027 {
1028 // Add threads stepping with the same signo...
1029 SetCurrentGDBRemoteThreadForRun (-1);
1030 continue_packet.Printf("S%2.2x", step_signo);
1031 }
1032 }
1033 else if (num_continue_c_tids == 0 &&
1034 num_continue_C_tids == 0 &&
1035 num_continue_s_tids == 0 &&
1036 num_continue_S_tids == 1 )
1037 {
1038 // Only one thread is stepping with signal
1039 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1040 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1041 }
1042 else
1043 {
1044 // We can't represent this continue packet....
1045 continue_packet_error = true;
1046 }
1047 }
1048 }
1049
1050 if (continue_packet_error)
1051 {
1052 error.SetErrorString ("can't make continue packet for this resume");
1053 }
1054 else
1055 {
1056 EventSP event_sp;
1057 TimeValue timeout;
1058 timeout = TimeValue::Now();
1059 timeout.OffsetWithSeconds (5);
1060 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1061
1062 if (listener.WaitForEvent (&timeout, event_sp) == false)
1063 error.SetErrorString("Resume timed out.");
1064 }
Greg Claytonb749a262010-12-03 06:02:24 +00001065 }
1066
Jim Ingham3ae449a2010-11-17 02:32:00 +00001067 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001068}
1069
1070size_t
1071ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1072{
1073 const uint8_t *trap_opcode = NULL;
1074 uint32_t trap_opcode_size = 0;
1075
1076 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
1077 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
1078 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
1079 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
1080
Jim Ingham7508e732010-08-09 23:31:02 +00001081 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +00001082 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +00001083 {
Greg Claytoncf015052010-06-11 03:25:34 +00001084 case ArchSpec::eCPU_i386:
1085 case ArchSpec::eCPU_x86_64:
1086 trap_opcode = g_i386_breakpoint_opcode;
1087 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
1088 break;
1089
1090 case ArchSpec::eCPU_arm:
1091 // TODO: fill this in for ARM. We need to dig up the symbol for
1092 // the address in the breakpoint locaiton and figure out if it is
1093 // an ARM or Thumb breakpoint.
1094 trap_opcode = g_arm_breakpoint_opcode;
1095 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1096 break;
1097
1098 case ArchSpec::eCPU_ppc:
1099 case ArchSpec::eCPU_ppc64:
1100 trap_opcode = g_ppc_breakpoint_opcode;
1101 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
1102 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001103
Greg Claytoncf015052010-06-11 03:25:34 +00001104 default:
1105 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
1106 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001107 }
1108
1109 if (trap_opcode && trap_opcode_size)
1110 {
1111 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1112 return trap_opcode_size;
1113 }
1114 return 0;
1115}
1116
1117uint32_t
1118ProcessGDBRemote::UpdateThreadListIfNeeded ()
1119{
1120 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001121 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001122 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001123 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1124
Greg Clayton5205f0b2010-09-03 17:10:42 +00001125 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001126 const uint32_t stop_id = GetStopID();
1127 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1128 {
1129 // Update the thread list's stop id immediately so we don't recurse into this function.
1130 ThreadList curr_thread_list (this);
1131 curr_thread_list.SetStopID(stop_id);
1132
1133 Error err;
1134 StringExtractorGDBRemote response;
1135 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
1136 response.IsNormalPacket();
1137 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
1138 {
1139 char ch = response.GetChar();
1140 if (ch == 'l')
1141 break;
1142 if (ch == 'm')
1143 {
1144 do
1145 {
1146 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1147
1148 if (tid != LLDB_INVALID_THREAD_ID)
1149 {
1150 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001151 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001152 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1153 curr_thread_list.AddThread(thread_sp);
1154 }
1155
1156 ch = response.GetChar();
1157 } while (ch == ',');
1158 }
1159 }
1160
1161 m_thread_list = curr_thread_list;
1162
1163 SetThreadStopInfo (m_last_stop_packet);
1164 }
1165 return GetThreadList().GetSize(false);
1166}
1167
1168
1169StateType
1170ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1171{
1172 const char stop_type = stop_packet.GetChar();
1173 switch (stop_type)
1174 {
1175 case 'T':
1176 case 'S':
1177 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001178 if (GetStopID() == 0)
1179 {
1180 // Our first stop, make sure we have a process ID, and also make
1181 // sure we know about our registers
1182 if (GetID() == LLDB_INVALID_PROCESS_ID)
1183 {
1184 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (1);
1185 if (pid != LLDB_INVALID_PROCESS_ID)
1186 SetID (pid);
1187 }
1188 BuildDynamicRegisterInfo (true);
1189 }
Chris Lattner24943d22010-06-08 16:52:24 +00001190 // Stop with signal and thread info
1191 const uint8_t signo = stop_packet.GetHexU8();
1192 std::string name;
1193 std::string value;
1194 std::string thread_name;
1195 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001196 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001197 uint32_t tid = LLDB_INVALID_THREAD_ID;
1198 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1199 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001200 ThreadSP thread_sp;
1201
Chris Lattner24943d22010-06-08 16:52:24 +00001202 while (stop_packet.GetNameColonValue(name, value))
1203 {
1204 if (name.compare("metype") == 0)
1205 {
1206 // exception type in big endian hex
1207 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1208 }
1209 else if (name.compare("mecount") == 0)
1210 {
1211 // exception count in big endian hex
1212 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1213 }
1214 else if (name.compare("medata") == 0)
1215 {
1216 // exception data in big endian hex
1217 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1218 }
1219 else if (name.compare("thread") == 0)
1220 {
1221 // thread in big endian hex
1222 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001223 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001224 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001225 if (!thread_sp)
1226 {
1227 // Create the thread if we need to
1228 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1229 m_thread_list.AddThread(thread_sp);
1230 }
Chris Lattner24943d22010-06-08 16:52:24 +00001231 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001232 else if (name.compare("hexname") == 0)
1233 {
1234 StringExtractor name_extractor;
1235 // Swap "value" over into "name_extractor"
1236 name_extractor.GetStringRef().swap(value);
1237 // Now convert the HEX bytes into a string value
1238 name_extractor.GetHexByteString (value);
1239 thread_name.swap (value);
1240 }
Chris Lattner24943d22010-06-08 16:52:24 +00001241 else if (name.compare("name") == 0)
1242 {
1243 thread_name.swap (value);
1244 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001245 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001246 {
1247 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1248 }
Greg Claytona875b642011-01-09 21:07:35 +00001249 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1250 {
1251 // We have a register number that contains an expedited
1252 // register value. Lets supply this register to our thread
1253 // so it won't have to go and read it.
1254 if (thread_sp)
1255 {
1256 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1257
1258 if (reg != UINT32_MAX)
1259 {
1260 StringExtractor reg_value_extractor;
1261 // Swap "value" over into "reg_value_extractor"
1262 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001263 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1264 {
1265 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1266 name.c_str(),
1267 reg,
1268 reg,
1269 reg_value_extractor.GetStringRef().c_str(),
1270 stop_packet.GetStringRef().c_str());
1271 }
Greg Claytona875b642011-01-09 21:07:35 +00001272 }
1273 }
1274 }
Chris Lattner24943d22010-06-08 16:52:24 +00001275 }
Chris Lattner24943d22010-06-08 16:52:24 +00001276
1277 if (thread_sp)
1278 {
1279 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1280
1281 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001282 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001283 if (exc_type != 0)
1284 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001285 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001286
1287 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1288 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001289 exc_data_size,
1290 exc_data_size >= 1 ? exc_data[0] : 0,
1291 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001292 }
1293 else if (signo)
1294 {
Greg Clayton643ee732010-08-04 01:40:35 +00001295 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001296 }
1297 else
1298 {
Greg Clayton643ee732010-08-04 01:40:35 +00001299 StopInfoSP invalid_stop_info_sp;
1300 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001301 }
1302 }
1303 return eStateStopped;
1304 }
1305 break;
1306
1307 case 'W':
1308 // process exited
1309 return eStateExited;
1310
1311 default:
1312 break;
1313 }
1314 return eStateInvalid;
1315}
1316
1317void
1318ProcessGDBRemote::RefreshStateAfterStop ()
1319{
Jim Ingham7508e732010-08-09 23:31:02 +00001320 // FIXME - add a variable to tell that we're in the middle of attaching if we
1321 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001322 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001323// if (!GetTarget().GetArchitecture().IsValid())
1324// {
1325// Module *exe_module = GetTarget().GetExecutableModule().get();
1326// if (exe_module)
1327// m_arch_spec = exe_module->GetArchitecture();
1328// }
1329
Chris Lattner24943d22010-06-08 16:52:24 +00001330 // Let all threads recover from stopping and do any clean up based
1331 // on the previous thread state (if any).
1332 m_thread_list.RefreshStateAfterStop();
1333
1334 // Discover new threads:
1335 UpdateThreadListIfNeeded ();
1336}
1337
1338Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001339ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001340{
1341 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001342
Greg Claytona4881d02011-01-22 07:12:45 +00001343 bool timed_out = false;
1344 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001345
1346 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001347 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001348 // We are being asked to halt during an attach. We need to just close
1349 // our file handle and debugserver will go away, and we can be done...
1350 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001351 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001352 else
1353 {
1354 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1355 {
1356 if (timed_out)
1357 error.SetErrorString("timed out sending interrupt packet");
1358 else
1359 error.SetErrorString("unknown error sending interrupt packet");
1360 }
1361 }
Chris Lattner24943d22010-06-08 16:52:24 +00001362 return error;
1363}
1364
1365Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001366ProcessGDBRemote::InterruptIfRunning
1367(
1368 bool discard_thread_plans,
1369 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001370 EventSP &stop_event_sp
1371)
Chris Lattner24943d22010-06-08 16:52:24 +00001372{
1373 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001374
Greg Clayton2860ba92011-01-23 19:58:49 +00001375 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1376
Greg Clayton68ca8232011-01-25 02:58:48 +00001377 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001378 const bool is_running = m_gdb_comm.IsRunning();
1379 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001380 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001381 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001382 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001383 is_running);
1384
Greg Clayton2860ba92011-01-23 19:58:49 +00001385 if (discard_thread_plans)
1386 {
1387 if (log)
1388 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1389 m_thread_list.DiscardThreadPlans();
1390 }
1391 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001392 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001393 if (catch_stop_event)
1394 {
1395 if (log)
1396 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1397 PausePrivateStateThread();
1398 paused_private_state_thread = true;
1399 }
1400
Greg Clayton4fb400f2010-09-27 21:07:38 +00001401 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001402 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001403 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001404
Greg Clayton72e1c782011-01-22 23:43:18 +00001405 //m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1406 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001407 {
1408 if (timed_out)
1409 error.SetErrorString("timed out sending interrupt packet");
1410 else
1411 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001412 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001413 ResumePrivateStateThread();
1414 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001415 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001416
Greg Clayton72e1c782011-01-22 23:43:18 +00001417 if (catch_stop_event)
1418 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001419 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001420 TimeValue timeout_time;
1421 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001422 timeout_time.OffsetWithSeconds(5);
1423 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001424
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001425 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001426 if (log)
1427 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001428
Greg Clayton2860ba92011-01-23 19:58:49 +00001429 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001430 error.SetErrorString("unable to verify target stopped");
1431 }
1432
Greg Clayton68ca8232011-01-25 02:58:48 +00001433 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001434 {
1435 if (log)
1436 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001437 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001438 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001439 }
Chris Lattner24943d22010-06-08 16:52:24 +00001440 return error;
1441}
1442
Greg Clayton4fb400f2010-09-27 21:07:38 +00001443Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001444ProcessGDBRemote::WillDetach ()
1445{
Greg Clayton2860ba92011-01-23 19:58:49 +00001446 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1447 if (log)
1448 log->Printf ("ProcessGDBRemote::WillDetach()");
1449
Greg Clayton72e1c782011-01-22 23:43:18 +00001450 bool discard_thread_plans = true;
1451 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001452 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001453 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001454}
1455
1456Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001457ProcessGDBRemote::DoDetach()
1458{
1459 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001460 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001461 if (log)
1462 log->Printf ("ProcessGDBRemote::DoDetach()");
1463
1464 DisableAllBreakpointSites ();
1465
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001466 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001467
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001468 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1469 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001470 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001471 if (response_size)
1472 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1473 else
1474 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001475 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001476 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001477 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001478
Greg Clayton4fb400f2010-09-27 21:07:38 +00001479 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001480 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001481
1482 SetPrivateState (eStateDetached);
1483 ResumePrivateStateThread();
1484
1485 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001486 return error;
1487}
Chris Lattner24943d22010-06-08 16:52:24 +00001488
1489Error
1490ProcessGDBRemote::DoDestroy ()
1491{
1492 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001493 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001494 if (log)
1495 log->Printf ("ProcessGDBRemote::DoDestroy()");
1496
1497 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001498 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001499 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001500 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001501 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001502 // We are being asked to halt during an attach. We need to just close
1503 // our file handle and debugserver will go away, and we can be done...
1504 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001505 }
1506 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001507 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001508
1509 StringExtractorGDBRemote response;
1510 bool send_async = true;
1511 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, 2, send_async))
1512 {
1513 char packet_cmd = response.GetChar(0);
1514
1515 if (packet_cmd == 'W' || packet_cmd == 'X')
1516 {
1517 m_last_stop_packet = response;
1518 SetExitStatus(response.GetHexU8(), NULL);
1519 }
1520 }
1521 else
1522 {
1523 SetExitStatus(SIGABRT, NULL);
1524 //error.SetErrorString("kill packet failed");
1525 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001526 }
1527 }
Chris Lattner24943d22010-06-08 16:52:24 +00001528 StopAsyncThread ();
1529 m_gdb_comm.StopReadThread();
1530 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001531 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001532 return error;
1533}
1534
Chris Lattner24943d22010-06-08 16:52:24 +00001535//------------------------------------------------------------------
1536// Process Queries
1537//------------------------------------------------------------------
1538
1539bool
1540ProcessGDBRemote::IsAlive ()
1541{
Greg Clayton58e844b2010-12-08 05:08:21 +00001542 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001543}
1544
1545addr_t
1546ProcessGDBRemote::GetImageInfoAddress()
1547{
1548 if (!m_gdb_comm.IsRunning())
1549 {
1550 StringExtractorGDBRemote response;
1551 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1552 {
1553 if (response.IsNormalPacket())
1554 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1555 }
1556 }
1557 return LLDB_INVALID_ADDRESS;
1558}
1559
1560DynamicLoader *
1561ProcessGDBRemote::GetDynamicLoader()
1562{
1563 return m_dynamic_loader_ap.get();
1564}
1565
1566//------------------------------------------------------------------
1567// Process Memory
1568//------------------------------------------------------------------
1569size_t
1570ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1571{
1572 if (size > m_max_memory_size)
1573 {
1574 // Keep memory read sizes down to a sane limit. This function will be
1575 // called multiple times in order to complete the task by
1576 // lldb_private::Process so it is ok to do this.
1577 size = m_max_memory_size;
1578 }
1579
1580 char packet[64];
1581 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1582 assert (packet_len + 1 < sizeof(packet));
1583 StringExtractorGDBRemote response;
1584 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1585 {
1586 if (response.IsNormalPacket())
1587 {
1588 error.Clear();
1589 return response.GetHexBytes(buf, size, '\xdd');
1590 }
1591 else if (response.IsErrorPacket())
1592 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1593 else if (response.IsUnsupportedPacket())
1594 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1595 else
1596 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1597 }
1598 else
1599 {
1600 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1601 }
1602 return 0;
1603}
1604
1605size_t
1606ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1607{
1608 StreamString packet;
1609 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001610 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001611 StringExtractorGDBRemote response;
1612 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1613 {
1614 if (response.IsOKPacket())
1615 {
1616 error.Clear();
1617 return size;
1618 }
1619 else if (response.IsErrorPacket())
1620 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1621 else if (response.IsUnsupportedPacket())
1622 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1623 else
1624 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1625 }
1626 else
1627 {
1628 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1629 }
1630 return 0;
1631}
1632
1633lldb::addr_t
1634ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1635{
1636 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1637 if (allocated_addr == LLDB_INVALID_ADDRESS)
1638 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1639 else
1640 error.Clear();
1641 return allocated_addr;
1642}
1643
1644Error
1645ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1646{
1647 Error error;
1648 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1649 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1650 return error;
1651}
1652
1653
1654//------------------------------------------------------------------
1655// Process STDIO
1656//------------------------------------------------------------------
1657
1658size_t
1659ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1660{
1661 Mutex::Locker locker(m_stdio_mutex);
1662 size_t bytes_available = m_stdout_data.size();
1663 if (bytes_available > 0)
1664 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001665 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1666 if (log)
1667 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001668 if (bytes_available > buf_size)
1669 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001670 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001671 m_stdout_data.erase(0, buf_size);
1672 bytes_available = buf_size;
1673 }
1674 else
1675 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001676 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001677 m_stdout_data.clear();
1678
1679 //ResetEventBits(eBroadcastBitSTDOUT);
1680 }
1681 }
1682 return bytes_available;
1683}
1684
1685size_t
1686ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1687{
1688 // Can we get STDERR through the remote protocol?
1689 return 0;
1690}
1691
1692size_t
1693ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1694{
1695 if (m_stdio_communication.IsConnected())
1696 {
1697 ConnectionStatus status;
1698 m_stdio_communication.Write(src, src_len, status, NULL);
1699 }
1700 return 0;
1701}
1702
1703Error
1704ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1705{
1706 Error error;
1707 assert (bp_site != NULL);
1708
Greg Claytone005f2c2010-11-06 01:53:30 +00001709 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001710 user_id_t site_id = bp_site->GetID();
1711 const addr_t addr = bp_site->GetLoadAddress();
1712 if (log)
1713 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1714
1715 if (bp_site->IsEnabled())
1716 {
1717 if (log)
1718 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1719 return error;
1720 }
1721 else
1722 {
1723 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1724
1725 if (bp_site->HardwarePreferred())
1726 {
1727 // Try and set hardware breakpoint, and if that fails, fall through
1728 // and set a software breakpoint?
1729 }
1730
1731 if (m_z0_supported)
1732 {
1733 char packet[64];
1734 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1735 assert (packet_len + 1 < sizeof(packet));
1736 StringExtractorGDBRemote response;
1737 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1738 {
1739 if (response.IsUnsupportedPacket())
1740 {
1741 // Disable z packet support and try again
1742 m_z0_supported = 0;
1743 return EnableBreakpoint (bp_site);
1744 }
1745 else if (response.IsOKPacket())
1746 {
1747 bp_site->SetEnabled(true);
1748 bp_site->SetType (BreakpointSite::eExternal);
1749 return error;
1750 }
1751 else
1752 {
1753 uint8_t error_byte = response.GetError();
1754 if (error_byte)
1755 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1756 }
1757 }
1758 }
1759 else
1760 {
1761 return EnableSoftwareBreakpoint (bp_site);
1762 }
1763 }
1764
1765 if (log)
1766 {
1767 const char *err_string = error.AsCString();
1768 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1769 bp_site->GetLoadAddress(),
1770 err_string ? err_string : "NULL");
1771 }
1772 // We shouldn't reach here on a successful breakpoint enable...
1773 if (error.Success())
1774 error.SetErrorToGenericError();
1775 return error;
1776}
1777
1778Error
1779ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1780{
1781 Error error;
1782 assert (bp_site != NULL);
1783 addr_t addr = bp_site->GetLoadAddress();
1784 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001785 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001786 if (log)
1787 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1788
1789 if (bp_site->IsEnabled())
1790 {
1791 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1792
1793 if (bp_site->IsHardware())
1794 {
1795 // TODO: disable hardware breakpoint...
1796 }
1797 else
1798 {
1799 if (m_z0_supported)
1800 {
1801 char packet[64];
1802 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1803 assert (packet_len + 1 < sizeof(packet));
1804 StringExtractorGDBRemote response;
1805 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1806 {
1807 if (response.IsUnsupportedPacket())
1808 {
1809 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1810 }
1811 else if (response.IsOKPacket())
1812 {
1813 if (log)
1814 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1815 bp_site->SetEnabled(false);
1816 return error;
1817 }
1818 else
1819 {
1820 uint8_t error_byte = response.GetError();
1821 if (error_byte)
1822 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1823 }
1824 }
1825 }
1826 else
1827 {
1828 return DisableSoftwareBreakpoint (bp_site);
1829 }
1830 }
1831 }
1832 else
1833 {
1834 if (log)
1835 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1836 return error;
1837 }
1838
1839 if (error.Success())
1840 error.SetErrorToGenericError();
1841 return error;
1842}
1843
1844Error
1845ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1846{
1847 Error error;
1848 if (wp)
1849 {
1850 user_id_t watchID = wp->GetID();
1851 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001852 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001853 if (log)
1854 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1855 if (wp->IsEnabled())
1856 {
1857 if (log)
1858 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1859 return error;
1860 }
1861 else
1862 {
1863 // Pass down an appropriate z/Z packet...
1864 error.SetErrorString("watchpoints not supported");
1865 }
1866 }
1867 else
1868 {
1869 error.SetErrorString("Watchpoint location argument was NULL.");
1870 }
1871 if (error.Success())
1872 error.SetErrorToGenericError();
1873 return error;
1874}
1875
1876Error
1877ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1878{
1879 Error error;
1880 if (wp)
1881 {
1882 user_id_t watchID = wp->GetID();
1883
Greg Claytone005f2c2010-11-06 01:53:30 +00001884 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001885
1886 addr_t addr = wp->GetLoadAddress();
1887 if (log)
1888 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1889
1890 if (wp->IsHardware())
1891 {
1892 // Pass down an appropriate z/Z packet...
1893 error.SetErrorString("watchpoints not supported");
1894 }
1895 // TODO: clear software watchpoints if we implement them
1896 }
1897 else
1898 {
1899 error.SetErrorString("Watchpoint location argument was NULL.");
1900 }
1901 if (error.Success())
1902 error.SetErrorToGenericError();
1903 return error;
1904}
1905
1906void
1907ProcessGDBRemote::Clear()
1908{
1909 m_flags = 0;
1910 m_thread_list.Clear();
1911 {
1912 Mutex::Locker locker(m_stdio_mutex);
1913 m_stdout_data.clear();
1914 }
Chris Lattner24943d22010-06-08 16:52:24 +00001915}
1916
1917Error
1918ProcessGDBRemote::DoSignal (int signo)
1919{
1920 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001921 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001922 if (log)
1923 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1924
1925 if (!m_gdb_comm.SendAsyncSignal (signo))
1926 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1927 return error;
1928}
1929
Chris Lattner24943d22010-06-08 16:52:24 +00001930Error
1931ProcessGDBRemote::StartDebugserverProcess
1932(
1933 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1934 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1935 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Claytonde915be2011-01-23 05:56:20 +00001936 const char *stdin_path,
1937 const char *stdout_path,
1938 const char *stderr_path,
1939 const char *working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001940 bool launch_process, // Set to true if we are going to be launching a the process
1941 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 +00001942 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1943 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001944 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001945 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1946)
1947{
1948 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001949 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1950 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001951 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1952 {
1953 // If we locate debugserver, keep that located version around
1954 static FileSpec g_debugserver_file_spec;
1955
1956 FileSpec debugserver_file_spec;
1957 char debugserver_path[PATH_MAX];
1958
1959 // Always check to see if we have an environment override for the path
1960 // to the debugserver to use and use it if we do.
1961 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1962 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001963 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001964 else
1965 debugserver_file_spec = g_debugserver_file_spec;
1966 bool debugserver_exists = debugserver_file_spec.Exists();
1967 if (!debugserver_exists)
1968 {
1969 // The debugserver binary is in the LLDB.framework/Resources
1970 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001971 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001972 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001973 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001974 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001975 if (debugserver_exists)
1976 {
1977 g_debugserver_file_spec = debugserver_file_spec;
1978 }
1979 else
1980 {
1981 g_debugserver_file_spec.Clear();
1982 debugserver_file_spec.Clear();
1983 }
Chris Lattner24943d22010-06-08 16:52:24 +00001984 }
1985 }
1986
1987 if (debugserver_exists)
1988 {
1989 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1990
1991 m_stdio_communication.Clear();
1992 posix_spawnattr_t attr;
1993
Greg Claytone005f2c2010-11-06 01:53:30 +00001994 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001995
1996 Error local_err; // Errors that don't affect the spawning.
1997 if (log)
1998 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1999 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
2000 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002001 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00002002 if (error.Fail())
2003 return error;;
2004
2005#if !defined (__arm__)
2006
Greg Clayton24b48ff2010-10-17 22:03:32 +00002007 // We don't need to do this for ARM, and we really shouldn't now
2008 // that we have multiple CPU subtypes and no posix_spawnattr call
2009 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00002010 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00002011 {
Greg Claytoncf015052010-06-11 03:25:34 +00002012 cpu_type_t cpu = inferior_arch.GetCPUType();
2013 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
2014 {
2015 size_t ocount = 0;
2016 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
2017 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002018 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 +00002019
Greg Claytoncf015052010-06-11 03:25:34 +00002020 if (error.Fail() != 0 || ocount != 1)
2021 return error;
2022 }
Chris Lattner24943d22010-06-08 16:52:24 +00002023 }
2024
2025#endif
2026
2027 Args debugserver_args;
2028 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002029
Chris Lattner24943d22010-06-08 16:52:24 +00002030 lldb_utility::PseudoTerminal pty;
Greg Claytonde915be2011-01-23 05:56:20 +00002031 const char *stdio_path = NULL;
2032 if (launch_process &&
Caroline Ticee4450f02011-01-28 00:19:58 +00002033 (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) &&
Greg Claytonde915be2011-01-23 05:56:20 +00002034 m_local_debugserver &&
2035 no_stdio == false)
Chris Lattner24943d22010-06-08 16:52:24 +00002036 {
Chris Lattner24943d22010-06-08 16:52:24 +00002037 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Caroline Ticee4450f02011-01-28 00:19:58 +00002038 {
2039 const char *slave_name = pty.GetSlaveName (NULL, 0);
2040 if (stdin_path == NULL
2041 && stdout_path == NULL
2042 && stderr_path == NULL)
2043 stdio_path = slave_name;
2044 else
2045 {
2046 if (stdin_path == NULL)
2047 stdin_path = slave_name;
2048 if (stdout_path == NULL)
2049 stdout_path = slave_name;
2050 if (stderr_path == NULL)
2051 stderr_path = slave_name;
2052 }
2053 }
Chris Lattner24943d22010-06-08 16:52:24 +00002054 }
2055
2056 // Start args with "debugserver /file/path -r --"
2057 debugserver_args.AppendArgument(debugserver_path);
2058 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002059 // use native registers, not the GDB registers
2060 debugserver_args.AppendArgument("--native-regs");
2061 // make debugserver run in its own session so signals generated by
2062 // special terminal key sequences (^C) don't affect debugserver
2063 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002064
Greg Clayton452bf612010-08-31 18:35:14 +00002065 if (disable_aslr)
2066 debugserver_args.AppendArguments("--disable-aslr");
2067
Chris Lattner24943d22010-06-08 16:52:24 +00002068 // Only set the inferior
Greg Claytonde915be2011-01-23 05:56:20 +00002069 if (launch_process)
Chris Lattner24943d22010-06-08 16:52:24 +00002070 {
Greg Claytonde915be2011-01-23 05:56:20 +00002071 if (no_stdio)
2072 debugserver_args.AppendArgument("--no-stdio");
2073 else
2074 {
2075 if (stdin_path && stdout_path && stderr_path &&
2076 strcmp(stdin_path, stdout_path) == 0 &&
2077 strcmp(stdin_path, stderr_path) == 0)
2078 {
2079 stdio_path = stdin_path;
2080 stdin_path = stdout_path = stderr_path = NULL;
2081 }
2082
2083 if (stdio_path)
2084 {
2085 // All file handles to stdin, stdout, stderr are the same...
2086 debugserver_args.AppendArgument("--stdio-path");
2087 debugserver_args.AppendArgument(stdio_path);
2088 }
2089 else
2090 {
2091 if (stdin_path == NULL && (stdout_path || stderr_path))
2092 stdin_path = "/dev/null";
2093
2094 if (stdout_path == NULL && (stdin_path || stderr_path))
2095 stdout_path = "/dev/null";
2096
2097 if (stderr_path == NULL && (stdin_path || stdout_path))
2098 stderr_path = "/dev/null";
2099
2100 if (stdin_path)
2101 {
2102 debugserver_args.AppendArgument("--stdin-path");
2103 debugserver_args.AppendArgument(stdin_path);
2104 }
2105 if (stdout_path)
2106 {
2107 debugserver_args.AppendArgument("--stdout-path");
2108 debugserver_args.AppendArgument(stdout_path);
2109 }
2110 if (stderr_path)
2111 {
2112 debugserver_args.AppendArgument("--stderr-path");
2113 debugserver_args.AppendArgument(stderr_path);
2114 }
2115 }
2116 }
Chris Lattner24943d22010-06-08 16:52:24 +00002117 }
Greg Claytonde915be2011-01-23 05:56:20 +00002118
2119 if (working_dir)
Caroline Ticebd666012010-12-03 18:46:09 +00002120 {
Greg Claytonde915be2011-01-23 05:56:20 +00002121 debugserver_args.AppendArgument("--working-dir");
2122 debugserver_args.AppendArgument(working_dir);
Caroline Ticebd666012010-12-03 18:46:09 +00002123 }
Chris Lattner24943d22010-06-08 16:52:24 +00002124
2125 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2126 if (env_debugserver_log_file)
2127 {
2128 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2129 debugserver_args.AppendArgument(arg_cstr);
2130 }
2131
2132 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2133 if (env_debugserver_log_flags)
2134 {
2135 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2136 debugserver_args.AppendArgument(arg_cstr);
2137 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002138// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002139// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002140
2141 // Now append the program arguments
2142 if (launch_process)
2143 {
2144 if (inferior_argv)
2145 {
2146 // Terminate the debugserver args so we can now append the inferior args
2147 debugserver_args.AppendArgument("--");
2148
2149 for (int i = 0; inferior_argv[i] != NULL; ++i)
2150 debugserver_args.AppendArgument (inferior_argv[i]);
2151 }
2152 else
2153 {
2154 // Will send environment entries with the 'QEnvironment:' packet
2155 // Will send arguments with the 'A' packet
2156 }
2157 }
2158 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2159 {
2160 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2161 debugserver_args.AppendArgument (arg_cstr);
2162 }
2163 else if (attach_name && attach_name[0])
2164 {
2165 if (wait_for_launch)
2166 debugserver_args.AppendArgument ("--waitfor");
2167 else
2168 debugserver_args.AppendArgument ("--attach");
2169 debugserver_args.AppendArgument (attach_name);
2170 }
2171
2172 Error file_actions_err;
2173 posix_spawn_file_actions_t file_actions;
2174#if DONT_CLOSE_DEBUGSERVER_STDIO
2175 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
2176#else
2177 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
2178 if (file_actions_err.Success())
2179 {
2180 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
2181 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
2182 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
2183 }
2184#endif
2185
2186 if (log)
2187 {
2188 StreamString strm;
2189 debugserver_args.Dump (&strm);
2190 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2191 }
2192
Greg Clayton72e1c782011-01-22 23:43:18 +00002193 error.SetError (::posix_spawnp (&m_debugserver_pid,
2194 debugserver_path,
2195 file_actions_err.Success() ? &file_actions : NULL,
2196 &attr,
2197 debugserver_args.GetArgumentVector(),
2198 (char * const*)inferior_envp),
2199 eErrorTypePOSIX);
2200
Greg Claytone9d0df42010-07-02 01:29:13 +00002201
2202 ::posix_spawnattr_destroy (&attr);
2203
Chris Lattner24943d22010-06-08 16:52:24 +00002204 if (file_actions_err.Success())
2205 ::posix_spawn_file_actions_destroy (&file_actions);
2206
2207 // We have seen some cases where posix_spawnp was returning a valid
2208 // looking pid even when an error was returned, so clear it out
2209 if (error.Fail())
2210 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2211
2212 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002213 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 +00002214
Caroline Ticebd666012010-12-03 18:46:09 +00002215 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00002216 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00002217 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00002218 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00002219 }
Chris Lattner24943d22010-06-08 16:52:24 +00002220 }
2221 else
2222 {
2223 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2224 }
2225
2226 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2227 StartAsyncThread ();
2228 }
2229 return error;
2230}
2231
2232bool
2233ProcessGDBRemote::MonitorDebugserverProcess
2234(
2235 void *callback_baton,
2236 lldb::pid_t debugserver_pid,
2237 int signo, // Zero for no signal
2238 int exit_status // Exit value of process if signal is zero
2239)
2240{
2241 // We pass in the ProcessGDBRemote inferior process it and name it
2242 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2243 // pointer value itself, thus we need the double cast...
2244
2245 // "debugserver_pid" argument passed in is the process ID for
2246 // debugserver that we are tracking...
2247
Greg Clayton75ccf502010-08-21 02:22:51 +00002248 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002249
2250 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2251 if (log)
2252 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2253
Greg Clayton75ccf502010-08-21 02:22:51 +00002254 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002255 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002256 // Sleep for a half a second to make sure our inferior process has
2257 // time to set its exit status before we set it incorrectly when
2258 // both the debugserver and the inferior process shut down.
2259 usleep (500000);
2260 // If our process hasn't yet exited, debugserver might have died.
2261 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002262 const StateType state = process->GetState();
2263
2264 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2265 state != eStateInvalid &&
2266 state != eStateUnloaded &&
2267 state != eStateExited &&
2268 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002269 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002270 char error_str[1024];
2271 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002272 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002273 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2274 if (signal_cstr)
2275 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002276 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002277 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002278 }
2279 else
2280 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002281 ::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 +00002282 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002283
2284 process->SetExitStatus (-1, error_str);
2285 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002286 // Debugserver has exited we need to let our ProcessGDBRemote
2287 // know that it no longer has a debugserver instance
2288 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2289 // We are returning true to this function below, so we can
2290 // forget about the monitor handle.
2291 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002292 }
2293 return true;
2294}
2295
2296void
2297ProcessGDBRemote::KillDebugserverProcess ()
2298{
2299 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2300 {
2301 ::kill (m_debugserver_pid, SIGINT);
2302 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2303 }
2304}
2305
2306void
2307ProcessGDBRemote::Initialize()
2308{
2309 static bool g_initialized = false;
2310
2311 if (g_initialized == false)
2312 {
2313 g_initialized = true;
2314 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2315 GetPluginDescriptionStatic(),
2316 CreateInstance);
2317
2318 Log::Callbacks log_callbacks = {
2319 ProcessGDBRemoteLog::DisableLog,
2320 ProcessGDBRemoteLog::EnableLog,
2321 ProcessGDBRemoteLog::ListLogCategories
2322 };
2323
2324 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2325 }
2326}
2327
2328bool
2329ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2330{
2331 if (m_curr_tid == tid)
2332 return true;
2333
2334 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002335 int packet_len;
2336 if (tid <= 0)
2337 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2338 else
2339 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002340 assert (packet_len + 1 < sizeof(packet));
2341 StringExtractorGDBRemote response;
2342 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2343 {
2344 if (response.IsOKPacket())
2345 {
2346 m_curr_tid = tid;
2347 return true;
2348 }
2349 }
2350 return false;
2351}
2352
2353bool
2354ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2355{
2356 if (m_curr_tid_run == tid)
2357 return true;
2358
2359 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002360 int packet_len;
2361 if (tid <= 0)
2362 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2363 else
2364 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2365
Chris Lattner24943d22010-06-08 16:52:24 +00002366 assert (packet_len + 1 < sizeof(packet));
2367 StringExtractorGDBRemote response;
2368 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2369 {
2370 if (response.IsOKPacket())
2371 {
2372 m_curr_tid_run = tid;
2373 return true;
2374 }
2375 }
2376 return false;
2377}
2378
2379void
2380ProcessGDBRemote::ResetGDBRemoteState ()
2381{
2382 // Reset and GDB remote state
2383 m_curr_tid = LLDB_INVALID_THREAD_ID;
2384 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2385 m_z0_supported = 1;
2386}
2387
2388
2389bool
2390ProcessGDBRemote::StartAsyncThread ()
2391{
2392 ResetGDBRemoteState ();
2393
Greg Claytone005f2c2010-11-06 01:53:30 +00002394 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002395
2396 if (log)
2397 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2398
2399 // Create a thread that watches our internal state and controls which
2400 // events make it to clients (into the DCProcess event queue).
2401 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002402 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002403}
2404
2405void
2406ProcessGDBRemote::StopAsyncThread ()
2407{
Greg Claytone005f2c2010-11-06 01:53:30 +00002408 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002409
2410 if (log)
2411 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2412
2413 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2414
2415 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002416 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002417 {
2418 Host::ThreadJoin (m_async_thread, NULL, NULL);
2419 }
2420}
2421
2422
2423void *
2424ProcessGDBRemote::AsyncThread (void *arg)
2425{
2426 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2427
Greg Claytone005f2c2010-11-06 01:53:30 +00002428 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002429 if (log)
2430 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2431
2432 Listener listener ("ProcessGDBRemote::AsyncThread");
2433 EventSP event_sp;
2434 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2435 eBroadcastBitAsyncThreadShouldExit;
2436
2437 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2438 {
2439 bool done = false;
2440 while (!done)
2441 {
2442 if (log)
2443 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2444 if (listener.WaitForEvent (NULL, event_sp))
2445 {
2446 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002447 if (log)
2448 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2449
Chris Lattner24943d22010-06-08 16:52:24 +00002450 switch (event_type)
2451 {
2452 case eBroadcastBitAsyncContinue:
2453 {
2454 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2455
2456 if (continue_packet)
2457 {
2458 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2459 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2460 if (log)
2461 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2462
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002463 if (::strstr (continue_cstr, "vAttach") == NULL)
2464 process->SetPrivateState(eStateRunning);
Chris Lattner24943d22010-06-08 16:52:24 +00002465 StringExtractorGDBRemote response;
2466 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2467
2468 switch (stop_state)
2469 {
2470 case eStateStopped:
2471 case eStateCrashed:
2472 case eStateSuspended:
2473 process->m_last_stop_packet = response;
2474 process->m_last_stop_packet.SetFilePos (0);
2475 process->SetPrivateState (stop_state);
2476 break;
2477
2478 case eStateExited:
2479 process->m_last_stop_packet = response;
2480 process->m_last_stop_packet.SetFilePos (0);
2481 response.SetFilePos(1);
2482 process->SetExitStatus(response.GetHexU8(), NULL);
2483 done = true;
2484 break;
2485
2486 case eStateInvalid:
2487 break;
2488
2489 default:
2490 process->SetPrivateState (stop_state);
2491 break;
2492 }
2493 }
2494 }
2495 break;
2496
2497 case eBroadcastBitAsyncThreadShouldExit:
2498 if (log)
2499 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2500 done = true;
2501 break;
2502
2503 default:
2504 if (log)
2505 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2506 done = true;
2507 break;
2508 }
2509 }
2510 else
2511 {
2512 if (log)
2513 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2514 done = true;
2515 }
2516 }
2517 }
2518
2519 if (log)
2520 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2521
2522 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2523 return NULL;
2524}
2525
Chris Lattner24943d22010-06-08 16:52:24 +00002526const char *
2527ProcessGDBRemote::GetDispatchQueueNameForThread
2528(
2529 addr_t thread_dispatch_qaddr,
2530 std::string &dispatch_queue_name
2531)
2532{
2533 dispatch_queue_name.clear();
2534 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2535 {
2536 // Cache the dispatch_queue_offsets_addr value so we don't always have
2537 // to look it up
2538 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2539 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002540 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2541 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002542 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002543 if (module_sp)
2544 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2545
2546 if (dispatch_queue_offsets_symbol == NULL)
2547 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002548 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002549 if (module_sp)
2550 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2551 }
Chris Lattner24943d22010-06-08 16:52:24 +00002552 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002553 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002554
2555 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2556 return NULL;
2557 }
2558
2559 uint8_t memory_buffer[8];
2560 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize());
2561
2562 // Excerpt from src/queue_private.h
2563 struct dispatch_queue_offsets_s
2564 {
2565 uint16_t dqo_version;
2566 uint16_t dqo_label;
2567 uint16_t dqo_label_size;
2568 } dispatch_queue_offsets;
2569
2570
2571 Error error;
2572 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2573 {
2574 uint32_t data_offset = 0;
2575 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2576 {
2577 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2578 {
2579 data_offset = 0;
2580 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2581 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2582 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2583 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2584 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2585 dispatch_queue_name.erase (bytes_read);
2586 }
2587 }
2588 }
2589 }
2590 if (dispatch_queue_name.empty())
2591 return NULL;
2592 return dispatch_queue_name.c_str();
2593}
2594
Jim Ingham7508e732010-08-09 23:31:02 +00002595uint32_t
2596ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2597{
2598 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2599 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2600 if (m_local_debugserver)
2601 {
2602 return Host::ListProcessesMatchingName (name, matches, pids);
2603 }
2604 else
2605 {
2606 // FIXME: Implement talking to the remote debugserver.
2607 return 0;
2608 }
2609
2610}
Jim Ingham55e01d82011-01-22 01:33:44 +00002611
2612bool
2613ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2614 lldb_private::StoppointCallbackContext *context,
2615 lldb::user_id_t break_id,
2616 lldb::user_id_t break_loc_id)
2617{
2618 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2619 // run so I can stop it if that's what I want to do.
2620 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2621 if (log)
2622 log->Printf("Hit New Thread Notification breakpoint.");
2623 return false;
2624}
2625
2626
2627bool
2628ProcessGDBRemote::StartNoticingNewThreads()
2629{
2630 static const char *bp_names[] =
2631 {
2632 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002633 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002634 "_pthread_start",
2635 NULL
2636 };
2637
2638 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2639 size_t num_bps = m_thread_observation_bps.size();
2640 if (num_bps != 0)
2641 {
2642 for (int i = 0; i < num_bps; i++)
2643 {
2644 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2645 if (break_sp)
2646 {
2647 if (log)
2648 log->Printf("Enabled noticing new thread breakpoint.");
2649 break_sp->SetEnabled(true);
2650 }
2651 }
2652 }
2653 else
2654 {
2655 for (int i = 0; bp_names[i] != NULL; i++)
2656 {
2657 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2658 if (breakpoint)
2659 {
2660 if (log)
2661 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2662 m_thread_observation_bps.push_back(breakpoint->GetID());
2663 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2664 }
2665 else
2666 {
2667 if (log)
2668 log->Printf("Failed to create new thread notification breakpoint.");
2669 return false;
2670 }
2671 }
2672 }
2673
2674 return true;
2675}
2676
2677bool
2678ProcessGDBRemote::StopNoticingNewThreads()
2679{
Jim Inghamff276fe2011-02-08 05:19:01 +00002680 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2681 if (log)
2682 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002683 size_t num_bps = m_thread_observation_bps.size();
2684 if (num_bps != 0)
2685 {
2686 for (int i = 0; i < num_bps; i++)
2687 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002688
2689 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2690 if (break_sp)
2691 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002692 break_sp->SetEnabled(false);
2693 }
2694 }
2695 }
2696 return true;
2697}
2698
2699