blob: df3e09a99884a522958f37697072efe52e415346 [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),
Chris Lattner24943d22010-06-08 16:52:24 +0000104 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000105 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner24943d22010-06-08 16:52:24 +0000106 m_gdb_comm(),
107 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000108 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000109 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000110 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000111 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
112 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000113 m_curr_tid (LLDB_INVALID_THREAD_ID),
114 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Chris Lattner24943d22010-06-08 16:52:24 +0000115 m_z0_supported (1),
Greg Claytonc1f45872011-02-12 06:28:37 +0000116 m_continue_c_tids (),
117 m_continue_C_tids (),
118 m_continue_s_tids (),
119 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000120 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000121 m_packet_timeout (1),
122 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000123 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000124 m_local_debugserver (true),
125 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000126{
127}
128
129//----------------------------------------------------------------------
130// Destructor
131//----------------------------------------------------------------------
132ProcessGDBRemote::~ProcessGDBRemote()
133{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000134 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000135 {
136 Host::ThreadCancel (m_debugserver_thread, NULL);
137 thread_result_t thread_result;
138 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
139 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
140 }
Chris Lattner24943d22010-06-08 16:52:24 +0000141 // m_mach_process.UnregisterNotificationCallbacks (this);
142 Clear();
143}
144
145//----------------------------------------------------------------------
146// PluginInterface
147//----------------------------------------------------------------------
148const char *
149ProcessGDBRemote::GetPluginName()
150{
151 return "Process debugging plug-in that uses the GDB remote protocol";
152}
153
154const char *
155ProcessGDBRemote::GetShortPluginName()
156{
157 return GetPluginNameStatic();
158}
159
160uint32_t
161ProcessGDBRemote::GetPluginVersion()
162{
163 return 1;
164}
165
166void
167ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm)
168{
169 strm->Printf("TODO: fill this in\n");
170}
171
172Error
173ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm)
174{
175 Error error;
176 error.SetErrorString("No plug-in commands are currently supported.");
177 return error;
178}
179
180Log *
181ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command)
182{
183 return NULL;
184}
185
186void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000187ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000188{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000189 if (!force && m_register_info.GetNumRegisters() > 0)
190 return;
191
192 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000193 m_register_info.Clear();
194 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse;
195 uint32_t reg_offset = 0;
196 uint32_t reg_num = 0;
197 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num)
198 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000199 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
200 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000201 StringExtractorGDBRemote response;
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000202 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000203 {
204 packet_type = response.GetType();
205 if (packet_type == StringExtractorGDBRemote::eResponse)
206 {
207 std::string name;
208 std::string value;
209 ConstString reg_name;
210 ConstString alt_name;
211 ConstString set_name;
212 RegisterInfo reg_info = { NULL, // Name
213 NULL, // Alt name
214 0, // byte size
215 reg_offset, // offset
216 eEncodingUint, // encoding
217 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000218 {
219 LLDB_INVALID_REGNUM, // GCC reg num
220 LLDB_INVALID_REGNUM, // DWARF reg num
221 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000222 reg_num, // GDB reg num
223 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000224 }
225 };
226
227 while (response.GetNameColonValue(name, value))
228 {
229 if (name.compare("name") == 0)
230 {
231 reg_name.SetCString(value.c_str());
232 }
233 else if (name.compare("alt-name") == 0)
234 {
235 alt_name.SetCString(value.c_str());
236 }
237 else if (name.compare("bitsize") == 0)
238 {
239 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
240 }
241 else if (name.compare("offset") == 0)
242 {
243 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000244 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000245 {
246 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000247 }
248 }
249 else if (name.compare("encoding") == 0)
250 {
251 if (value.compare("uint") == 0)
252 reg_info.encoding = eEncodingUint;
253 else if (value.compare("sint") == 0)
254 reg_info.encoding = eEncodingSint;
255 else if (value.compare("ieee754") == 0)
256 reg_info.encoding = eEncodingIEEE754;
257 else if (value.compare("vector") == 0)
258 reg_info.encoding = eEncodingVector;
259 }
260 else if (name.compare("format") == 0)
261 {
262 if (value.compare("binary") == 0)
263 reg_info.format = eFormatBinary;
264 else if (value.compare("decimal") == 0)
265 reg_info.format = eFormatDecimal;
266 else if (value.compare("hex") == 0)
267 reg_info.format = eFormatHex;
268 else if (value.compare("float") == 0)
269 reg_info.format = eFormatFloat;
270 else if (value.compare("vector-sint8") == 0)
271 reg_info.format = eFormatVectorOfSInt8;
272 else if (value.compare("vector-uint8") == 0)
273 reg_info.format = eFormatVectorOfUInt8;
274 else if (value.compare("vector-sint16") == 0)
275 reg_info.format = eFormatVectorOfSInt16;
276 else if (value.compare("vector-uint16") == 0)
277 reg_info.format = eFormatVectorOfUInt16;
278 else if (value.compare("vector-sint32") == 0)
279 reg_info.format = eFormatVectorOfSInt32;
280 else if (value.compare("vector-uint32") == 0)
281 reg_info.format = eFormatVectorOfUInt32;
282 else if (value.compare("vector-float32") == 0)
283 reg_info.format = eFormatVectorOfFloat32;
284 else if (value.compare("vector-uint128") == 0)
285 reg_info.format = eFormatVectorOfUInt128;
286 }
287 else if (name.compare("set") == 0)
288 {
289 set_name.SetCString(value.c_str());
290 }
291 else if (name.compare("gcc") == 0)
292 {
293 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
294 }
295 else if (name.compare("dwarf") == 0)
296 {
297 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
298 }
299 else if (name.compare("generic") == 0)
300 {
301 if (value.compare("pc") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
303 else if (value.compare("sp") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
305 else if (value.compare("fp") == 0)
306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
307 else if (value.compare("ra") == 0)
308 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
309 else if (value.compare("flags") == 0)
310 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
311 }
312 }
313
Jason Molenda53d96862010-06-11 23:44:18 +0000314 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000315 assert (reg_info.byte_size != 0);
316 reg_offset += reg_info.byte_size;
317 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
318 }
319 }
320 else
321 {
322 packet_type = StringExtractorGDBRemote::eError;
323 }
324 }
325
326 if (reg_num == 0)
327 {
328 // We didn't get anything. See if we are debugging ARM and fill with
329 // a hard coded register set until we can get an updated debugserver
330 // down on the devices.
331 ArchSpec arm_arch ("arm");
332 if (GetTarget().GetArchitecture() == arm_arch)
333 m_register_info.HardcodeARMRegisters();
334 }
335 m_register_info.Finalize ();
336}
337
338Error
339ProcessGDBRemote::WillLaunch (Module* module)
340{
341 return WillLaunchOrAttach ();
342}
343
344Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000345ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000346{
347 return WillLaunchOrAttach ();
348}
349
350Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000351ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000352{
353 return WillLaunchOrAttach ();
354}
355
356Error
Greg Claytone71e2582011-02-04 01:58:07 +0000357ProcessGDBRemote::DoConnectRemote (const char *remote_url)
358{
359 Error error (WillLaunchOrAttach ());
360
361 if (error.Fail())
362 return error;
363
364 if (strncmp (remote_url, "connect://", strlen ("connect://")) == 0)
365 {
366 error = ConnectToDebugserver (remote_url);
367 }
368 else
369 {
370 error.SetErrorStringWithFormat ("unsupported remote url: %s", remote_url);
371 }
372
373 if (error.Fail())
374 return error;
375 StartAsyncThread ();
376
377 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (m_packet_timeout);
378 if (pid == LLDB_INVALID_PROCESS_ID)
379 {
380 // We don't have a valid process ID, so note that we are connected
381 // and could now request to launch or attach, or get remote process
382 // listings...
383 SetPrivateState (eStateConnected);
384 }
385 else
386 {
387 // We have a valid process
388 SetID (pid);
389 StringExtractorGDBRemote response;
390 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
391 {
392 const StateType state = SetThreadStopInfo (response);
393 if (state == eStateStopped)
394 {
395 SetPrivateState (state);
396 }
397 else
398 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
399 }
400 else
401 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
402 }
403 return error;
404}
405
406Error
Chris Lattner24943d22010-06-08 16:52:24 +0000407ProcessGDBRemote::WillLaunchOrAttach ()
408{
409 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000410 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000411 return error;
412}
413
414//----------------------------------------------------------------------
415// Process Control
416//----------------------------------------------------------------------
417Error
418ProcessGDBRemote::DoLaunch
419(
420 Module* module,
421 char const *argv[],
422 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000423 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000424 const char *stdin_path,
425 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000426 const char *stderr_path,
427 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000428)
429{
Greg Clayton4b407112010-09-30 21:49:03 +0000430 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000431 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
432 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
433 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000434
435 ObjectFile * object_file = module->GetObjectFile();
436 if (object_file)
437 {
438 ArchSpec inferior_arch(module->GetArchitecture());
439 char host_port[128];
440 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000441 char connect_url[128];
442 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000443
Greg Clayton23cf0c72010-11-08 04:29:11 +0000444 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000445 bool start_debugserver_with_inferior_args = false;
446 if (start_debugserver_with_inferior_args)
447 {
448 // We want to launch debugserver with the inferior program and its
449 // arguments on the command line. We should only do this if we
450 // the GDB server we are talking to doesn't support the 'A' packet.
451 error = StartDebugserverProcess (host_port,
452 argv,
453 envp,
Greg Claytonde915be2011-01-23 05:56:20 +0000454 stdin_path,
455 stdout_path,
456 stderr_path,
457 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000458 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000459 LLDB_INVALID_PROCESS_ID,
460 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000461 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000462 inferior_arch);
463 if (error.Fail())
464 return error;
465
Greg Claytone71e2582011-02-04 01:58:07 +0000466 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000467 if (error.Success())
468 {
469 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
470 }
471 }
472 else
473 {
474 error = StartDebugserverProcess (host_port,
475 NULL,
476 NULL,
Greg Claytonde915be2011-01-23 05:56:20 +0000477 stdin_path,
478 stdout_path,
479 stderr_path,
480 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000481 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000482 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000483 NULL,
484 false,
Caroline Ticebd666012010-12-03 18:46:09 +0000485 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000486 inferior_arch);
487 if (error.Fail())
488 return error;
489
Greg Claytone71e2582011-02-04 01:58:07 +0000490 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000491 if (error.Success())
492 {
493 // Send the environment and the program + arguments after we connect
494 if (envp)
495 {
496 const char *env_entry;
497 for (int i=0; (env_entry = envp[i]); ++i)
498 {
499 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
500 break;
501 }
502 }
503
Greg Clayton960d6a42010-08-03 00:35:52 +0000504 // FIXME: convert this to use the new set/show variables when they are available
505#if 0
506 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
507 {
508 const uint32_t attach_debugserver_secs = 10;
509 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
510 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
511 {
512 printf ("%i\n", attach_debugserver_secs - i);
513 sleep (1);
514 }
515 }
516#endif
517
Chris Lattner24943d22010-06-08 16:52:24 +0000518 const uint32_t arg_timeout_seconds = 10;
519 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
520 if (arg_packet_err == 0)
521 {
522 std::string error_str;
523 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
524 {
525 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
526 }
527 else
528 {
529 error.SetErrorString (error_str.c_str());
530 }
531 }
532 else
533 {
534 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
535 }
536
537 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
538 }
539 }
540
541 if (GetID() == LLDB_INVALID_PROCESS_ID)
542 {
543 KillDebugserverProcess ();
544 return error;
545 }
546
547 StringExtractorGDBRemote response;
548 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
549 SetPrivateState (SetThreadStopInfo (response));
550
551 }
552 else
553 {
554 // Set our user ID to an invalid process ID.
555 SetID(LLDB_INVALID_PROCESS_ID);
556 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
557 }
Chris Lattner24943d22010-06-08 16:52:24 +0000558 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000559
Chris Lattner24943d22010-06-08 16:52:24 +0000560}
561
562
563Error
Greg Claytone71e2582011-02-04 01:58:07 +0000564ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000565{
566 Error error;
567 // Sleep and wait a bit for debugserver to start to listen...
568 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
569 if (conn_ap.get())
570 {
Chris Lattner24943d22010-06-08 16:52:24 +0000571 const uint32_t max_retry_count = 50;
572 uint32_t retry_count = 0;
573 while (!m_gdb_comm.IsConnected())
574 {
Greg Claytone71e2582011-02-04 01:58:07 +0000575 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000576 {
577 m_gdb_comm.SetConnection (conn_ap.release());
578 break;
579 }
580 retry_count++;
581
582 if (retry_count >= max_retry_count)
583 break;
584
585 usleep (100000);
586 }
587 }
588
589 if (!m_gdb_comm.IsConnected())
590 {
591 if (error.Success())
592 error.SetErrorString("not connected to remote gdb server");
593 return error;
594 }
595
Chris Lattner24943d22010-06-08 16:52:24 +0000596 if (m_gdb_comm.StartReadThread(&error))
597 {
598 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000599 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000600
601 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000602 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
603 this,
604 m_debugserver_pid,
605 false);
606
Greg Claytonc1f45872011-02-12 06:28:37 +0000607 m_gdb_comm.ResetDiscoverableSettings();
608 m_gdb_comm.GetSendAcks ();
609 m_gdb_comm.GetThreadSuffixSupported ();
610 m_gdb_comm.GetHostInfo ();
611 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000612 }
613 return error;
614}
615
616void
617ProcessGDBRemote::DidLaunchOrAttach ()
618{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000619 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
620 if (log)
621 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000622 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000623 {
624 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
625
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000626 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000627
Greg Clayton395fc332011-02-15 21:59:32 +0000628 m_target.GetArchitecture().SetByteOrder (m_gdb_comm.GetByteOrder());
Greg Clayton20d338f2010-11-18 05:57:03 +0000629
Chris Lattner24943d22010-06-08 16:52:24 +0000630 StreamString strm;
631
Chris Lattner24943d22010-06-08 16:52:24 +0000632 // See if the GDB server supports the qHostInfo information
633 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
634 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Claytonfc7920f2011-02-09 03:09:55 +0000635 ArchSpec target_arch (GetTarget().GetArchitecture());
636 ArchSpec gdb_remote_arch (m_gdb_comm.GetHostArchitecture());
637
Greg Claytonc62176d2011-02-09 03:12:09 +0000638 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytonfc7920f2011-02-09 03:09:55 +0000639 // ARM executables and shared libraries can have mixed ARM architectures.
640 // You can have an armv6 executable, and if the host is armv7, then the
641 // system will load the best possible architecture for all shared libraries
642 // it has, so we really need to take the remote host architecture as our
643 // defacto architecture in this case.
644
645 if (gdb_remote_arch == ArchSpec ("arm") &&
Greg Clayton395fc332011-02-15 21:59:32 +0000646 vendor && ::strcmp(vendor, "apple") == 0)
Greg Claytonfc7920f2011-02-09 03:09:55 +0000647 {
648 GetTarget().SetArchitecture (gdb_remote_arch);
649 target_arch = gdb_remote_arch;
650 }
651
Greg Clayton395fc332011-02-15 21:59:32 +0000652 if (vendor)
653 m_target.GetArchitecture().GetTriple().setVendorName(vendor);
654 if (os_type)
655 m_target.GetArchitecture().GetTriple().setOSName(os_type);
Chris Lattner24943d22010-06-08 16:52:24 +0000656 }
657}
658
659void
660ProcessGDBRemote::DidLaunch ()
661{
662 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000663}
664
665Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000666ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000667{
668 Error error;
669 // Clear out and clean up from any current state
670 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000671 ArchSpec arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000672
Chris Lattner24943d22010-06-08 16:52:24 +0000673 if (attach_pid != LLDB_INVALID_PROCESS_ID)
674 {
Chris Lattner24943d22010-06-08 16:52:24 +0000675 char host_port[128];
676 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000677 char connect_url[128];
678 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
679
Greg Clayton452bf612010-08-31 18:35:14 +0000680 error = StartDebugserverProcess (host_port, // debugserver_url
681 NULL, // inferior_argv
682 NULL, // inferior_envp
683 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000684 NULL, // stdout_path
685 NULL, // stderr_path
686 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000687 false, // launch_process == false (we are attaching)
688 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
689 NULL, // Don't send any attach by process name option to debugserver
690 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000691 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000692 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000693
694 if (error.Fail())
695 {
696 const char *error_string = error.AsCString();
697 if (error_string == NULL)
698 error_string = "unable to launch " DEBUGSERVER_BASENAME;
699
700 SetExitStatus (-1, error_string);
701 }
702 else
703 {
Greg Claytone71e2582011-02-04 01:58:07 +0000704 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000705 if (error.Success())
706 {
707 char packet[64];
708 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000709
710 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000711 }
712 }
713 }
Chris Lattner24943d22010-06-08 16:52:24 +0000714 return error;
715}
716
717size_t
718ProcessGDBRemote::AttachInputReaderCallback
719(
720 void *baton,
721 InputReader *reader,
722 lldb::InputReaderAction notification,
723 const char *bytes,
724 size_t bytes_len
725)
726{
727 if (notification == eInputReaderGotToken)
728 {
729 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
730 if (gdb_process->m_waiting_for_attach)
731 gdb_process->m_waiting_for_attach = false;
732 reader->SetIsDone(true);
733 return 1;
734 }
735 return 0;
736}
737
738Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000739ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000740{
741 Error error;
742 // Clear out and clean up from any current state
743 Clear();
744 // HACK: require arch be set correctly at the target level until we can
745 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000746
Chris Lattner24943d22010-06-08 16:52:24 +0000747 if (process_name && process_name[0])
748 {
Jim Ingham7508e732010-08-09 23:31:02 +0000749 ArchSpec arch_spec = GetTarget().GetArchitecture();
Greg Claytone71e2582011-02-04 01:58:07 +0000750
751 char host_port[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000752 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000753 char connect_url[128];
754 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
755
Greg Clayton452bf612010-08-31 18:35:14 +0000756 error = StartDebugserverProcess (host_port, // debugserver_url
757 NULL, // inferior_argv
758 NULL, // inferior_envp
759 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000760 NULL, // stdout_path
761 NULL, // stderr_path
762 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000763 false, // launch_process == false (we are attaching)
764 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
765 NULL, // Don't send any attach by process name option to debugserver
766 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000767 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000768 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000769 if (error.Fail())
770 {
771 const char *error_string = error.AsCString();
772 if (error_string == NULL)
773 error_string = "unable to launch " DEBUGSERVER_BASENAME;
774
775 SetExitStatus (-1, error_string);
776 }
777 else
778 {
Greg Claytone71e2582011-02-04 01:58:07 +0000779 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000780 if (error.Success())
781 {
782 StreamString packet;
783
Chris Lattner24943d22010-06-08 16:52:24 +0000784 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000785 packet.PutCString("vAttachWait");
786 else
787 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000788 packet.PutChar(';');
Greg Claytoncd548032011-02-01 01:31:41 +0000789 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000790
791 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
Chris Lattner24943d22010-06-08 16:52:24 +0000792
Chris Lattner24943d22010-06-08 16:52:24 +0000793 }
794 }
795 }
Chris Lattner24943d22010-06-08 16:52:24 +0000796 return error;
797}
798
Chris Lattner24943d22010-06-08 16:52:24 +0000799
800void
801ProcessGDBRemote::DidAttach ()
802{
Greg Claytone71e2582011-02-04 01:58:07 +0000803 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000804}
805
806Error
807ProcessGDBRemote::WillResume ()
808{
Greg Claytonc1f45872011-02-12 06:28:37 +0000809 m_continue_c_tids.clear();
810 m_continue_C_tids.clear();
811 m_continue_s_tids.clear();
812 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000813 return Error();
814}
815
816Error
817ProcessGDBRemote::DoResume ()
818{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000819 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000820 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
821 if (log)
822 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000823
824 Listener listener ("gdb-remote.resume-packet-sent");
825 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
826 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000827 StreamString continue_packet;
828 bool continue_packet_error = false;
829 if (m_gdb_comm.HasAnyVContSupport ())
830 {
831 continue_packet.PutCString ("vCont");
832
833 if (!m_continue_c_tids.empty())
834 {
835 if (m_gdb_comm.GetVContSupported ('c'))
836 {
837 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)
838 continue_packet.Printf(";c:%4.4x", *t_pos);
839 }
840 else
841 continue_packet_error = true;
842 }
843
844 if (!continue_packet_error && !m_continue_C_tids.empty())
845 {
846 if (m_gdb_comm.GetVContSupported ('C'))
847 {
848 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)
849 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
850 }
851 else
852 continue_packet_error = true;
853 }
Greg Claytonb749a262010-12-03 06:02:24 +0000854
Greg Claytonc1f45872011-02-12 06:28:37 +0000855 if (!continue_packet_error && !m_continue_s_tids.empty())
856 {
857 if (m_gdb_comm.GetVContSupported ('s'))
858 {
859 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)
860 continue_packet.Printf(";s:%4.4x", *t_pos);
861 }
862 else
863 continue_packet_error = true;
864 }
865
866 if (!continue_packet_error && !m_continue_S_tids.empty())
867 {
868 if (m_gdb_comm.GetVContSupported ('S'))
869 {
870 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)
871 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
872 }
873 else
874 continue_packet_error = true;
875 }
876
877 if (continue_packet_error)
878 continue_packet.GetString().clear();
879 }
880 else
881 continue_packet_error = true;
882
883 if (continue_packet_error)
884 {
885 continue_packet_error = false;
886 // Either no vCont support, or we tried to use part of the vCont
887 // packet that wasn't supported by the remote GDB server.
888 // We need to try and make a simple packet that can do our continue
889 const size_t num_threads = GetThreadList().GetSize();
890 const size_t num_continue_c_tids = m_continue_c_tids.size();
891 const size_t num_continue_C_tids = m_continue_C_tids.size();
892 const size_t num_continue_s_tids = m_continue_s_tids.size();
893 const size_t num_continue_S_tids = m_continue_S_tids.size();
894 if (num_continue_c_tids > 0)
895 {
896 if (num_continue_c_tids == num_threads)
897 {
898 // All threads are resuming...
899 SetCurrentGDBRemoteThreadForRun (-1);
900 continue_packet.PutChar ('c');
901 }
902 else if (num_continue_c_tids == 1 &&
903 num_continue_C_tids == 0 &&
904 num_continue_s_tids == 0 &&
905 num_continue_S_tids == 0 )
906 {
907 // Only one thread is continuing
908 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
909 continue_packet.PutChar ('c');
910 }
911 else
912 {
913 // We can't represent this continue packet....
914 continue_packet_error = true;
915 }
916 }
917
918 if (!continue_packet_error && num_continue_C_tids > 0)
919 {
920 if (num_continue_C_tids == num_threads)
921 {
922 const int continue_signo = m_continue_C_tids.front().second;
923 if (num_continue_C_tids > 1)
924 {
925 for (size_t i=1; i<num_threads; ++i)
926 {
927 if (m_continue_C_tids[i].second != continue_signo)
928 continue_packet_error = true;
929 }
930 }
931 if (!continue_packet_error)
932 {
933 // Add threads continuing with the same signo...
934 SetCurrentGDBRemoteThreadForRun (-1);
935 continue_packet.Printf("C%2.2x", continue_signo);
936 }
937 }
938 else if (num_continue_c_tids == 0 &&
939 num_continue_C_tids == 1 &&
940 num_continue_s_tids == 0 &&
941 num_continue_S_tids == 0 )
942 {
943 // Only one thread is continuing with signal
944 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
945 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
946 }
947 else
948 {
949 // We can't represent this continue packet....
950 continue_packet_error = true;
951 }
952 }
953
954 if (!continue_packet_error && num_continue_s_tids > 0)
955 {
956 if (num_continue_s_tids == num_threads)
957 {
958 // All threads are resuming...
959 SetCurrentGDBRemoteThreadForRun (-1);
960 continue_packet.PutChar ('s');
961 }
962 else if (num_continue_c_tids == 0 &&
963 num_continue_C_tids == 0 &&
964 num_continue_s_tids == 1 &&
965 num_continue_S_tids == 0 )
966 {
967 // Only one thread is stepping
968 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
969 continue_packet.PutChar ('s');
970 }
971 else
972 {
973 // We can't represent this continue packet....
974 continue_packet_error = true;
975 }
976 }
977
978 if (!continue_packet_error && num_continue_S_tids > 0)
979 {
980 if (num_continue_S_tids == num_threads)
981 {
982 const int step_signo = m_continue_S_tids.front().second;
983 // Are all threads trying to step with the same signal?
984 if (num_continue_S_tids > 1)
985 {
986 for (size_t i=1; i<num_threads; ++i)
987 {
988 if (m_continue_S_tids[i].second != step_signo)
989 continue_packet_error = true;
990 }
991 }
992 if (!continue_packet_error)
993 {
994 // Add threads stepping with the same signo...
995 SetCurrentGDBRemoteThreadForRun (-1);
996 continue_packet.Printf("S%2.2x", step_signo);
997 }
998 }
999 else if (num_continue_c_tids == 0 &&
1000 num_continue_C_tids == 0 &&
1001 num_continue_s_tids == 0 &&
1002 num_continue_S_tids == 1 )
1003 {
1004 // Only one thread is stepping with signal
1005 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1006 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1007 }
1008 else
1009 {
1010 // We can't represent this continue packet....
1011 continue_packet_error = true;
1012 }
1013 }
1014 }
1015
1016 if (continue_packet_error)
1017 {
1018 error.SetErrorString ("can't make continue packet for this resume");
1019 }
1020 else
1021 {
1022 EventSP event_sp;
1023 TimeValue timeout;
1024 timeout = TimeValue::Now();
1025 timeout.OffsetWithSeconds (5);
1026 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1027
1028 if (listener.WaitForEvent (&timeout, event_sp) == false)
1029 error.SetErrorString("Resume timed out.");
1030 }
Greg Claytonb749a262010-12-03 06:02:24 +00001031 }
1032
Jim Ingham3ae449a2010-11-17 02:32:00 +00001033 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001034}
1035
1036size_t
1037ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1038{
1039 const uint8_t *trap_opcode = NULL;
1040 uint32_t trap_opcode_size = 0;
1041
1042 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
1043 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
1044 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
1045 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
1046
Jim Ingham7508e732010-08-09 23:31:02 +00001047 ArchSpec::CPU arch_cpu = GetTarget().GetArchitecture().GetGenericCPUType();
Greg Claytoncf015052010-06-11 03:25:34 +00001048 switch (arch_cpu)
Chris Lattner24943d22010-06-08 16:52:24 +00001049 {
Greg Claytoncf015052010-06-11 03:25:34 +00001050 case ArchSpec::eCPU_i386:
1051 case ArchSpec::eCPU_x86_64:
1052 trap_opcode = g_i386_breakpoint_opcode;
1053 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
1054 break;
1055
1056 case ArchSpec::eCPU_arm:
1057 // TODO: fill this in for ARM. We need to dig up the symbol for
1058 // the address in the breakpoint locaiton and figure out if it is
1059 // an ARM or Thumb breakpoint.
1060 trap_opcode = g_arm_breakpoint_opcode;
1061 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1062 break;
1063
1064 case ArchSpec::eCPU_ppc:
1065 case ArchSpec::eCPU_ppc64:
1066 trap_opcode = g_ppc_breakpoint_opcode;
1067 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
1068 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001069
Greg Claytoncf015052010-06-11 03:25:34 +00001070 default:
1071 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
1072 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001073 }
1074
1075 if (trap_opcode && trap_opcode_size)
1076 {
1077 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1078 return trap_opcode_size;
1079 }
1080 return 0;
1081}
1082
1083uint32_t
1084ProcessGDBRemote::UpdateThreadListIfNeeded ()
1085{
1086 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001087 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001088 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001089 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1090
Greg Clayton5205f0b2010-09-03 17:10:42 +00001091 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001092 const uint32_t stop_id = GetStopID();
1093 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1094 {
1095 // Update the thread list's stop id immediately so we don't recurse into this function.
1096 ThreadList curr_thread_list (this);
1097 curr_thread_list.SetStopID(stop_id);
1098
1099 Error err;
1100 StringExtractorGDBRemote response;
1101 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
1102 response.IsNormalPacket();
1103 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
1104 {
1105 char ch = response.GetChar();
1106 if (ch == 'l')
1107 break;
1108 if (ch == 'm')
1109 {
1110 do
1111 {
1112 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1113
1114 if (tid != LLDB_INVALID_THREAD_ID)
1115 {
1116 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001117 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001118 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1119 curr_thread_list.AddThread(thread_sp);
1120 }
1121
1122 ch = response.GetChar();
1123 } while (ch == ',');
1124 }
1125 }
1126
1127 m_thread_list = curr_thread_list;
1128
1129 SetThreadStopInfo (m_last_stop_packet);
1130 }
1131 return GetThreadList().GetSize(false);
1132}
1133
1134
1135StateType
1136ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1137{
1138 const char stop_type = stop_packet.GetChar();
1139 switch (stop_type)
1140 {
1141 case 'T':
1142 case 'S':
1143 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001144 if (GetStopID() == 0)
1145 {
1146 // Our first stop, make sure we have a process ID, and also make
1147 // sure we know about our registers
1148 if (GetID() == LLDB_INVALID_PROCESS_ID)
1149 {
1150 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (1);
1151 if (pid != LLDB_INVALID_PROCESS_ID)
1152 SetID (pid);
1153 }
1154 BuildDynamicRegisterInfo (true);
1155 }
Chris Lattner24943d22010-06-08 16:52:24 +00001156 // Stop with signal and thread info
1157 const uint8_t signo = stop_packet.GetHexU8();
1158 std::string name;
1159 std::string value;
1160 std::string thread_name;
1161 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001162 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001163 uint32_t tid = LLDB_INVALID_THREAD_ID;
1164 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1165 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001166 ThreadSP thread_sp;
1167
Chris Lattner24943d22010-06-08 16:52:24 +00001168 while (stop_packet.GetNameColonValue(name, value))
1169 {
1170 if (name.compare("metype") == 0)
1171 {
1172 // exception type in big endian hex
1173 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1174 }
1175 else if (name.compare("mecount") == 0)
1176 {
1177 // exception count in big endian hex
1178 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1179 }
1180 else if (name.compare("medata") == 0)
1181 {
1182 // exception data in big endian hex
1183 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1184 }
1185 else if (name.compare("thread") == 0)
1186 {
1187 // thread in big endian hex
1188 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001189 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001190 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001191 if (!thread_sp)
1192 {
1193 // Create the thread if we need to
1194 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1195 m_thread_list.AddThread(thread_sp);
1196 }
Chris Lattner24943d22010-06-08 16:52:24 +00001197 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001198 else if (name.compare("hexname") == 0)
1199 {
1200 StringExtractor name_extractor;
1201 // Swap "value" over into "name_extractor"
1202 name_extractor.GetStringRef().swap(value);
1203 // Now convert the HEX bytes into a string value
1204 name_extractor.GetHexByteString (value);
1205 thread_name.swap (value);
1206 }
Chris Lattner24943d22010-06-08 16:52:24 +00001207 else if (name.compare("name") == 0)
1208 {
1209 thread_name.swap (value);
1210 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001211 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001212 {
1213 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1214 }
Greg Claytona875b642011-01-09 21:07:35 +00001215 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1216 {
1217 // We have a register number that contains an expedited
1218 // register value. Lets supply this register to our thread
1219 // so it won't have to go and read it.
1220 if (thread_sp)
1221 {
1222 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1223
1224 if (reg != UINT32_MAX)
1225 {
1226 StringExtractor reg_value_extractor;
1227 // Swap "value" over into "reg_value_extractor"
1228 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001229 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1230 {
1231 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1232 name.c_str(),
1233 reg,
1234 reg,
1235 reg_value_extractor.GetStringRef().c_str(),
1236 stop_packet.GetStringRef().c_str());
1237 }
Greg Claytona875b642011-01-09 21:07:35 +00001238 }
1239 }
1240 }
Chris Lattner24943d22010-06-08 16:52:24 +00001241 }
Chris Lattner24943d22010-06-08 16:52:24 +00001242
1243 if (thread_sp)
1244 {
1245 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1246
1247 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001248 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001249 if (exc_type != 0)
1250 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001251 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001252
1253 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1254 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001255 exc_data_size,
1256 exc_data_size >= 1 ? exc_data[0] : 0,
1257 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001258 }
1259 else if (signo)
1260 {
Greg Clayton643ee732010-08-04 01:40:35 +00001261 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001262 }
1263 else
1264 {
Greg Clayton643ee732010-08-04 01:40:35 +00001265 StopInfoSP invalid_stop_info_sp;
1266 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001267 }
1268 }
1269 return eStateStopped;
1270 }
1271 break;
1272
1273 case 'W':
1274 // process exited
1275 return eStateExited;
1276
1277 default:
1278 break;
1279 }
1280 return eStateInvalid;
1281}
1282
1283void
1284ProcessGDBRemote::RefreshStateAfterStop ()
1285{
Jim Ingham7508e732010-08-09 23:31:02 +00001286 // FIXME - add a variable to tell that we're in the middle of attaching if we
1287 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001288 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001289// if (!GetTarget().GetArchitecture().IsValid())
1290// {
1291// Module *exe_module = GetTarget().GetExecutableModule().get();
1292// if (exe_module)
1293// m_arch_spec = exe_module->GetArchitecture();
1294// }
1295
Chris Lattner24943d22010-06-08 16:52:24 +00001296 // Let all threads recover from stopping and do any clean up based
1297 // on the previous thread state (if any).
1298 m_thread_list.RefreshStateAfterStop();
1299
1300 // Discover new threads:
1301 UpdateThreadListIfNeeded ();
1302}
1303
1304Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001305ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001306{
1307 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001308
Greg Claytona4881d02011-01-22 07:12:45 +00001309 bool timed_out = false;
1310 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001311
1312 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001313 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001314 // We are being asked to halt during an attach. We need to just close
1315 // our file handle and debugserver will go away, and we can be done...
1316 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001317 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001318 else
1319 {
1320 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1321 {
1322 if (timed_out)
1323 error.SetErrorString("timed out sending interrupt packet");
1324 else
1325 error.SetErrorString("unknown error sending interrupt packet");
1326 }
1327 }
Chris Lattner24943d22010-06-08 16:52:24 +00001328 return error;
1329}
1330
1331Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001332ProcessGDBRemote::InterruptIfRunning
1333(
1334 bool discard_thread_plans,
1335 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001336 EventSP &stop_event_sp
1337)
Chris Lattner24943d22010-06-08 16:52:24 +00001338{
1339 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001340
Greg Clayton2860ba92011-01-23 19:58:49 +00001341 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1342
Greg Clayton68ca8232011-01-25 02:58:48 +00001343 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001344 const bool is_running = m_gdb_comm.IsRunning();
1345 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001346 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001347 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001348 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001349 is_running);
1350
Greg Clayton2860ba92011-01-23 19:58:49 +00001351 if (discard_thread_plans)
1352 {
1353 if (log)
1354 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1355 m_thread_list.DiscardThreadPlans();
1356 }
1357 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001358 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001359 if (catch_stop_event)
1360 {
1361 if (log)
1362 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1363 PausePrivateStateThread();
1364 paused_private_state_thread = true;
1365 }
1366
Greg Clayton4fb400f2010-09-27 21:07:38 +00001367 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001368 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001369 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001370
Greg Clayton72e1c782011-01-22 23:43:18 +00001371 //m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1372 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001373 {
1374 if (timed_out)
1375 error.SetErrorString("timed out sending interrupt packet");
1376 else
1377 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001378 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001379 ResumePrivateStateThread();
1380 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001381 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001382
Greg Clayton72e1c782011-01-22 23:43:18 +00001383 if (catch_stop_event)
1384 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001385 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001386 TimeValue timeout_time;
1387 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001388 timeout_time.OffsetWithSeconds(5);
1389 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001390
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001391 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001392 if (log)
1393 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001394
Greg Clayton2860ba92011-01-23 19:58:49 +00001395 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001396 error.SetErrorString("unable to verify target stopped");
1397 }
1398
Greg Clayton68ca8232011-01-25 02:58:48 +00001399 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001400 {
1401 if (log)
1402 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001403 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001404 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001405 }
Chris Lattner24943d22010-06-08 16:52:24 +00001406 return error;
1407}
1408
Greg Clayton4fb400f2010-09-27 21:07:38 +00001409Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001410ProcessGDBRemote::WillDetach ()
1411{
Greg Clayton2860ba92011-01-23 19:58:49 +00001412 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1413 if (log)
1414 log->Printf ("ProcessGDBRemote::WillDetach()");
1415
Greg Clayton72e1c782011-01-22 23:43:18 +00001416 bool discard_thread_plans = true;
1417 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001418 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001419 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001420}
1421
1422Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001423ProcessGDBRemote::DoDetach()
1424{
1425 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001426 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001427 if (log)
1428 log->Printf ("ProcessGDBRemote::DoDetach()");
1429
1430 DisableAllBreakpointSites ();
1431
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001432 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001433
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001434 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1435 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001436 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001437 if (response_size)
1438 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1439 else
1440 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001441 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001442 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001443 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001444
Greg Clayton4fb400f2010-09-27 21:07:38 +00001445 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001446 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001447
1448 SetPrivateState (eStateDetached);
1449 ResumePrivateStateThread();
1450
1451 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001452 return error;
1453}
Chris Lattner24943d22010-06-08 16:52:24 +00001454
1455Error
1456ProcessGDBRemote::DoDestroy ()
1457{
1458 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001459 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001460 if (log)
1461 log->Printf ("ProcessGDBRemote::DoDestroy()");
1462
1463 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001464 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001465 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001466 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001467 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001468 // We are being asked to halt during an attach. We need to just close
1469 // our file handle and debugserver will go away, and we can be done...
1470 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001471 }
1472 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001473 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001474
1475 StringExtractorGDBRemote response;
1476 bool send_async = true;
1477 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, 2, send_async))
1478 {
1479 char packet_cmd = response.GetChar(0);
1480
1481 if (packet_cmd == 'W' || packet_cmd == 'X')
1482 {
1483 m_last_stop_packet = response;
1484 SetExitStatus(response.GetHexU8(), NULL);
1485 }
1486 }
1487 else
1488 {
1489 SetExitStatus(SIGABRT, NULL);
1490 //error.SetErrorString("kill packet failed");
1491 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001492 }
1493 }
Chris Lattner24943d22010-06-08 16:52:24 +00001494 StopAsyncThread ();
1495 m_gdb_comm.StopReadThread();
1496 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001497 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001498 return error;
1499}
1500
Chris Lattner24943d22010-06-08 16:52:24 +00001501//------------------------------------------------------------------
1502// Process Queries
1503//------------------------------------------------------------------
1504
1505bool
1506ProcessGDBRemote::IsAlive ()
1507{
Greg Clayton58e844b2010-12-08 05:08:21 +00001508 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001509}
1510
1511addr_t
1512ProcessGDBRemote::GetImageInfoAddress()
1513{
1514 if (!m_gdb_comm.IsRunning())
1515 {
1516 StringExtractorGDBRemote response;
1517 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1518 {
1519 if (response.IsNormalPacket())
1520 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1521 }
1522 }
1523 return LLDB_INVALID_ADDRESS;
1524}
1525
Chris Lattner24943d22010-06-08 16:52:24 +00001526//------------------------------------------------------------------
1527// Process Memory
1528//------------------------------------------------------------------
1529size_t
1530ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1531{
1532 if (size > m_max_memory_size)
1533 {
1534 // Keep memory read sizes down to a sane limit. This function will be
1535 // called multiple times in order to complete the task by
1536 // lldb_private::Process so it is ok to do this.
1537 size = m_max_memory_size;
1538 }
1539
1540 char packet[64];
1541 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1542 assert (packet_len + 1 < sizeof(packet));
1543 StringExtractorGDBRemote response;
1544 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1545 {
1546 if (response.IsNormalPacket())
1547 {
1548 error.Clear();
1549 return response.GetHexBytes(buf, size, '\xdd');
1550 }
1551 else if (response.IsErrorPacket())
1552 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1553 else if (response.IsUnsupportedPacket())
1554 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1555 else
1556 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1557 }
1558 else
1559 {
1560 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1561 }
1562 return 0;
1563}
1564
1565size_t
1566ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1567{
1568 StreamString packet;
1569 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001570 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001571 StringExtractorGDBRemote response;
1572 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1573 {
1574 if (response.IsOKPacket())
1575 {
1576 error.Clear();
1577 return size;
1578 }
1579 else if (response.IsErrorPacket())
1580 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1581 else if (response.IsUnsupportedPacket())
1582 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1583 else
1584 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1585 }
1586 else
1587 {
1588 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1589 }
1590 return 0;
1591}
1592
1593lldb::addr_t
1594ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1595{
1596 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1597 if (allocated_addr == LLDB_INVALID_ADDRESS)
1598 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1599 else
1600 error.Clear();
1601 return allocated_addr;
1602}
1603
1604Error
1605ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1606{
1607 Error error;
1608 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1609 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1610 return error;
1611}
1612
1613
1614//------------------------------------------------------------------
1615// Process STDIO
1616//------------------------------------------------------------------
1617
1618size_t
1619ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1620{
1621 Mutex::Locker locker(m_stdio_mutex);
1622 size_t bytes_available = m_stdout_data.size();
1623 if (bytes_available > 0)
1624 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001625 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1626 if (log)
1627 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001628 if (bytes_available > buf_size)
1629 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001630 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001631 m_stdout_data.erase(0, buf_size);
1632 bytes_available = buf_size;
1633 }
1634 else
1635 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001636 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001637 m_stdout_data.clear();
1638
1639 //ResetEventBits(eBroadcastBitSTDOUT);
1640 }
1641 }
1642 return bytes_available;
1643}
1644
1645size_t
1646ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1647{
1648 // Can we get STDERR through the remote protocol?
1649 return 0;
1650}
1651
1652size_t
1653ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1654{
1655 if (m_stdio_communication.IsConnected())
1656 {
1657 ConnectionStatus status;
1658 m_stdio_communication.Write(src, src_len, status, NULL);
1659 }
1660 return 0;
1661}
1662
1663Error
1664ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1665{
1666 Error error;
1667 assert (bp_site != NULL);
1668
Greg Claytone005f2c2010-11-06 01:53:30 +00001669 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001670 user_id_t site_id = bp_site->GetID();
1671 const addr_t addr = bp_site->GetLoadAddress();
1672 if (log)
1673 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1674
1675 if (bp_site->IsEnabled())
1676 {
1677 if (log)
1678 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1679 return error;
1680 }
1681 else
1682 {
1683 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1684
1685 if (bp_site->HardwarePreferred())
1686 {
1687 // Try and set hardware breakpoint, and if that fails, fall through
1688 // and set a software breakpoint?
1689 }
1690
1691 if (m_z0_supported)
1692 {
1693 char packet[64];
1694 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1695 assert (packet_len + 1 < sizeof(packet));
1696 StringExtractorGDBRemote response;
1697 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1698 {
1699 if (response.IsUnsupportedPacket())
1700 {
1701 // Disable z packet support and try again
1702 m_z0_supported = 0;
1703 return EnableBreakpoint (bp_site);
1704 }
1705 else if (response.IsOKPacket())
1706 {
1707 bp_site->SetEnabled(true);
1708 bp_site->SetType (BreakpointSite::eExternal);
1709 return error;
1710 }
1711 else
1712 {
1713 uint8_t error_byte = response.GetError();
1714 if (error_byte)
1715 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1716 }
1717 }
1718 }
1719 else
1720 {
1721 return EnableSoftwareBreakpoint (bp_site);
1722 }
1723 }
1724
1725 if (log)
1726 {
1727 const char *err_string = error.AsCString();
1728 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1729 bp_site->GetLoadAddress(),
1730 err_string ? err_string : "NULL");
1731 }
1732 // We shouldn't reach here on a successful breakpoint enable...
1733 if (error.Success())
1734 error.SetErrorToGenericError();
1735 return error;
1736}
1737
1738Error
1739ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1740{
1741 Error error;
1742 assert (bp_site != NULL);
1743 addr_t addr = bp_site->GetLoadAddress();
1744 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001745 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001746 if (log)
1747 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1748
1749 if (bp_site->IsEnabled())
1750 {
1751 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1752
1753 if (bp_site->IsHardware())
1754 {
1755 // TODO: disable hardware breakpoint...
1756 }
1757 else
1758 {
1759 if (m_z0_supported)
1760 {
1761 char packet[64];
1762 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1763 assert (packet_len + 1 < sizeof(packet));
1764 StringExtractorGDBRemote response;
1765 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1766 {
1767 if (response.IsUnsupportedPacket())
1768 {
1769 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1770 }
1771 else if (response.IsOKPacket())
1772 {
1773 if (log)
1774 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1775 bp_site->SetEnabled(false);
1776 return error;
1777 }
1778 else
1779 {
1780 uint8_t error_byte = response.GetError();
1781 if (error_byte)
1782 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1783 }
1784 }
1785 }
1786 else
1787 {
1788 return DisableSoftwareBreakpoint (bp_site);
1789 }
1790 }
1791 }
1792 else
1793 {
1794 if (log)
1795 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1796 return error;
1797 }
1798
1799 if (error.Success())
1800 error.SetErrorToGenericError();
1801 return error;
1802}
1803
1804Error
1805ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1806{
1807 Error error;
1808 if (wp)
1809 {
1810 user_id_t watchID = wp->GetID();
1811 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001812 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001813 if (log)
1814 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1815 if (wp->IsEnabled())
1816 {
1817 if (log)
1818 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1819 return error;
1820 }
1821 else
1822 {
1823 // Pass down an appropriate z/Z packet...
1824 error.SetErrorString("watchpoints not supported");
1825 }
1826 }
1827 else
1828 {
1829 error.SetErrorString("Watchpoint location argument was NULL.");
1830 }
1831 if (error.Success())
1832 error.SetErrorToGenericError();
1833 return error;
1834}
1835
1836Error
1837ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1838{
1839 Error error;
1840 if (wp)
1841 {
1842 user_id_t watchID = wp->GetID();
1843
Greg Claytone005f2c2010-11-06 01:53:30 +00001844 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001845
1846 addr_t addr = wp->GetLoadAddress();
1847 if (log)
1848 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1849
1850 if (wp->IsHardware())
1851 {
1852 // Pass down an appropriate z/Z packet...
1853 error.SetErrorString("watchpoints not supported");
1854 }
1855 // TODO: clear software watchpoints if we implement them
1856 }
1857 else
1858 {
1859 error.SetErrorString("Watchpoint location argument was NULL.");
1860 }
1861 if (error.Success())
1862 error.SetErrorToGenericError();
1863 return error;
1864}
1865
1866void
1867ProcessGDBRemote::Clear()
1868{
1869 m_flags = 0;
1870 m_thread_list.Clear();
1871 {
1872 Mutex::Locker locker(m_stdio_mutex);
1873 m_stdout_data.clear();
1874 }
Chris Lattner24943d22010-06-08 16:52:24 +00001875}
1876
1877Error
1878ProcessGDBRemote::DoSignal (int signo)
1879{
1880 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001881 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001882 if (log)
1883 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1884
1885 if (!m_gdb_comm.SendAsyncSignal (signo))
1886 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1887 return error;
1888}
1889
Chris Lattner24943d22010-06-08 16:52:24 +00001890Error
1891ProcessGDBRemote::StartDebugserverProcess
1892(
1893 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1894 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1895 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Claytonde915be2011-01-23 05:56:20 +00001896 const char *stdin_path,
1897 const char *stdout_path,
1898 const char *stderr_path,
1899 const char *working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001900 bool launch_process, // Set to true if we are going to be launching a the process
1901 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 +00001902 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1903 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001904 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001905 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1906)
1907{
1908 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001909 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1910 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001911 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1912 {
1913 // If we locate debugserver, keep that located version around
1914 static FileSpec g_debugserver_file_spec;
1915
1916 FileSpec debugserver_file_spec;
1917 char debugserver_path[PATH_MAX];
1918
1919 // Always check to see if we have an environment override for the path
1920 // to the debugserver to use and use it if we do.
1921 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1922 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001923 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001924 else
1925 debugserver_file_spec = g_debugserver_file_spec;
1926 bool debugserver_exists = debugserver_file_spec.Exists();
1927 if (!debugserver_exists)
1928 {
1929 // The debugserver binary is in the LLDB.framework/Resources
1930 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001931 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001932 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001933 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001934 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001935 if (debugserver_exists)
1936 {
1937 g_debugserver_file_spec = debugserver_file_spec;
1938 }
1939 else
1940 {
1941 g_debugserver_file_spec.Clear();
1942 debugserver_file_spec.Clear();
1943 }
Chris Lattner24943d22010-06-08 16:52:24 +00001944 }
1945 }
1946
1947 if (debugserver_exists)
1948 {
1949 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1950
1951 m_stdio_communication.Clear();
1952 posix_spawnattr_t attr;
1953
Greg Claytone005f2c2010-11-06 01:53:30 +00001954 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001955
1956 Error local_err; // Errors that don't affect the spawning.
1957 if (log)
1958 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString());
1959 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1960 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001961 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001962 if (error.Fail())
1963 return error;;
1964
1965#if !defined (__arm__)
1966
Greg Clayton24b48ff2010-10-17 22:03:32 +00001967 // We don't need to do this for ARM, and we really shouldn't now
1968 // that we have multiple CPU subtypes and no posix_spawnattr call
1969 // that allows us to set which CPU subtype to launch...
Greg Claytoncf015052010-06-11 03:25:34 +00001970 if (inferior_arch.GetType() == eArchTypeMachO)
Chris Lattner24943d22010-06-08 16:52:24 +00001971 {
Greg Claytoncf015052010-06-11 03:25:34 +00001972 cpu_type_t cpu = inferior_arch.GetCPUType();
1973 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
1974 {
1975 size_t ocount = 0;
1976 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1977 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001978 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 +00001979
Greg Claytoncf015052010-06-11 03:25:34 +00001980 if (error.Fail() != 0 || ocount != 1)
1981 return error;
1982 }
Chris Lattner24943d22010-06-08 16:52:24 +00001983 }
1984
1985#endif
1986
1987 Args debugserver_args;
1988 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001989
Chris Lattner24943d22010-06-08 16:52:24 +00001990 lldb_utility::PseudoTerminal pty;
Greg Claytonde915be2011-01-23 05:56:20 +00001991 const char *stdio_path = NULL;
1992 if (launch_process &&
Caroline Ticee4450f02011-01-28 00:19:58 +00001993 (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) &&
Greg Claytonde915be2011-01-23 05:56:20 +00001994 m_local_debugserver &&
1995 no_stdio == false)
Chris Lattner24943d22010-06-08 16:52:24 +00001996 {
Chris Lattner24943d22010-06-08 16:52:24 +00001997 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Caroline Ticee4450f02011-01-28 00:19:58 +00001998 {
1999 const char *slave_name = pty.GetSlaveName (NULL, 0);
2000 if (stdin_path == NULL
2001 && stdout_path == NULL
2002 && stderr_path == NULL)
2003 stdio_path = slave_name;
2004 else
2005 {
2006 if (stdin_path == NULL)
2007 stdin_path = slave_name;
2008 if (stdout_path == NULL)
2009 stdout_path = slave_name;
2010 if (stderr_path == NULL)
2011 stderr_path = slave_name;
2012 }
2013 }
Chris Lattner24943d22010-06-08 16:52:24 +00002014 }
2015
2016 // Start args with "debugserver /file/path -r --"
2017 debugserver_args.AppendArgument(debugserver_path);
2018 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002019 // use native registers, not the GDB registers
2020 debugserver_args.AppendArgument("--native-regs");
2021 // make debugserver run in its own session so signals generated by
2022 // special terminal key sequences (^C) don't affect debugserver
2023 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002024
Greg Clayton452bf612010-08-31 18:35:14 +00002025 if (disable_aslr)
2026 debugserver_args.AppendArguments("--disable-aslr");
2027
Chris Lattner24943d22010-06-08 16:52:24 +00002028 // Only set the inferior
Greg Claytonde915be2011-01-23 05:56:20 +00002029 if (launch_process)
Chris Lattner24943d22010-06-08 16:52:24 +00002030 {
Greg Claytonde915be2011-01-23 05:56:20 +00002031 if (no_stdio)
2032 debugserver_args.AppendArgument("--no-stdio");
2033 else
2034 {
2035 if (stdin_path && stdout_path && stderr_path &&
2036 strcmp(stdin_path, stdout_path) == 0 &&
2037 strcmp(stdin_path, stderr_path) == 0)
2038 {
2039 stdio_path = stdin_path;
2040 stdin_path = stdout_path = stderr_path = NULL;
2041 }
2042
2043 if (stdio_path)
2044 {
2045 // All file handles to stdin, stdout, stderr are the same...
2046 debugserver_args.AppendArgument("--stdio-path");
2047 debugserver_args.AppendArgument(stdio_path);
2048 }
2049 else
2050 {
2051 if (stdin_path == NULL && (stdout_path || stderr_path))
2052 stdin_path = "/dev/null";
2053
2054 if (stdout_path == NULL && (stdin_path || stderr_path))
2055 stdout_path = "/dev/null";
2056
2057 if (stderr_path == NULL && (stdin_path || stdout_path))
2058 stderr_path = "/dev/null";
2059
2060 if (stdin_path)
2061 {
2062 debugserver_args.AppendArgument("--stdin-path");
2063 debugserver_args.AppendArgument(stdin_path);
2064 }
2065 if (stdout_path)
2066 {
2067 debugserver_args.AppendArgument("--stdout-path");
2068 debugserver_args.AppendArgument(stdout_path);
2069 }
2070 if (stderr_path)
2071 {
2072 debugserver_args.AppendArgument("--stderr-path");
2073 debugserver_args.AppendArgument(stderr_path);
2074 }
2075 }
2076 }
Chris Lattner24943d22010-06-08 16:52:24 +00002077 }
Greg Claytonde915be2011-01-23 05:56:20 +00002078
2079 if (working_dir)
Caroline Ticebd666012010-12-03 18:46:09 +00002080 {
Greg Claytonde915be2011-01-23 05:56:20 +00002081 debugserver_args.AppendArgument("--working-dir");
2082 debugserver_args.AppendArgument(working_dir);
Caroline Ticebd666012010-12-03 18:46:09 +00002083 }
Chris Lattner24943d22010-06-08 16:52:24 +00002084
2085 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2086 if (env_debugserver_log_file)
2087 {
2088 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2089 debugserver_args.AppendArgument(arg_cstr);
2090 }
2091
2092 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2093 if (env_debugserver_log_flags)
2094 {
2095 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2096 debugserver_args.AppendArgument(arg_cstr);
2097 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002098// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002099// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002100
2101 // Now append the program arguments
2102 if (launch_process)
2103 {
2104 if (inferior_argv)
2105 {
2106 // Terminate the debugserver args so we can now append the inferior args
2107 debugserver_args.AppendArgument("--");
2108
2109 for (int i = 0; inferior_argv[i] != NULL; ++i)
2110 debugserver_args.AppendArgument (inferior_argv[i]);
2111 }
2112 else
2113 {
2114 // Will send environment entries with the 'QEnvironment:' packet
2115 // Will send arguments with the 'A' packet
2116 }
2117 }
2118 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2119 {
2120 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2121 debugserver_args.AppendArgument (arg_cstr);
2122 }
2123 else if (attach_name && attach_name[0])
2124 {
2125 if (wait_for_launch)
2126 debugserver_args.AppendArgument ("--waitfor");
2127 else
2128 debugserver_args.AppendArgument ("--attach");
2129 debugserver_args.AppendArgument (attach_name);
2130 }
2131
2132 Error file_actions_err;
2133 posix_spawn_file_actions_t file_actions;
2134#if DONT_CLOSE_DEBUGSERVER_STDIO
2135 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
2136#else
2137 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
2138 if (file_actions_err.Success())
2139 {
2140 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
2141 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
2142 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
2143 }
2144#endif
2145
2146 if (log)
2147 {
2148 StreamString strm;
2149 debugserver_args.Dump (&strm);
2150 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2151 }
2152
Greg Clayton72e1c782011-01-22 23:43:18 +00002153 error.SetError (::posix_spawnp (&m_debugserver_pid,
2154 debugserver_path,
2155 file_actions_err.Success() ? &file_actions : NULL,
2156 &attr,
2157 debugserver_args.GetArgumentVector(),
2158 (char * const*)inferior_envp),
2159 eErrorTypePOSIX);
2160
Greg Claytone9d0df42010-07-02 01:29:13 +00002161
2162 ::posix_spawnattr_destroy (&attr);
2163
Chris Lattner24943d22010-06-08 16:52:24 +00002164 if (file_actions_err.Success())
2165 ::posix_spawn_file_actions_destroy (&file_actions);
2166
2167 // We have seen some cases where posix_spawnp was returning a valid
2168 // looking pid even when an error was returned, so clear it out
2169 if (error.Fail())
2170 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2171
2172 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002173 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 +00002174
Caroline Ticebd666012010-12-03 18:46:09 +00002175 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00002176 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00002177 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00002178 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00002179 }
Chris Lattner24943d22010-06-08 16:52:24 +00002180 }
2181 else
2182 {
2183 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2184 }
2185
2186 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2187 StartAsyncThread ();
2188 }
2189 return error;
2190}
2191
2192bool
2193ProcessGDBRemote::MonitorDebugserverProcess
2194(
2195 void *callback_baton,
2196 lldb::pid_t debugserver_pid,
2197 int signo, // Zero for no signal
2198 int exit_status // Exit value of process if signal is zero
2199)
2200{
2201 // We pass in the ProcessGDBRemote inferior process it and name it
2202 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2203 // pointer value itself, thus we need the double cast...
2204
2205 // "debugserver_pid" argument passed in is the process ID for
2206 // debugserver that we are tracking...
2207
Greg Clayton75ccf502010-08-21 02:22:51 +00002208 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002209
2210 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2211 if (log)
2212 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2213
Greg Clayton75ccf502010-08-21 02:22:51 +00002214 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002215 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002216 // Sleep for a half a second to make sure our inferior process has
2217 // time to set its exit status before we set it incorrectly when
2218 // both the debugserver and the inferior process shut down.
2219 usleep (500000);
2220 // If our process hasn't yet exited, debugserver might have died.
2221 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002222 const StateType state = process->GetState();
2223
2224 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2225 state != eStateInvalid &&
2226 state != eStateUnloaded &&
2227 state != eStateExited &&
2228 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002229 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002230 char error_str[1024];
2231 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002232 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002233 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2234 if (signal_cstr)
2235 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002236 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002237 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002238 }
2239 else
2240 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002241 ::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 +00002242 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002243
2244 process->SetExitStatus (-1, error_str);
2245 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002246 // Debugserver has exited we need to let our ProcessGDBRemote
2247 // know that it no longer has a debugserver instance
2248 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2249 // We are returning true to this function below, so we can
2250 // forget about the monitor handle.
2251 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002252 }
2253 return true;
2254}
2255
2256void
2257ProcessGDBRemote::KillDebugserverProcess ()
2258{
2259 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2260 {
2261 ::kill (m_debugserver_pid, SIGINT);
2262 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2263 }
2264}
2265
2266void
2267ProcessGDBRemote::Initialize()
2268{
2269 static bool g_initialized = false;
2270
2271 if (g_initialized == false)
2272 {
2273 g_initialized = true;
2274 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2275 GetPluginDescriptionStatic(),
2276 CreateInstance);
2277
2278 Log::Callbacks log_callbacks = {
2279 ProcessGDBRemoteLog::DisableLog,
2280 ProcessGDBRemoteLog::EnableLog,
2281 ProcessGDBRemoteLog::ListLogCategories
2282 };
2283
2284 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2285 }
2286}
2287
2288bool
2289ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2290{
2291 if (m_curr_tid == tid)
2292 return true;
2293
2294 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002295 int packet_len;
2296 if (tid <= 0)
2297 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2298 else
2299 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002300 assert (packet_len + 1 < sizeof(packet));
2301 StringExtractorGDBRemote response;
2302 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2303 {
2304 if (response.IsOKPacket())
2305 {
2306 m_curr_tid = tid;
2307 return true;
2308 }
2309 }
2310 return false;
2311}
2312
2313bool
2314ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2315{
2316 if (m_curr_tid_run == tid)
2317 return true;
2318
2319 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002320 int packet_len;
2321 if (tid <= 0)
2322 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2323 else
2324 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2325
Chris Lattner24943d22010-06-08 16:52:24 +00002326 assert (packet_len + 1 < sizeof(packet));
2327 StringExtractorGDBRemote response;
2328 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2329 {
2330 if (response.IsOKPacket())
2331 {
2332 m_curr_tid_run = tid;
2333 return true;
2334 }
2335 }
2336 return false;
2337}
2338
2339void
2340ProcessGDBRemote::ResetGDBRemoteState ()
2341{
2342 // Reset and GDB remote state
2343 m_curr_tid = LLDB_INVALID_THREAD_ID;
2344 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2345 m_z0_supported = 1;
2346}
2347
2348
2349bool
2350ProcessGDBRemote::StartAsyncThread ()
2351{
2352 ResetGDBRemoteState ();
2353
Greg Claytone005f2c2010-11-06 01:53:30 +00002354 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002355
2356 if (log)
2357 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2358
2359 // Create a thread that watches our internal state and controls which
2360 // events make it to clients (into the DCProcess event queue).
2361 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002362 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002363}
2364
2365void
2366ProcessGDBRemote::StopAsyncThread ()
2367{
Greg Claytone005f2c2010-11-06 01:53:30 +00002368 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002369
2370 if (log)
2371 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2372
2373 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2374
2375 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002376 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002377 {
2378 Host::ThreadJoin (m_async_thread, NULL, NULL);
2379 }
2380}
2381
2382
2383void *
2384ProcessGDBRemote::AsyncThread (void *arg)
2385{
2386 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2387
Greg Claytone005f2c2010-11-06 01:53:30 +00002388 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002389 if (log)
2390 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2391
2392 Listener listener ("ProcessGDBRemote::AsyncThread");
2393 EventSP event_sp;
2394 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2395 eBroadcastBitAsyncThreadShouldExit;
2396
2397 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2398 {
2399 bool done = false;
2400 while (!done)
2401 {
2402 if (log)
2403 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2404 if (listener.WaitForEvent (NULL, event_sp))
2405 {
2406 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002407 if (log)
2408 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2409
Chris Lattner24943d22010-06-08 16:52:24 +00002410 switch (event_type)
2411 {
2412 case eBroadcastBitAsyncContinue:
2413 {
2414 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2415
2416 if (continue_packet)
2417 {
2418 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2419 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2420 if (log)
2421 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2422
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002423 if (::strstr (continue_cstr, "vAttach") == NULL)
2424 process->SetPrivateState(eStateRunning);
Chris Lattner24943d22010-06-08 16:52:24 +00002425 StringExtractorGDBRemote response;
2426 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2427
2428 switch (stop_state)
2429 {
2430 case eStateStopped:
2431 case eStateCrashed:
2432 case eStateSuspended:
2433 process->m_last_stop_packet = response;
2434 process->m_last_stop_packet.SetFilePos (0);
2435 process->SetPrivateState (stop_state);
2436 break;
2437
2438 case eStateExited:
2439 process->m_last_stop_packet = response;
2440 process->m_last_stop_packet.SetFilePos (0);
2441 response.SetFilePos(1);
2442 process->SetExitStatus(response.GetHexU8(), NULL);
2443 done = true;
2444 break;
2445
2446 case eStateInvalid:
2447 break;
2448
2449 default:
2450 process->SetPrivateState (stop_state);
2451 break;
2452 }
2453 }
2454 }
2455 break;
2456
2457 case eBroadcastBitAsyncThreadShouldExit:
2458 if (log)
2459 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2460 done = true;
2461 break;
2462
2463 default:
2464 if (log)
2465 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2466 done = true;
2467 break;
2468 }
2469 }
2470 else
2471 {
2472 if (log)
2473 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2474 done = true;
2475 }
2476 }
2477 }
2478
2479 if (log)
2480 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2481
2482 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2483 return NULL;
2484}
2485
Chris Lattner24943d22010-06-08 16:52:24 +00002486const char *
2487ProcessGDBRemote::GetDispatchQueueNameForThread
2488(
2489 addr_t thread_dispatch_qaddr,
2490 std::string &dispatch_queue_name
2491)
2492{
2493 dispatch_queue_name.clear();
2494 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2495 {
2496 // Cache the dispatch_queue_offsets_addr value so we don't always have
2497 // to look it up
2498 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2499 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002500 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2501 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002502 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002503 if (module_sp)
2504 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2505
2506 if (dispatch_queue_offsets_symbol == NULL)
2507 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002508 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002509 if (module_sp)
2510 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2511 }
Chris Lattner24943d22010-06-08 16:52:24 +00002512 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002513 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002514
2515 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2516 return NULL;
2517 }
2518
2519 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002520 DataExtractor data (memory_buffer,
2521 sizeof(memory_buffer),
2522 m_target.GetArchitecture().GetByteOrder(),
2523 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002524
2525 // Excerpt from src/queue_private.h
2526 struct dispatch_queue_offsets_s
2527 {
2528 uint16_t dqo_version;
2529 uint16_t dqo_label;
2530 uint16_t dqo_label_size;
2531 } dispatch_queue_offsets;
2532
2533
2534 Error error;
2535 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2536 {
2537 uint32_t data_offset = 0;
2538 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2539 {
2540 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2541 {
2542 data_offset = 0;
2543 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2544 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2545 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2546 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2547 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2548 dispatch_queue_name.erase (bytes_read);
2549 }
2550 }
2551 }
2552 }
2553 if (dispatch_queue_name.empty())
2554 return NULL;
2555 return dispatch_queue_name.c_str();
2556}
2557
Jim Ingham7508e732010-08-09 23:31:02 +00002558uint32_t
2559ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2560{
2561 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2562 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2563 if (m_local_debugserver)
2564 {
2565 return Host::ListProcessesMatchingName (name, matches, pids);
2566 }
2567 else
2568 {
2569 // FIXME: Implement talking to the remote debugserver.
2570 return 0;
2571 }
2572
2573}
Jim Ingham55e01d82011-01-22 01:33:44 +00002574
2575bool
2576ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2577 lldb_private::StoppointCallbackContext *context,
2578 lldb::user_id_t break_id,
2579 lldb::user_id_t break_loc_id)
2580{
2581 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2582 // run so I can stop it if that's what I want to do.
2583 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2584 if (log)
2585 log->Printf("Hit New Thread Notification breakpoint.");
2586 return false;
2587}
2588
2589
2590bool
2591ProcessGDBRemote::StartNoticingNewThreads()
2592{
2593 static const char *bp_names[] =
2594 {
2595 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002596 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002597 "_pthread_start",
2598 NULL
2599 };
2600
2601 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2602 size_t num_bps = m_thread_observation_bps.size();
2603 if (num_bps != 0)
2604 {
2605 for (int i = 0; i < num_bps; i++)
2606 {
2607 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2608 if (break_sp)
2609 {
2610 if (log)
2611 log->Printf("Enabled noticing new thread breakpoint.");
2612 break_sp->SetEnabled(true);
2613 }
2614 }
2615 }
2616 else
2617 {
2618 for (int i = 0; bp_names[i] != NULL; i++)
2619 {
2620 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2621 if (breakpoint)
2622 {
2623 if (log)
2624 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2625 m_thread_observation_bps.push_back(breakpoint->GetID());
2626 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2627 }
2628 else
2629 {
2630 if (log)
2631 log->Printf("Failed to create new thread notification breakpoint.");
2632 return false;
2633 }
2634 }
2635 }
2636
2637 return true;
2638}
2639
2640bool
2641ProcessGDBRemote::StopNoticingNewThreads()
2642{
Jim Inghamff276fe2011-02-08 05:19:01 +00002643 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2644 if (log)
2645 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002646 size_t num_bps = m_thread_observation_bps.size();
2647 if (num_bps != 0)
2648 {
2649 for (int i = 0; i < num_bps; i++)
2650 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002651
2652 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2653 if (break_sp)
2654 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002655 break_sp->SetEnabled(false);
2656 }
2657 }
2658 }
2659 return true;
2660}
2661
2662