blob: 34eca44081aef73577f00034fde9b7a102882db9 [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.
Greg Clayton940b1032011-02-23 00:35:02 +0000331 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000332 m_register_info.HardcodeARMRegisters();
333 }
334 m_register_info.Finalize ();
335}
336
337Error
338ProcessGDBRemote::WillLaunch (Module* module)
339{
340 return WillLaunchOrAttach ();
341}
342
343Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000344ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000345{
346 return WillLaunchOrAttach ();
347}
348
349Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000350ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000351{
352 return WillLaunchOrAttach ();
353}
354
355Error
Greg Claytone71e2582011-02-04 01:58:07 +0000356ProcessGDBRemote::DoConnectRemote (const char *remote_url)
357{
358 Error error (WillLaunchOrAttach ());
359
360 if (error.Fail())
361 return error;
362
363 if (strncmp (remote_url, "connect://", strlen ("connect://")) == 0)
364 {
365 error = ConnectToDebugserver (remote_url);
366 }
367 else
368 {
369 error.SetErrorStringWithFormat ("unsupported remote url: %s", remote_url);
370 }
371
372 if (error.Fail())
373 return error;
374 StartAsyncThread ();
375
376 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (m_packet_timeout);
377 if (pid == LLDB_INVALID_PROCESS_ID)
378 {
379 // We don't have a valid process ID, so note that we are connected
380 // and could now request to launch or attach, or get remote process
381 // listings...
382 SetPrivateState (eStateConnected);
383 }
384 else
385 {
386 // We have a valid process
387 SetID (pid);
388 StringExtractorGDBRemote response;
389 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
390 {
391 const StateType state = SetThreadStopInfo (response);
392 if (state == eStateStopped)
393 {
394 SetPrivateState (state);
395 }
396 else
397 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
398 }
399 else
400 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
401 }
402 return error;
403}
404
405Error
Chris Lattner24943d22010-06-08 16:52:24 +0000406ProcessGDBRemote::WillLaunchOrAttach ()
407{
408 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000409 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000410 return error;
411}
412
413//----------------------------------------------------------------------
414// Process Control
415//----------------------------------------------------------------------
416Error
417ProcessGDBRemote::DoLaunch
418(
419 Module* module,
420 char const *argv[],
421 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000422 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000423 const char *stdin_path,
424 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000425 const char *stderr_path,
426 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000427)
428{
Greg Clayton4b407112010-09-30 21:49:03 +0000429 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000430 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
431 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
432 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner24943d22010-06-08 16:52:24 +0000433
434 ObjectFile * object_file = module->GetObjectFile();
435 if (object_file)
436 {
437 ArchSpec inferior_arch(module->GetArchitecture());
438 char host_port[128];
439 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000440 char connect_url[128];
441 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000442
Greg Clayton23cf0c72010-11-08 04:29:11 +0000443 const bool launch_process = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000444 bool start_debugserver_with_inferior_args = false;
445 if (start_debugserver_with_inferior_args)
446 {
447 // We want to launch debugserver with the inferior program and its
448 // arguments on the command line. We should only do this if we
449 // the GDB server we are talking to doesn't support the 'A' packet.
450 error = StartDebugserverProcess (host_port,
451 argv,
452 envp,
Greg Claytonde915be2011-01-23 05:56:20 +0000453 stdin_path,
454 stdout_path,
455 stderr_path,
456 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000457 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000458 LLDB_INVALID_PROCESS_ID,
459 NULL, false,
Caroline Ticebd666012010-12-03 18:46:09 +0000460 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000461 inferior_arch);
462 if (error.Fail())
463 return error;
464
Greg Claytone71e2582011-02-04 01:58:07 +0000465 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000466 if (error.Success())
467 {
468 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
469 }
470 }
471 else
472 {
473 error = StartDebugserverProcess (host_port,
474 NULL,
475 NULL,
Greg Claytonde915be2011-01-23 05:56:20 +0000476 stdin_path,
477 stdout_path,
478 stderr_path,
479 working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +0000480 launch_process,
Chris Lattner24943d22010-06-08 16:52:24 +0000481 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000482 NULL,
483 false,
Caroline Ticebd666012010-12-03 18:46:09 +0000484 launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000485 inferior_arch);
486 if (error.Fail())
487 return error;
488
Greg Claytone71e2582011-02-04 01:58:07 +0000489 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000490 if (error.Success())
491 {
492 // Send the environment and the program + arguments after we connect
493 if (envp)
494 {
495 const char *env_entry;
496 for (int i=0; (env_entry = envp[i]); ++i)
497 {
498 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
499 break;
500 }
501 }
502
Greg Clayton960d6a42010-08-03 00:35:52 +0000503 // FIXME: convert this to use the new set/show variables when they are available
504#if 0
505 if (::getenv ("LLDB_DEBUG_DEBUGSERVER"))
506 {
507 const uint32_t attach_debugserver_secs = 10;
508 ::printf ("attach to debugserver (pid = %i)\n", m_debugserver_pid);
509 for (uint32_t i=0; i<attach_debugserver_secs; ++i)
510 {
511 printf ("%i\n", attach_debugserver_secs - i);
512 sleep (1);
513 }
514 }
515#endif
516
Chris Lattner24943d22010-06-08 16:52:24 +0000517 const uint32_t arg_timeout_seconds = 10;
518 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
519 if (arg_packet_err == 0)
520 {
521 std::string error_str;
522 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
523 {
524 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
525 }
526 else
527 {
528 error.SetErrorString (error_str.c_str());
529 }
530 }
531 else
532 {
533 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
534 }
535
536 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
537 }
538 }
539
540 if (GetID() == LLDB_INVALID_PROCESS_ID)
541 {
542 KillDebugserverProcess ();
543 return error;
544 }
545
546 StringExtractorGDBRemote response;
547 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
548 SetPrivateState (SetThreadStopInfo (response));
549
550 }
551 else
552 {
553 // Set our user ID to an invalid process ID.
554 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000555 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
556 module->GetFileSpec().GetFilename().AsCString(),
557 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000558 }
Chris Lattner24943d22010-06-08 16:52:24 +0000559 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000560
Chris Lattner24943d22010-06-08 16:52:24 +0000561}
562
563
564Error
Greg Claytone71e2582011-02-04 01:58:07 +0000565ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000566{
567 Error error;
568 // Sleep and wait a bit for debugserver to start to listen...
569 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
570 if (conn_ap.get())
571 {
Chris Lattner24943d22010-06-08 16:52:24 +0000572 const uint32_t max_retry_count = 50;
573 uint32_t retry_count = 0;
574 while (!m_gdb_comm.IsConnected())
575 {
Greg Claytone71e2582011-02-04 01:58:07 +0000576 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000577 {
578 m_gdb_comm.SetConnection (conn_ap.release());
579 break;
580 }
581 retry_count++;
582
583 if (retry_count >= max_retry_count)
584 break;
585
586 usleep (100000);
587 }
588 }
589
590 if (!m_gdb_comm.IsConnected())
591 {
592 if (error.Success())
593 error.SetErrorString("not connected to remote gdb server");
594 return error;
595 }
596
Chris Lattner24943d22010-06-08 16:52:24 +0000597 if (m_gdb_comm.StartReadThread(&error))
598 {
599 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000600 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000601
602 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000603 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
604 this,
605 m_debugserver_pid,
606 false);
607
Greg Claytonc1f45872011-02-12 06:28:37 +0000608 m_gdb_comm.ResetDiscoverableSettings();
609 m_gdb_comm.GetSendAcks ();
610 m_gdb_comm.GetThreadSuffixSupported ();
611 m_gdb_comm.GetHostInfo ();
612 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000613 }
614 return error;
615}
616
617void
618ProcessGDBRemote::DidLaunchOrAttach ()
619{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000620 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
621 if (log)
622 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000623 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000624 {
625 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
626
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000627 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000628
Greg Clayton395fc332011-02-15 21:59:32 +0000629 m_target.GetArchitecture().SetByteOrder (m_gdb_comm.GetByteOrder());
Greg Clayton20d338f2010-11-18 05:57:03 +0000630
Chris Lattner24943d22010-06-08 16:52:24 +0000631 StreamString strm;
632
Chris Lattner24943d22010-06-08 16:52:24 +0000633 // See if the GDB server supports the qHostInfo information
634 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
635 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Claytonfc7920f2011-02-09 03:09:55 +0000636 ArchSpec target_arch (GetTarget().GetArchitecture());
637 ArchSpec gdb_remote_arch (m_gdb_comm.GetHostArchitecture());
638
Greg Claytonc62176d2011-02-09 03:12:09 +0000639 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytonfc7920f2011-02-09 03:09:55 +0000640 // ARM executables and shared libraries can have mixed ARM architectures.
641 // You can have an armv6 executable, and if the host is armv7, then the
642 // system will load the best possible architecture for all shared libraries
643 // it has, so we really need to take the remote host architecture as our
644 // defacto architecture in this case.
645
Greg Clayton940b1032011-02-23 00:35:02 +0000646 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
647 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytonfc7920f2011-02-09 03:09:55 +0000648 {
649 GetTarget().SetArchitecture (gdb_remote_arch);
650 target_arch = gdb_remote_arch;
651 }
652
Greg Clayton395fc332011-02-15 21:59:32 +0000653 if (vendor)
654 m_target.GetArchitecture().GetTriple().setVendorName(vendor);
655 if (os_type)
656 m_target.GetArchitecture().GetTriple().setOSName(os_type);
Chris Lattner24943d22010-06-08 16:52:24 +0000657 }
658}
659
660void
661ProcessGDBRemote::DidLaunch ()
662{
663 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000664}
665
666Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000667ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000668{
669 Error error;
670 // Clear out and clean up from any current state
671 Clear();
Jim Ingham7508e732010-08-09 23:31:02 +0000672 ArchSpec arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000673
Chris Lattner24943d22010-06-08 16:52:24 +0000674 if (attach_pid != LLDB_INVALID_PROCESS_ID)
675 {
Chris Lattner24943d22010-06-08 16:52:24 +0000676 char host_port[128];
677 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000678 char connect_url[128];
679 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
680
Greg Clayton452bf612010-08-31 18:35:14 +0000681 error = StartDebugserverProcess (host_port, // debugserver_url
682 NULL, // inferior_argv
683 NULL, // inferior_envp
684 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000685 NULL, // stdout_path
686 NULL, // stderr_path
687 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000688 false, // launch_process == false (we are attaching)
689 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
690 NULL, // Don't send any attach by process name option to debugserver
691 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000692 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000693 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000694
695 if (error.Fail())
696 {
697 const char *error_string = error.AsCString();
698 if (error_string == NULL)
699 error_string = "unable to launch " DEBUGSERVER_BASENAME;
700
701 SetExitStatus (-1, error_string);
702 }
703 else
704 {
Greg Claytone71e2582011-02-04 01:58:07 +0000705 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000706 if (error.Success())
707 {
708 char packet[64];
709 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000710
711 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000712 }
713 }
714 }
Chris Lattner24943d22010-06-08 16:52:24 +0000715 return error;
716}
717
718size_t
719ProcessGDBRemote::AttachInputReaderCallback
720(
721 void *baton,
722 InputReader *reader,
723 lldb::InputReaderAction notification,
724 const char *bytes,
725 size_t bytes_len
726)
727{
728 if (notification == eInputReaderGotToken)
729 {
730 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
731 if (gdb_process->m_waiting_for_attach)
732 gdb_process->m_waiting_for_attach = false;
733 reader->SetIsDone(true);
734 return 1;
735 }
736 return 0;
737}
738
739Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000740ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000741{
742 Error error;
743 // Clear out and clean up from any current state
744 Clear();
745 // HACK: require arch be set correctly at the target level until we can
746 // figure out a good way to determine the arch of what we are attaching to
Chris Lattner24943d22010-06-08 16:52:24 +0000747
Chris Lattner24943d22010-06-08 16:52:24 +0000748 if (process_name && process_name[0])
749 {
Jim Ingham7508e732010-08-09 23:31:02 +0000750 ArchSpec arch_spec = GetTarget().GetArchitecture();
Greg Claytone71e2582011-02-04 01:58:07 +0000751
752 char host_port[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000753 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000754 char connect_url[128];
755 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
756
Greg Clayton452bf612010-08-31 18:35:14 +0000757 error = StartDebugserverProcess (host_port, // debugserver_url
758 NULL, // inferior_argv
759 NULL, // inferior_envp
760 NULL, // stdin_path
Greg Claytonde915be2011-01-23 05:56:20 +0000761 NULL, // stdout_path
762 NULL, // stderr_path
763 NULL, // working_dir
Greg Clayton23cf0c72010-11-08 04:29:11 +0000764 false, // launch_process == false (we are attaching)
765 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
766 NULL, // Don't send any attach by process name option to debugserver
767 false, // Don't send any attach wait_for_launch flag as an option to debugserver
Caroline Ticebd666012010-12-03 18:46:09 +0000768 0, // launch_flags
Jim Ingham7508e732010-08-09 23:31:02 +0000769 arch_spec);
Chris Lattner24943d22010-06-08 16:52:24 +0000770 if (error.Fail())
771 {
772 const char *error_string = error.AsCString();
773 if (error_string == NULL)
774 error_string = "unable to launch " DEBUGSERVER_BASENAME;
775
776 SetExitStatus (-1, error_string);
777 }
778 else
779 {
Greg Claytone71e2582011-02-04 01:58:07 +0000780 error = ConnectToDebugserver (connect_url);
Chris Lattner24943d22010-06-08 16:52:24 +0000781 if (error.Success())
782 {
783 StreamString packet;
784
Chris Lattner24943d22010-06-08 16:52:24 +0000785 if (wait_for_launch)
Greg Claytonc1d37752010-10-18 01:45:30 +0000786 packet.PutCString("vAttachWait");
787 else
788 packet.PutCString("vAttachName");
Chris Lattner24943d22010-06-08 16:52:24 +0000789 packet.PutChar(';');
Greg Claytoncd548032011-02-01 01:31:41 +0000790 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000791
792 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
Chris Lattner24943d22010-06-08 16:52:24 +0000793
Chris Lattner24943d22010-06-08 16:52:24 +0000794 }
795 }
796 }
Chris Lattner24943d22010-06-08 16:52:24 +0000797 return error;
798}
799
Chris Lattner24943d22010-06-08 16:52:24 +0000800
801void
802ProcessGDBRemote::DidAttach ()
803{
Greg Claytone71e2582011-02-04 01:58:07 +0000804 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000805}
806
807Error
808ProcessGDBRemote::WillResume ()
809{
Greg Claytonc1f45872011-02-12 06:28:37 +0000810 m_continue_c_tids.clear();
811 m_continue_C_tids.clear();
812 m_continue_s_tids.clear();
813 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000814 return Error();
815}
816
817Error
818ProcessGDBRemote::DoResume ()
819{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000820 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000821 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
822 if (log)
823 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000824
825 Listener listener ("gdb-remote.resume-packet-sent");
826 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
827 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000828 StreamString continue_packet;
829 bool continue_packet_error = false;
830 if (m_gdb_comm.HasAnyVContSupport ())
831 {
832 continue_packet.PutCString ("vCont");
833
834 if (!m_continue_c_tids.empty())
835 {
836 if (m_gdb_comm.GetVContSupported ('c'))
837 {
838 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)
839 continue_packet.Printf(";c:%4.4x", *t_pos);
840 }
841 else
842 continue_packet_error = true;
843 }
844
845 if (!continue_packet_error && !m_continue_C_tids.empty())
846 {
847 if (m_gdb_comm.GetVContSupported ('C'))
848 {
849 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)
850 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
851 }
852 else
853 continue_packet_error = true;
854 }
Greg Claytonb749a262010-12-03 06:02:24 +0000855
Greg Claytonc1f45872011-02-12 06:28:37 +0000856 if (!continue_packet_error && !m_continue_s_tids.empty())
857 {
858 if (m_gdb_comm.GetVContSupported ('s'))
859 {
860 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)
861 continue_packet.Printf(";s:%4.4x", *t_pos);
862 }
863 else
864 continue_packet_error = true;
865 }
866
867 if (!continue_packet_error && !m_continue_S_tids.empty())
868 {
869 if (m_gdb_comm.GetVContSupported ('S'))
870 {
871 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)
872 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
873 }
874 else
875 continue_packet_error = true;
876 }
877
878 if (continue_packet_error)
879 continue_packet.GetString().clear();
880 }
881 else
882 continue_packet_error = true;
883
884 if (continue_packet_error)
885 {
886 continue_packet_error = false;
887 // Either no vCont support, or we tried to use part of the vCont
888 // packet that wasn't supported by the remote GDB server.
889 // We need to try and make a simple packet that can do our continue
890 const size_t num_threads = GetThreadList().GetSize();
891 const size_t num_continue_c_tids = m_continue_c_tids.size();
892 const size_t num_continue_C_tids = m_continue_C_tids.size();
893 const size_t num_continue_s_tids = m_continue_s_tids.size();
894 const size_t num_continue_S_tids = m_continue_S_tids.size();
895 if (num_continue_c_tids > 0)
896 {
897 if (num_continue_c_tids == num_threads)
898 {
899 // All threads are resuming...
900 SetCurrentGDBRemoteThreadForRun (-1);
901 continue_packet.PutChar ('c');
902 }
903 else if (num_continue_c_tids == 1 &&
904 num_continue_C_tids == 0 &&
905 num_continue_s_tids == 0 &&
906 num_continue_S_tids == 0 )
907 {
908 // Only one thread is continuing
909 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
910 continue_packet.PutChar ('c');
911 }
912 else
913 {
914 // We can't represent this continue packet....
915 continue_packet_error = true;
916 }
917 }
918
919 if (!continue_packet_error && num_continue_C_tids > 0)
920 {
921 if (num_continue_C_tids == num_threads)
922 {
923 const int continue_signo = m_continue_C_tids.front().second;
924 if (num_continue_C_tids > 1)
925 {
926 for (size_t i=1; i<num_threads; ++i)
927 {
928 if (m_continue_C_tids[i].second != continue_signo)
929 continue_packet_error = true;
930 }
931 }
932 if (!continue_packet_error)
933 {
934 // Add threads continuing with the same signo...
935 SetCurrentGDBRemoteThreadForRun (-1);
936 continue_packet.Printf("C%2.2x", continue_signo);
937 }
938 }
939 else if (num_continue_c_tids == 0 &&
940 num_continue_C_tids == 1 &&
941 num_continue_s_tids == 0 &&
942 num_continue_S_tids == 0 )
943 {
944 // Only one thread is continuing with signal
945 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
946 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
947 }
948 else
949 {
950 // We can't represent this continue packet....
951 continue_packet_error = true;
952 }
953 }
954
955 if (!continue_packet_error && num_continue_s_tids > 0)
956 {
957 if (num_continue_s_tids == num_threads)
958 {
959 // All threads are resuming...
960 SetCurrentGDBRemoteThreadForRun (-1);
961 continue_packet.PutChar ('s');
962 }
963 else if (num_continue_c_tids == 0 &&
964 num_continue_C_tids == 0 &&
965 num_continue_s_tids == 1 &&
966 num_continue_S_tids == 0 )
967 {
968 // Only one thread is stepping
969 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
970 continue_packet.PutChar ('s');
971 }
972 else
973 {
974 // We can't represent this continue packet....
975 continue_packet_error = true;
976 }
977 }
978
979 if (!continue_packet_error && num_continue_S_tids > 0)
980 {
981 if (num_continue_S_tids == num_threads)
982 {
983 const int step_signo = m_continue_S_tids.front().second;
984 // Are all threads trying to step with the same signal?
985 if (num_continue_S_tids > 1)
986 {
987 for (size_t i=1; i<num_threads; ++i)
988 {
989 if (m_continue_S_tids[i].second != step_signo)
990 continue_packet_error = true;
991 }
992 }
993 if (!continue_packet_error)
994 {
995 // Add threads stepping with the same signo...
996 SetCurrentGDBRemoteThreadForRun (-1);
997 continue_packet.Printf("S%2.2x", step_signo);
998 }
999 }
1000 else if (num_continue_c_tids == 0 &&
1001 num_continue_C_tids == 0 &&
1002 num_continue_s_tids == 0 &&
1003 num_continue_S_tids == 1 )
1004 {
1005 // Only one thread is stepping with signal
1006 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1007 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1008 }
1009 else
1010 {
1011 // We can't represent this continue packet....
1012 continue_packet_error = true;
1013 }
1014 }
1015 }
1016
1017 if (continue_packet_error)
1018 {
1019 error.SetErrorString ("can't make continue packet for this resume");
1020 }
1021 else
1022 {
1023 EventSP event_sp;
1024 TimeValue timeout;
1025 timeout = TimeValue::Now();
1026 timeout.OffsetWithSeconds (5);
1027 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1028
1029 if (listener.WaitForEvent (&timeout, event_sp) == false)
1030 error.SetErrorString("Resume timed out.");
1031 }
Greg Claytonb749a262010-12-03 06:02:24 +00001032 }
1033
Jim Ingham3ae449a2010-11-17 02:32:00 +00001034 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001035}
1036
1037size_t
1038ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1039{
1040 const uint8_t *trap_opcode = NULL;
1041 uint32_t trap_opcode_size = 0;
1042
1043 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
1044 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
1045 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
1046 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
1047
Greg Clayton940b1032011-02-23 00:35:02 +00001048 const llvm::Triple::ArchType machine = GetTarget().GetArchitecture().GetMachine();
1049 switch (machine)
Chris Lattner24943d22010-06-08 16:52:24 +00001050 {
Greg Clayton940b1032011-02-23 00:35:02 +00001051 case llvm::Triple::x86:
1052 case llvm::Triple::x86_64:
Greg Claytoncf015052010-06-11 03:25:34 +00001053 trap_opcode = g_i386_breakpoint_opcode;
1054 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
1055 break;
1056
Greg Clayton940b1032011-02-23 00:35:02 +00001057 case llvm::Triple::arm:
Greg Claytoncf015052010-06-11 03:25:34 +00001058 // TODO: fill this in for ARM. We need to dig up the symbol for
1059 // the address in the breakpoint locaiton and figure out if it is
1060 // an ARM or Thumb breakpoint.
1061 trap_opcode = g_arm_breakpoint_opcode;
1062 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1063 break;
1064
Greg Clayton940b1032011-02-23 00:35:02 +00001065 case llvm::Triple::ppc:
1066 case llvm::Triple::ppc64:
Greg Claytoncf015052010-06-11 03:25:34 +00001067 trap_opcode = g_ppc_breakpoint_opcode;
1068 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
1069 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001070
Greg Claytoncf015052010-06-11 03:25:34 +00001071 default:
1072 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
1073 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001074 }
1075
1076 if (trap_opcode && trap_opcode_size)
1077 {
1078 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1079 return trap_opcode_size;
1080 }
1081 return 0;
1082}
1083
1084uint32_t
1085ProcessGDBRemote::UpdateThreadListIfNeeded ()
1086{
1087 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001088 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001089 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001090 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1091
Greg Clayton5205f0b2010-09-03 17:10:42 +00001092 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001093 const uint32_t stop_id = GetStopID();
1094 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1095 {
1096 // Update the thread list's stop id immediately so we don't recurse into this function.
1097 ThreadList curr_thread_list (this);
1098 curr_thread_list.SetStopID(stop_id);
1099
1100 Error err;
1101 StringExtractorGDBRemote response;
1102 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
1103 response.IsNormalPacket();
1104 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
1105 {
1106 char ch = response.GetChar();
1107 if (ch == 'l')
1108 break;
1109 if (ch == 'm')
1110 {
1111 do
1112 {
1113 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1114
1115 if (tid != LLDB_INVALID_THREAD_ID)
1116 {
1117 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001118 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001119 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1120 curr_thread_list.AddThread(thread_sp);
1121 }
1122
1123 ch = response.GetChar();
1124 } while (ch == ',');
1125 }
1126 }
1127
1128 m_thread_list = curr_thread_list;
1129
1130 SetThreadStopInfo (m_last_stop_packet);
1131 }
1132 return GetThreadList().GetSize(false);
1133}
1134
1135
1136StateType
1137ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1138{
1139 const char stop_type = stop_packet.GetChar();
1140 switch (stop_type)
1141 {
1142 case 'T':
1143 case 'S':
1144 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001145 if (GetStopID() == 0)
1146 {
1147 // Our first stop, make sure we have a process ID, and also make
1148 // sure we know about our registers
1149 if (GetID() == LLDB_INVALID_PROCESS_ID)
1150 {
1151 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (1);
1152 if (pid != LLDB_INVALID_PROCESS_ID)
1153 SetID (pid);
1154 }
1155 BuildDynamicRegisterInfo (true);
1156 }
Chris Lattner24943d22010-06-08 16:52:24 +00001157 // Stop with signal and thread info
1158 const uint8_t signo = stop_packet.GetHexU8();
1159 std::string name;
1160 std::string value;
1161 std::string thread_name;
1162 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001163 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001164 uint32_t tid = LLDB_INVALID_THREAD_ID;
1165 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1166 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001167 ThreadSP thread_sp;
1168
Chris Lattner24943d22010-06-08 16:52:24 +00001169 while (stop_packet.GetNameColonValue(name, value))
1170 {
1171 if (name.compare("metype") == 0)
1172 {
1173 // exception type in big endian hex
1174 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1175 }
1176 else if (name.compare("mecount") == 0)
1177 {
1178 // exception count in big endian hex
1179 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1180 }
1181 else if (name.compare("medata") == 0)
1182 {
1183 // exception data in big endian hex
1184 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1185 }
1186 else if (name.compare("thread") == 0)
1187 {
1188 // thread in big endian hex
1189 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001190 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001191 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001192 if (!thread_sp)
1193 {
1194 // Create the thread if we need to
1195 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1196 m_thread_list.AddThread(thread_sp);
1197 }
Chris Lattner24943d22010-06-08 16:52:24 +00001198 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001199 else if (name.compare("hexname") == 0)
1200 {
1201 StringExtractor name_extractor;
1202 // Swap "value" over into "name_extractor"
1203 name_extractor.GetStringRef().swap(value);
1204 // Now convert the HEX bytes into a string value
1205 name_extractor.GetHexByteString (value);
1206 thread_name.swap (value);
1207 }
Chris Lattner24943d22010-06-08 16:52:24 +00001208 else if (name.compare("name") == 0)
1209 {
1210 thread_name.swap (value);
1211 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001212 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001213 {
1214 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1215 }
Greg Claytona875b642011-01-09 21:07:35 +00001216 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1217 {
1218 // We have a register number that contains an expedited
1219 // register value. Lets supply this register to our thread
1220 // so it won't have to go and read it.
1221 if (thread_sp)
1222 {
1223 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1224
1225 if (reg != UINT32_MAX)
1226 {
1227 StringExtractor reg_value_extractor;
1228 // Swap "value" over into "reg_value_extractor"
1229 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001230 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1231 {
1232 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1233 name.c_str(),
1234 reg,
1235 reg,
1236 reg_value_extractor.GetStringRef().c_str(),
1237 stop_packet.GetStringRef().c_str());
1238 }
Greg Claytona875b642011-01-09 21:07:35 +00001239 }
1240 }
1241 }
Chris Lattner24943d22010-06-08 16:52:24 +00001242 }
Chris Lattner24943d22010-06-08 16:52:24 +00001243
1244 if (thread_sp)
1245 {
1246 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1247
1248 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001249 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001250 if (exc_type != 0)
1251 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001252 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001253
1254 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1255 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001256 exc_data_size,
1257 exc_data_size >= 1 ? exc_data[0] : 0,
1258 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001259 }
1260 else if (signo)
1261 {
Greg Clayton643ee732010-08-04 01:40:35 +00001262 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001263 }
1264 else
1265 {
Greg Clayton643ee732010-08-04 01:40:35 +00001266 StopInfoSP invalid_stop_info_sp;
1267 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001268 }
1269 }
1270 return eStateStopped;
1271 }
1272 break;
1273
1274 case 'W':
1275 // process exited
1276 return eStateExited;
1277
1278 default:
1279 break;
1280 }
1281 return eStateInvalid;
1282}
1283
1284void
1285ProcessGDBRemote::RefreshStateAfterStop ()
1286{
Jim Ingham7508e732010-08-09 23:31:02 +00001287 // FIXME - add a variable to tell that we're in the middle of attaching if we
1288 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001289 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001290// if (!GetTarget().GetArchitecture().IsValid())
1291// {
1292// Module *exe_module = GetTarget().GetExecutableModule().get();
1293// if (exe_module)
1294// m_arch_spec = exe_module->GetArchitecture();
1295// }
1296
Chris Lattner24943d22010-06-08 16:52:24 +00001297 // Let all threads recover from stopping and do any clean up based
1298 // on the previous thread state (if any).
1299 m_thread_list.RefreshStateAfterStop();
1300
1301 // Discover new threads:
1302 UpdateThreadListIfNeeded ();
1303}
1304
1305Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001306ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001307{
1308 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001309
Greg Claytona4881d02011-01-22 07:12:45 +00001310 bool timed_out = false;
1311 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001312
1313 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001314 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001315 // We are being asked to halt during an attach. We need to just close
1316 // our file handle and debugserver will go away, and we can be done...
1317 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001318 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001319 else
1320 {
1321 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1322 {
1323 if (timed_out)
1324 error.SetErrorString("timed out sending interrupt packet");
1325 else
1326 error.SetErrorString("unknown error sending interrupt packet");
1327 }
1328 }
Chris Lattner24943d22010-06-08 16:52:24 +00001329 return error;
1330}
1331
1332Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001333ProcessGDBRemote::InterruptIfRunning
1334(
1335 bool discard_thread_plans,
1336 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001337 EventSP &stop_event_sp
1338)
Chris Lattner24943d22010-06-08 16:52:24 +00001339{
1340 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001341
Greg Clayton2860ba92011-01-23 19:58:49 +00001342 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1343
Greg Clayton68ca8232011-01-25 02:58:48 +00001344 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001345 const bool is_running = m_gdb_comm.IsRunning();
1346 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001347 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001348 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001349 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001350 is_running);
1351
Greg Clayton2860ba92011-01-23 19:58:49 +00001352 if (discard_thread_plans)
1353 {
1354 if (log)
1355 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1356 m_thread_list.DiscardThreadPlans();
1357 }
1358 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001359 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001360 if (catch_stop_event)
1361 {
1362 if (log)
1363 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1364 PausePrivateStateThread();
1365 paused_private_state_thread = true;
1366 }
1367
Greg Clayton4fb400f2010-09-27 21:07:38 +00001368 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001369 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001370 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001371
Greg Clayton72e1c782011-01-22 23:43:18 +00001372 //m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
1373 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001374 {
1375 if (timed_out)
1376 error.SetErrorString("timed out sending interrupt packet");
1377 else
1378 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001379 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001380 ResumePrivateStateThread();
1381 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001382 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001383
Greg Clayton72e1c782011-01-22 23:43:18 +00001384 if (catch_stop_event)
1385 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001386 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001387 TimeValue timeout_time;
1388 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001389 timeout_time.OffsetWithSeconds(5);
1390 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001391
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001392 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001393 if (log)
1394 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001395
Greg Clayton2860ba92011-01-23 19:58:49 +00001396 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001397 error.SetErrorString("unable to verify target stopped");
1398 }
1399
Greg Clayton68ca8232011-01-25 02:58:48 +00001400 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001401 {
1402 if (log)
1403 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001404 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001405 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001406 }
Chris Lattner24943d22010-06-08 16:52:24 +00001407 return error;
1408}
1409
Greg Clayton4fb400f2010-09-27 21:07:38 +00001410Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001411ProcessGDBRemote::WillDetach ()
1412{
Greg Clayton2860ba92011-01-23 19:58:49 +00001413 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1414 if (log)
1415 log->Printf ("ProcessGDBRemote::WillDetach()");
1416
Greg Clayton72e1c782011-01-22 23:43:18 +00001417 bool discard_thread_plans = true;
1418 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001419 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001420 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001421}
1422
1423Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001424ProcessGDBRemote::DoDetach()
1425{
1426 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001427 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001428 if (log)
1429 log->Printf ("ProcessGDBRemote::DoDetach()");
1430
1431 DisableAllBreakpointSites ();
1432
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001433 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001434
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001435 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1436 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001437 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001438 if (response_size)
1439 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1440 else
1441 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001442 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001443 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001444 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001445
Greg Clayton4fb400f2010-09-27 21:07:38 +00001446 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001447 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001448
1449 SetPrivateState (eStateDetached);
1450 ResumePrivateStateThread();
1451
1452 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001453 return error;
1454}
Chris Lattner24943d22010-06-08 16:52:24 +00001455
1456Error
1457ProcessGDBRemote::DoDestroy ()
1458{
1459 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001460 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001461 if (log)
1462 log->Printf ("ProcessGDBRemote::DoDestroy()");
1463
1464 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001465 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001466 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001467 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001468 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001469 // We are being asked to halt during an attach. We need to just close
1470 // our file handle and debugserver will go away, and we can be done...
1471 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001472 }
1473 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001474 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001475
1476 StringExtractorGDBRemote response;
1477 bool send_async = true;
1478 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, 2, send_async))
1479 {
1480 char packet_cmd = response.GetChar(0);
1481
1482 if (packet_cmd == 'W' || packet_cmd == 'X')
1483 {
1484 m_last_stop_packet = response;
1485 SetExitStatus(response.GetHexU8(), NULL);
1486 }
1487 }
1488 else
1489 {
1490 SetExitStatus(SIGABRT, NULL);
1491 //error.SetErrorString("kill packet failed");
1492 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001493 }
1494 }
Chris Lattner24943d22010-06-08 16:52:24 +00001495 StopAsyncThread ();
1496 m_gdb_comm.StopReadThread();
1497 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001498 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001499 return error;
1500}
1501
Chris Lattner24943d22010-06-08 16:52:24 +00001502//------------------------------------------------------------------
1503// Process Queries
1504//------------------------------------------------------------------
1505
1506bool
1507ProcessGDBRemote::IsAlive ()
1508{
Greg Clayton58e844b2010-12-08 05:08:21 +00001509 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001510}
1511
1512addr_t
1513ProcessGDBRemote::GetImageInfoAddress()
1514{
1515 if (!m_gdb_comm.IsRunning())
1516 {
1517 StringExtractorGDBRemote response;
1518 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1519 {
1520 if (response.IsNormalPacket())
1521 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1522 }
1523 }
1524 return LLDB_INVALID_ADDRESS;
1525}
1526
Chris Lattner24943d22010-06-08 16:52:24 +00001527//------------------------------------------------------------------
1528// Process Memory
1529//------------------------------------------------------------------
1530size_t
1531ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1532{
1533 if (size > m_max_memory_size)
1534 {
1535 // Keep memory read sizes down to a sane limit. This function will be
1536 // called multiple times in order to complete the task by
1537 // lldb_private::Process so it is ok to do this.
1538 size = m_max_memory_size;
1539 }
1540
1541 char packet[64];
1542 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1543 assert (packet_len + 1 < sizeof(packet));
1544 StringExtractorGDBRemote response;
1545 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1546 {
1547 if (response.IsNormalPacket())
1548 {
1549 error.Clear();
1550 return response.GetHexBytes(buf, size, '\xdd');
1551 }
1552 else if (response.IsErrorPacket())
1553 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1554 else if (response.IsUnsupportedPacket())
1555 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1556 else
1557 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1558 }
1559 else
1560 {
1561 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1562 }
1563 return 0;
1564}
1565
1566size_t
1567ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1568{
1569 StreamString packet;
1570 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001571 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001572 StringExtractorGDBRemote response;
1573 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1574 {
1575 if (response.IsOKPacket())
1576 {
1577 error.Clear();
1578 return size;
1579 }
1580 else if (response.IsErrorPacket())
1581 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1582 else if (response.IsUnsupportedPacket())
1583 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1584 else
1585 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1586 }
1587 else
1588 {
1589 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1590 }
1591 return 0;
1592}
1593
1594lldb::addr_t
1595ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1596{
1597 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1598 if (allocated_addr == LLDB_INVALID_ADDRESS)
1599 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1600 else
1601 error.Clear();
1602 return allocated_addr;
1603}
1604
1605Error
1606ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1607{
1608 Error error;
1609 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1610 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1611 return error;
1612}
1613
1614
1615//------------------------------------------------------------------
1616// Process STDIO
1617//------------------------------------------------------------------
1618
1619size_t
1620ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1621{
1622 Mutex::Locker locker(m_stdio_mutex);
1623 size_t bytes_available = m_stdout_data.size();
1624 if (bytes_available > 0)
1625 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001626 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1627 if (log)
1628 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001629 if (bytes_available > buf_size)
1630 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001631 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001632 m_stdout_data.erase(0, buf_size);
1633 bytes_available = buf_size;
1634 }
1635 else
1636 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001637 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001638 m_stdout_data.clear();
1639
1640 //ResetEventBits(eBroadcastBitSTDOUT);
1641 }
1642 }
1643 return bytes_available;
1644}
1645
1646size_t
1647ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1648{
1649 // Can we get STDERR through the remote protocol?
1650 return 0;
1651}
1652
1653size_t
1654ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1655{
1656 if (m_stdio_communication.IsConnected())
1657 {
1658 ConnectionStatus status;
1659 m_stdio_communication.Write(src, src_len, status, NULL);
1660 }
1661 return 0;
1662}
1663
1664Error
1665ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1666{
1667 Error error;
1668 assert (bp_site != NULL);
1669
Greg Claytone005f2c2010-11-06 01:53:30 +00001670 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001671 user_id_t site_id = bp_site->GetID();
1672 const addr_t addr = bp_site->GetLoadAddress();
1673 if (log)
1674 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1675
1676 if (bp_site->IsEnabled())
1677 {
1678 if (log)
1679 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1680 return error;
1681 }
1682 else
1683 {
1684 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1685
1686 if (bp_site->HardwarePreferred())
1687 {
1688 // Try and set hardware breakpoint, and if that fails, fall through
1689 // and set a software breakpoint?
1690 }
1691
1692 if (m_z0_supported)
1693 {
1694 char packet[64];
1695 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1696 assert (packet_len + 1 < sizeof(packet));
1697 StringExtractorGDBRemote response;
1698 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1699 {
1700 if (response.IsUnsupportedPacket())
1701 {
1702 // Disable z packet support and try again
1703 m_z0_supported = 0;
1704 return EnableBreakpoint (bp_site);
1705 }
1706 else if (response.IsOKPacket())
1707 {
1708 bp_site->SetEnabled(true);
1709 bp_site->SetType (BreakpointSite::eExternal);
1710 return error;
1711 }
1712 else
1713 {
1714 uint8_t error_byte = response.GetError();
1715 if (error_byte)
1716 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1717 }
1718 }
1719 }
1720 else
1721 {
1722 return EnableSoftwareBreakpoint (bp_site);
1723 }
1724 }
1725
1726 if (log)
1727 {
1728 const char *err_string = error.AsCString();
1729 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1730 bp_site->GetLoadAddress(),
1731 err_string ? err_string : "NULL");
1732 }
1733 // We shouldn't reach here on a successful breakpoint enable...
1734 if (error.Success())
1735 error.SetErrorToGenericError();
1736 return error;
1737}
1738
1739Error
1740ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1741{
1742 Error error;
1743 assert (bp_site != NULL);
1744 addr_t addr = bp_site->GetLoadAddress();
1745 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001746 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001747 if (log)
1748 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1749
1750 if (bp_site->IsEnabled())
1751 {
1752 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1753
1754 if (bp_site->IsHardware())
1755 {
1756 // TODO: disable hardware breakpoint...
1757 }
1758 else
1759 {
1760 if (m_z0_supported)
1761 {
1762 char packet[64];
1763 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1764 assert (packet_len + 1 < sizeof(packet));
1765 StringExtractorGDBRemote response;
1766 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1767 {
1768 if (response.IsUnsupportedPacket())
1769 {
1770 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1771 }
1772 else if (response.IsOKPacket())
1773 {
1774 if (log)
1775 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1776 bp_site->SetEnabled(false);
1777 return error;
1778 }
1779 else
1780 {
1781 uint8_t error_byte = response.GetError();
1782 if (error_byte)
1783 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1784 }
1785 }
1786 }
1787 else
1788 {
1789 return DisableSoftwareBreakpoint (bp_site);
1790 }
1791 }
1792 }
1793 else
1794 {
1795 if (log)
1796 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1797 return error;
1798 }
1799
1800 if (error.Success())
1801 error.SetErrorToGenericError();
1802 return error;
1803}
1804
1805Error
1806ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1807{
1808 Error error;
1809 if (wp)
1810 {
1811 user_id_t watchID = wp->GetID();
1812 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001813 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001814 if (log)
1815 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1816 if (wp->IsEnabled())
1817 {
1818 if (log)
1819 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1820 return error;
1821 }
1822 else
1823 {
1824 // Pass down an appropriate z/Z packet...
1825 error.SetErrorString("watchpoints not supported");
1826 }
1827 }
1828 else
1829 {
1830 error.SetErrorString("Watchpoint location argument was NULL.");
1831 }
1832 if (error.Success())
1833 error.SetErrorToGenericError();
1834 return error;
1835}
1836
1837Error
1838ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1839{
1840 Error error;
1841 if (wp)
1842 {
1843 user_id_t watchID = wp->GetID();
1844
Greg Claytone005f2c2010-11-06 01:53:30 +00001845 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001846
1847 addr_t addr = wp->GetLoadAddress();
1848 if (log)
1849 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1850
1851 if (wp->IsHardware())
1852 {
1853 // Pass down an appropriate z/Z packet...
1854 error.SetErrorString("watchpoints not supported");
1855 }
1856 // TODO: clear software watchpoints if we implement them
1857 }
1858 else
1859 {
1860 error.SetErrorString("Watchpoint location argument was NULL.");
1861 }
1862 if (error.Success())
1863 error.SetErrorToGenericError();
1864 return error;
1865}
1866
1867void
1868ProcessGDBRemote::Clear()
1869{
1870 m_flags = 0;
1871 m_thread_list.Clear();
1872 {
1873 Mutex::Locker locker(m_stdio_mutex);
1874 m_stdout_data.clear();
1875 }
Chris Lattner24943d22010-06-08 16:52:24 +00001876}
1877
1878Error
1879ProcessGDBRemote::DoSignal (int signo)
1880{
1881 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001882 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001883 if (log)
1884 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1885
1886 if (!m_gdb_comm.SendAsyncSignal (signo))
1887 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1888 return error;
1889}
1890
Chris Lattner24943d22010-06-08 16:52:24 +00001891Error
1892ProcessGDBRemote::StartDebugserverProcess
1893(
1894 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1895 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1896 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Claytonde915be2011-01-23 05:56:20 +00001897 const char *stdin_path,
1898 const char *stdout_path,
1899 const char *stderr_path,
1900 const char *working_dir,
Greg Clayton23cf0c72010-11-08 04:29:11 +00001901 bool launch_process, // Set to true if we are going to be launching a the process
1902 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 +00001903 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1904 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Caroline Ticebd666012010-12-03 18:46:09 +00001905 uint32_t launch_flags, // Launch flags
Chris Lattner24943d22010-06-08 16:52:24 +00001906 ArchSpec& inferior_arch // The arch of the inferior that we will launch
1907)
1908{
1909 Error error;
Caroline Ticebd666012010-12-03 18:46:09 +00001910 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0;
1911 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001912 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1913 {
1914 // If we locate debugserver, keep that located version around
1915 static FileSpec g_debugserver_file_spec;
1916
1917 FileSpec debugserver_file_spec;
1918 char debugserver_path[PATH_MAX];
1919
1920 // Always check to see if we have an environment override for the path
1921 // to the debugserver to use and use it if we do.
1922 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1923 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001924 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001925 else
1926 debugserver_file_spec = g_debugserver_file_spec;
1927 bool debugserver_exists = debugserver_file_spec.Exists();
1928 if (!debugserver_exists)
1929 {
1930 // The debugserver binary is in the LLDB.framework/Resources
1931 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001932 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001933 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001934 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001935 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001936 if (debugserver_exists)
1937 {
1938 g_debugserver_file_spec = debugserver_file_spec;
1939 }
1940 else
1941 {
1942 g_debugserver_file_spec.Clear();
1943 debugserver_file_spec.Clear();
1944 }
Chris Lattner24943d22010-06-08 16:52:24 +00001945 }
1946 }
1947
1948 if (debugserver_exists)
1949 {
1950 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1951
1952 m_stdio_communication.Clear();
1953 posix_spawnattr_t attr;
1954
Greg Claytone005f2c2010-11-06 01:53:30 +00001955 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001956
1957 Error local_err; // Errors that don't affect the spawning.
1958 if (log)
Greg Clayton940b1032011-02-23 00:35:02 +00001959 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )",
1960 __FUNCTION__,
1961 debugserver_path,
1962 inferior_argv,
1963 inferior_envp,
1964 inferior_arch.GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +00001965 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1966 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001967 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001968 if (error.Fail())
Greg Clayton940b1032011-02-23 00:35:02 +00001969 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001970
1971#if !defined (__arm__)
1972
Greg Clayton24b48ff2010-10-17 22:03:32 +00001973 // We don't need to do this for ARM, and we really shouldn't now
1974 // that we have multiple CPU subtypes and no posix_spawnattr call
1975 // that allows us to set which CPU subtype to launch...
Greg Clayton940b1032011-02-23 00:35:02 +00001976 cpu_type_t cpu = inferior_arch.GetMachOCPUType();
1977 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE)
Chris Lattner24943d22010-06-08 16:52:24 +00001978 {
Greg Clayton940b1032011-02-23 00:35:02 +00001979 size_t ocount = 0;
1980 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1981 if (error.Fail() || log)
1982 error.PutToLog(log.get(), "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount);
1983
1984 if (error.Fail() != 0 || ocount != 1)
1985 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001986 }
1987
1988#endif
1989
1990 Args debugserver_args;
1991 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001992
Chris Lattner24943d22010-06-08 16:52:24 +00001993 lldb_utility::PseudoTerminal pty;
Greg Claytonde915be2011-01-23 05:56:20 +00001994 const char *stdio_path = NULL;
1995 if (launch_process &&
Caroline Ticee4450f02011-01-28 00:19:58 +00001996 (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) &&
Greg Claytonde915be2011-01-23 05:56:20 +00001997 m_local_debugserver &&
1998 no_stdio == false)
Chris Lattner24943d22010-06-08 16:52:24 +00001999 {
Chris Lattner24943d22010-06-08 16:52:24 +00002000 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Caroline Ticee4450f02011-01-28 00:19:58 +00002001 {
2002 const char *slave_name = pty.GetSlaveName (NULL, 0);
2003 if (stdin_path == NULL
2004 && stdout_path == NULL
2005 && stderr_path == NULL)
2006 stdio_path = slave_name;
2007 else
2008 {
2009 if (stdin_path == NULL)
2010 stdin_path = slave_name;
2011 if (stdout_path == NULL)
2012 stdout_path = slave_name;
2013 if (stderr_path == NULL)
2014 stderr_path = slave_name;
2015 }
2016 }
Chris Lattner24943d22010-06-08 16:52:24 +00002017 }
2018
2019 // Start args with "debugserver /file/path -r --"
2020 debugserver_args.AppendArgument(debugserver_path);
2021 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002022 // use native registers, not the GDB registers
2023 debugserver_args.AppendArgument("--native-regs");
2024 // make debugserver run in its own session so signals generated by
2025 // special terminal key sequences (^C) don't affect debugserver
2026 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002027
Greg Clayton452bf612010-08-31 18:35:14 +00002028 if (disable_aslr)
2029 debugserver_args.AppendArguments("--disable-aslr");
2030
Chris Lattner24943d22010-06-08 16:52:24 +00002031 // Only set the inferior
Greg Claytonde915be2011-01-23 05:56:20 +00002032 if (launch_process)
Chris Lattner24943d22010-06-08 16:52:24 +00002033 {
Greg Claytonde915be2011-01-23 05:56:20 +00002034 if (no_stdio)
2035 debugserver_args.AppendArgument("--no-stdio");
2036 else
2037 {
2038 if (stdin_path && stdout_path && stderr_path &&
2039 strcmp(stdin_path, stdout_path) == 0 &&
2040 strcmp(stdin_path, stderr_path) == 0)
2041 {
2042 stdio_path = stdin_path;
2043 stdin_path = stdout_path = stderr_path = NULL;
2044 }
2045
2046 if (stdio_path)
2047 {
2048 // All file handles to stdin, stdout, stderr are the same...
2049 debugserver_args.AppendArgument("--stdio-path");
2050 debugserver_args.AppendArgument(stdio_path);
2051 }
2052 else
2053 {
2054 if (stdin_path == NULL && (stdout_path || stderr_path))
2055 stdin_path = "/dev/null";
2056
2057 if (stdout_path == NULL && (stdin_path || stderr_path))
2058 stdout_path = "/dev/null";
2059
2060 if (stderr_path == NULL && (stdin_path || stdout_path))
2061 stderr_path = "/dev/null";
2062
2063 if (stdin_path)
2064 {
2065 debugserver_args.AppendArgument("--stdin-path");
2066 debugserver_args.AppendArgument(stdin_path);
2067 }
2068 if (stdout_path)
2069 {
2070 debugserver_args.AppendArgument("--stdout-path");
2071 debugserver_args.AppendArgument(stdout_path);
2072 }
2073 if (stderr_path)
2074 {
2075 debugserver_args.AppendArgument("--stderr-path");
2076 debugserver_args.AppendArgument(stderr_path);
2077 }
2078 }
2079 }
Chris Lattner24943d22010-06-08 16:52:24 +00002080 }
Greg Claytonde915be2011-01-23 05:56:20 +00002081
2082 if (working_dir)
Caroline Ticebd666012010-12-03 18:46:09 +00002083 {
Greg Claytonde915be2011-01-23 05:56:20 +00002084 debugserver_args.AppendArgument("--working-dir");
2085 debugserver_args.AppendArgument(working_dir);
Caroline Ticebd666012010-12-03 18:46:09 +00002086 }
Chris Lattner24943d22010-06-08 16:52:24 +00002087
2088 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2089 if (env_debugserver_log_file)
2090 {
2091 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2092 debugserver_args.AppendArgument(arg_cstr);
2093 }
2094
2095 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2096 if (env_debugserver_log_flags)
2097 {
2098 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2099 debugserver_args.AppendArgument(arg_cstr);
2100 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002101// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002102// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002103
2104 // Now append the program arguments
2105 if (launch_process)
2106 {
2107 if (inferior_argv)
2108 {
2109 // Terminate the debugserver args so we can now append the inferior args
2110 debugserver_args.AppendArgument("--");
2111
2112 for (int i = 0; inferior_argv[i] != NULL; ++i)
2113 debugserver_args.AppendArgument (inferior_argv[i]);
2114 }
2115 else
2116 {
2117 // Will send environment entries with the 'QEnvironment:' packet
2118 // Will send arguments with the 'A' packet
2119 }
2120 }
2121 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2122 {
2123 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2124 debugserver_args.AppendArgument (arg_cstr);
2125 }
2126 else if (attach_name && attach_name[0])
2127 {
2128 if (wait_for_launch)
2129 debugserver_args.AppendArgument ("--waitfor");
2130 else
2131 debugserver_args.AppendArgument ("--attach");
2132 debugserver_args.AppendArgument (attach_name);
2133 }
2134
2135 Error file_actions_err;
2136 posix_spawn_file_actions_t file_actions;
2137#if DONT_CLOSE_DEBUGSERVER_STDIO
2138 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
2139#else
2140 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
2141 if (file_actions_err.Success())
2142 {
2143 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
2144 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
2145 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
2146 }
2147#endif
2148
2149 if (log)
2150 {
2151 StreamString strm;
2152 debugserver_args.Dump (&strm);
2153 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2154 }
2155
Greg Clayton72e1c782011-01-22 23:43:18 +00002156 error.SetError (::posix_spawnp (&m_debugserver_pid,
2157 debugserver_path,
2158 file_actions_err.Success() ? &file_actions : NULL,
2159 &attr,
2160 debugserver_args.GetArgumentVector(),
2161 (char * const*)inferior_envp),
2162 eErrorTypePOSIX);
2163
Greg Claytone9d0df42010-07-02 01:29:13 +00002164
2165 ::posix_spawnattr_destroy (&attr);
2166
Chris Lattner24943d22010-06-08 16:52:24 +00002167 if (file_actions_err.Success())
2168 ::posix_spawn_file_actions_destroy (&file_actions);
2169
2170 // We have seen some cases where posix_spawnp was returning a valid
2171 // looking pid even when an error was returned, so clear it out
2172 if (error.Fail())
2173 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2174
2175 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002176 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 +00002177
Caroline Ticebd666012010-12-03 18:46:09 +00002178 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio)
Caroline Tice91a1dab2010-11-05 22:37:44 +00002179 {
Greg Clayton23cf0c72010-11-08 04:29:11 +00002180 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Caroline Tice861efb32010-11-16 05:07:41 +00002181 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
Caroline Tice91a1dab2010-11-05 22:37:44 +00002182 }
Chris Lattner24943d22010-06-08 16:52:24 +00002183 }
2184 else
2185 {
2186 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2187 }
2188
2189 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2190 StartAsyncThread ();
2191 }
2192 return error;
2193}
2194
2195bool
2196ProcessGDBRemote::MonitorDebugserverProcess
2197(
2198 void *callback_baton,
2199 lldb::pid_t debugserver_pid,
2200 int signo, // Zero for no signal
2201 int exit_status // Exit value of process if signal is zero
2202)
2203{
2204 // We pass in the ProcessGDBRemote inferior process it and name it
2205 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2206 // pointer value itself, thus we need the double cast...
2207
2208 // "debugserver_pid" argument passed in is the process ID for
2209 // debugserver that we are tracking...
2210
Greg Clayton75ccf502010-08-21 02:22:51 +00002211 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002212
2213 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2214 if (log)
2215 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2216
Greg Clayton75ccf502010-08-21 02:22:51 +00002217 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002218 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002219 // Sleep for a half a second to make sure our inferior process has
2220 // time to set its exit status before we set it incorrectly when
2221 // both the debugserver and the inferior process shut down.
2222 usleep (500000);
2223 // If our process hasn't yet exited, debugserver might have died.
2224 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002225 const StateType state = process->GetState();
2226
2227 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2228 state != eStateInvalid &&
2229 state != eStateUnloaded &&
2230 state != eStateExited &&
2231 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002232 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002233 char error_str[1024];
2234 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002235 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002236 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2237 if (signal_cstr)
2238 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002239 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002240 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002241 }
2242 else
2243 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002244 ::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 +00002245 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002246
2247 process->SetExitStatus (-1, error_str);
2248 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002249 // Debugserver has exited we need to let our ProcessGDBRemote
2250 // know that it no longer has a debugserver instance
2251 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2252 // We are returning true to this function below, so we can
2253 // forget about the monitor handle.
2254 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002255 }
2256 return true;
2257}
2258
2259void
2260ProcessGDBRemote::KillDebugserverProcess ()
2261{
2262 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2263 {
2264 ::kill (m_debugserver_pid, SIGINT);
2265 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2266 }
2267}
2268
2269void
2270ProcessGDBRemote::Initialize()
2271{
2272 static bool g_initialized = false;
2273
2274 if (g_initialized == false)
2275 {
2276 g_initialized = true;
2277 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2278 GetPluginDescriptionStatic(),
2279 CreateInstance);
2280
2281 Log::Callbacks log_callbacks = {
2282 ProcessGDBRemoteLog::DisableLog,
2283 ProcessGDBRemoteLog::EnableLog,
2284 ProcessGDBRemoteLog::ListLogCategories
2285 };
2286
2287 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2288 }
2289}
2290
2291bool
2292ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2293{
2294 if (m_curr_tid == tid)
2295 return true;
2296
2297 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002298 int packet_len;
2299 if (tid <= 0)
2300 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2301 else
2302 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002303 assert (packet_len + 1 < sizeof(packet));
2304 StringExtractorGDBRemote response;
2305 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2306 {
2307 if (response.IsOKPacket())
2308 {
2309 m_curr_tid = tid;
2310 return true;
2311 }
2312 }
2313 return false;
2314}
2315
2316bool
2317ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2318{
2319 if (m_curr_tid_run == tid)
2320 return true;
2321
2322 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002323 int packet_len;
2324 if (tid <= 0)
2325 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2326 else
2327 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2328
Chris Lattner24943d22010-06-08 16:52:24 +00002329 assert (packet_len + 1 < sizeof(packet));
2330 StringExtractorGDBRemote response;
2331 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2332 {
2333 if (response.IsOKPacket())
2334 {
2335 m_curr_tid_run = tid;
2336 return true;
2337 }
2338 }
2339 return false;
2340}
2341
2342void
2343ProcessGDBRemote::ResetGDBRemoteState ()
2344{
2345 // Reset and GDB remote state
2346 m_curr_tid = LLDB_INVALID_THREAD_ID;
2347 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2348 m_z0_supported = 1;
2349}
2350
2351
2352bool
2353ProcessGDBRemote::StartAsyncThread ()
2354{
2355 ResetGDBRemoteState ();
2356
Greg Claytone005f2c2010-11-06 01:53:30 +00002357 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002358
2359 if (log)
2360 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2361
2362 // Create a thread that watches our internal state and controls which
2363 // events make it to clients (into the DCProcess event queue).
2364 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002365 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002366}
2367
2368void
2369ProcessGDBRemote::StopAsyncThread ()
2370{
Greg Claytone005f2c2010-11-06 01:53:30 +00002371 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002372
2373 if (log)
2374 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2375
2376 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2377
2378 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002379 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002380 {
2381 Host::ThreadJoin (m_async_thread, NULL, NULL);
2382 }
2383}
2384
2385
2386void *
2387ProcessGDBRemote::AsyncThread (void *arg)
2388{
2389 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2390
Greg Claytone005f2c2010-11-06 01:53:30 +00002391 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002392 if (log)
2393 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2394
2395 Listener listener ("ProcessGDBRemote::AsyncThread");
2396 EventSP event_sp;
2397 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2398 eBroadcastBitAsyncThreadShouldExit;
2399
2400 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2401 {
2402 bool done = false;
2403 while (!done)
2404 {
2405 if (log)
2406 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2407 if (listener.WaitForEvent (NULL, event_sp))
2408 {
2409 const uint32_t event_type = event_sp->GetType();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002410 if (log)
2411 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2412
Chris Lattner24943d22010-06-08 16:52:24 +00002413 switch (event_type)
2414 {
2415 case eBroadcastBitAsyncContinue:
2416 {
2417 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2418
2419 if (continue_packet)
2420 {
2421 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2422 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2423 if (log)
2424 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2425
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002426 if (::strstr (continue_cstr, "vAttach") == NULL)
2427 process->SetPrivateState(eStateRunning);
Chris Lattner24943d22010-06-08 16:52:24 +00002428 StringExtractorGDBRemote response;
2429 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2430
2431 switch (stop_state)
2432 {
2433 case eStateStopped:
2434 case eStateCrashed:
2435 case eStateSuspended:
2436 process->m_last_stop_packet = response;
2437 process->m_last_stop_packet.SetFilePos (0);
2438 process->SetPrivateState (stop_state);
2439 break;
2440
2441 case eStateExited:
2442 process->m_last_stop_packet = response;
2443 process->m_last_stop_packet.SetFilePos (0);
2444 response.SetFilePos(1);
2445 process->SetExitStatus(response.GetHexU8(), NULL);
2446 done = true;
2447 break;
2448
2449 case eStateInvalid:
2450 break;
2451
2452 default:
2453 process->SetPrivateState (stop_state);
2454 break;
2455 }
2456 }
2457 }
2458 break;
2459
2460 case eBroadcastBitAsyncThreadShouldExit:
2461 if (log)
2462 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2463 done = true;
2464 break;
2465
2466 default:
2467 if (log)
2468 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2469 done = true;
2470 break;
2471 }
2472 }
2473 else
2474 {
2475 if (log)
2476 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2477 done = true;
2478 }
2479 }
2480 }
2481
2482 if (log)
2483 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2484
2485 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2486 return NULL;
2487}
2488
Chris Lattner24943d22010-06-08 16:52:24 +00002489const char *
2490ProcessGDBRemote::GetDispatchQueueNameForThread
2491(
2492 addr_t thread_dispatch_qaddr,
2493 std::string &dispatch_queue_name
2494)
2495{
2496 dispatch_queue_name.clear();
2497 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2498 {
2499 // Cache the dispatch_queue_offsets_addr value so we don't always have
2500 // to look it up
2501 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2502 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002503 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2504 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002505 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002506 if (module_sp)
2507 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2508
2509 if (dispatch_queue_offsets_symbol == NULL)
2510 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002511 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002512 if (module_sp)
2513 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2514 }
Chris Lattner24943d22010-06-08 16:52:24 +00002515 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002516 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002517
2518 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2519 return NULL;
2520 }
2521
2522 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002523 DataExtractor data (memory_buffer,
2524 sizeof(memory_buffer),
2525 m_target.GetArchitecture().GetByteOrder(),
2526 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002527
2528 // Excerpt from src/queue_private.h
2529 struct dispatch_queue_offsets_s
2530 {
2531 uint16_t dqo_version;
2532 uint16_t dqo_label;
2533 uint16_t dqo_label_size;
2534 } dispatch_queue_offsets;
2535
2536
2537 Error error;
2538 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2539 {
2540 uint32_t data_offset = 0;
2541 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2542 {
2543 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2544 {
2545 data_offset = 0;
2546 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2547 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2548 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2549 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2550 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2551 dispatch_queue_name.erase (bytes_read);
2552 }
2553 }
2554 }
2555 }
2556 if (dispatch_queue_name.empty())
2557 return NULL;
2558 return dispatch_queue_name.c_str();
2559}
2560
Jim Ingham7508e732010-08-09 23:31:02 +00002561uint32_t
2562ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2563{
2564 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2565 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2566 if (m_local_debugserver)
2567 {
2568 return Host::ListProcessesMatchingName (name, matches, pids);
2569 }
2570 else
2571 {
2572 // FIXME: Implement talking to the remote debugserver.
2573 return 0;
2574 }
2575
2576}
Jim Ingham55e01d82011-01-22 01:33:44 +00002577
2578bool
2579ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2580 lldb_private::StoppointCallbackContext *context,
2581 lldb::user_id_t break_id,
2582 lldb::user_id_t break_loc_id)
2583{
2584 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2585 // run so I can stop it if that's what I want to do.
2586 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2587 if (log)
2588 log->Printf("Hit New Thread Notification breakpoint.");
2589 return false;
2590}
2591
2592
2593bool
2594ProcessGDBRemote::StartNoticingNewThreads()
2595{
2596 static const char *bp_names[] =
2597 {
2598 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002599 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002600 "_pthread_start",
2601 NULL
2602 };
2603
2604 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2605 size_t num_bps = m_thread_observation_bps.size();
2606 if (num_bps != 0)
2607 {
2608 for (int i = 0; i < num_bps; i++)
2609 {
2610 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2611 if (break_sp)
2612 {
2613 if (log)
2614 log->Printf("Enabled noticing new thread breakpoint.");
2615 break_sp->SetEnabled(true);
2616 }
2617 }
2618 }
2619 else
2620 {
2621 for (int i = 0; bp_names[i] != NULL; i++)
2622 {
2623 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2624 if (breakpoint)
2625 {
2626 if (log)
2627 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2628 m_thread_observation_bps.push_back(breakpoint->GetID());
2629 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2630 }
2631 else
2632 {
2633 if (log)
2634 log->Printf("Failed to create new thread notification breakpoint.");
2635 return false;
2636 }
2637 }
2638 }
2639
2640 return true;
2641}
2642
2643bool
2644ProcessGDBRemote::StopNoticingNewThreads()
2645{
Jim Inghamff276fe2011-02-08 05:19:01 +00002646 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2647 if (log)
2648 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002649 size_t num_bps = m_thread_observation_bps.size();
2650 if (num_bps != 0)
2651 {
2652 for (int i = 0; i < num_bps; i++)
2653 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002654
2655 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2656 if (break_sp)
2657 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002658 break_sp->SetEnabled(false);
2659 }
2660 }
2661 }
2662 return true;
2663}
2664
2665