blob: df09bf37d9595504e9dcd38e6156014bb95d1d97 [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 Claytona2f74232011-02-24 22:24:29 +0000443 // Make sure we aren't already connected?
444 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000445 {
446 error = StartDebugserverProcess (host_port,
447 NULL,
448 NULL,
Chris Lattner24943d22010-06-08 16:52:24 +0000449 LLDB_INVALID_PROCESS_ID,
Greg Claytonde915be2011-01-23 05:56:20 +0000450 NULL,
451 false,
Chris Lattner24943d22010-06-08 16:52:24 +0000452 inferior_arch);
453 if (error.Fail())
454 return error;
455
Greg Claytone71e2582011-02-04 01:58:07 +0000456 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000457 }
458
459 if (error.Success())
460 {
461 lldb_utility::PseudoTerminal pty;
462 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000463
464 // If the debugserver is local and we aren't disabling STDIO, lets use
465 // a pseudo terminal to instead of relying on the 'O' packets for stdio
466 // since 'O' packets can really slow down debugging if the inferior
467 // does a lot of output.
468 if (m_local_debugserver && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000469 {
470 const char *slave_name = NULL;
471 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000472 {
Greg Claytona2f74232011-02-24 22:24:29 +0000473 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
474 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000475 }
Greg Claytona2f74232011-02-24 22:24:29 +0000476 if (stdin_path == NULL)
477 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000478
Greg Claytona2f74232011-02-24 22:24:29 +0000479 if (stdout_path == NULL)
480 stdout_path = slave_name;
481
482 if (stderr_path == NULL)
483 stderr_path = slave_name;
484 }
485
Greg Claytonafb81862011-03-02 21:34:46 +0000486 // Set STDIN to /dev/null if we want STDIO disabled or if either
487 // STDOUT or STDERR have been set to something and STDIN hasn't
488 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000489 stdin_path = "/dev/null";
490
Greg Claytonafb81862011-03-02 21:34:46 +0000491 // Set STDOUT to /dev/null if we want STDIO disabled or if either
492 // STDIN or STDERR have been set to something and STDOUT hasn't
493 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000494 stdout_path = "/dev/null";
495
Greg Claytonafb81862011-03-02 21:34:46 +0000496 // Set STDERR to /dev/null if we want STDIO disabled or if either
497 // STDIN or STDOUT have been set to something and STDERR hasn't
498 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000499 stderr_path = "/dev/null";
500
501 if (stdin_path)
502 m_gdb_comm.SetSTDIN (stdin_path);
503 if (stdout_path)
504 m_gdb_comm.SetSTDOUT (stdout_path);
505 if (stderr_path)
506 m_gdb_comm.SetSTDERR (stderr_path);
507
508 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
509
510
511 if (working_dir && working_dir[0])
512 {
513 m_gdb_comm.SetWorkingDir (working_dir);
514 }
515
516 // Send the environment and the program + arguments after we connect
517 if (envp)
518 {
519 const char *env_entry;
520 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000521 {
Greg Claytona2f74232011-02-24 22:24:29 +0000522 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0)
523 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000524 }
Greg Claytona2f74232011-02-24 22:24:29 +0000525 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000526
Greg Claytona2f74232011-02-24 22:24:29 +0000527 const uint32_t arg_timeout_seconds = 10;
528 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds);
529 if (arg_packet_err == 0)
530 {
531 std::string error_str;
532 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000533 {
Greg Claytona2f74232011-02-24 22:24:29 +0000534 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout));
Chris Lattner24943d22010-06-08 16:52:24 +0000535 }
536 else
537 {
Greg Claytona2f74232011-02-24 22:24:29 +0000538 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000539 }
Greg Claytona2f74232011-02-24 22:24:29 +0000540 }
541 else
542 {
543 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
544 }
Chris Lattner24943d22010-06-08 16:52:24 +0000545
Greg Claytona2f74232011-02-24 22:24:29 +0000546 if (GetID() == LLDB_INVALID_PROCESS_ID)
547 {
548 KillDebugserverProcess ();
549 return error;
550 }
551
552 StringExtractorGDBRemote response;
553 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false))
554 {
555 SetPrivateState (SetThreadStopInfo (response));
556
557 if (!disable_stdio)
558 {
559 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
560 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
561 }
Chris Lattner24943d22010-06-08 16:52:24 +0000562 }
563 }
Chris Lattner24943d22010-06-08 16:52:24 +0000564 }
565 else
566 {
567 // Set our user ID to an invalid process ID.
568 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000569 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
570 module->GetFileSpec().GetFilename().AsCString(),
571 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000572 }
Chris Lattner24943d22010-06-08 16:52:24 +0000573 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000574
Chris Lattner24943d22010-06-08 16:52:24 +0000575}
576
577
578Error
Greg Claytone71e2582011-02-04 01:58:07 +0000579ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000580{
581 Error error;
582 // Sleep and wait a bit for debugserver to start to listen...
583 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
584 if (conn_ap.get())
585 {
Chris Lattner24943d22010-06-08 16:52:24 +0000586 const uint32_t max_retry_count = 50;
587 uint32_t retry_count = 0;
588 while (!m_gdb_comm.IsConnected())
589 {
Greg Claytone71e2582011-02-04 01:58:07 +0000590 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000591 {
592 m_gdb_comm.SetConnection (conn_ap.release());
593 break;
594 }
595 retry_count++;
596
597 if (retry_count >= max_retry_count)
598 break;
599
600 usleep (100000);
601 }
602 }
603
604 if (!m_gdb_comm.IsConnected())
605 {
606 if (error.Success())
607 error.SetErrorString("not connected to remote gdb server");
608 return error;
609 }
610
Chris Lattner24943d22010-06-08 16:52:24 +0000611 if (m_gdb_comm.StartReadThread(&error))
612 {
613 // Send an initial ack
Greg Claytona4881d02011-01-22 07:12:45 +0000614 m_gdb_comm.SendAck();
Chris Lattner24943d22010-06-08 16:52:24 +0000615
616 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton75ccf502010-08-21 02:22:51 +0000617 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
618 this,
619 m_debugserver_pid,
620 false);
621
Greg Claytonc1f45872011-02-12 06:28:37 +0000622 m_gdb_comm.ResetDiscoverableSettings();
623 m_gdb_comm.GetSendAcks ();
624 m_gdb_comm.GetThreadSuffixSupported ();
625 m_gdb_comm.GetHostInfo ();
626 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000627 }
628 return error;
629}
630
631void
632ProcessGDBRemote::DidLaunchOrAttach ()
633{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000634 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
635 if (log)
636 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000637 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000638 {
639 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
640
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000641 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000642
Greg Clayton395fc332011-02-15 21:59:32 +0000643 m_target.GetArchitecture().SetByteOrder (m_gdb_comm.GetByteOrder());
Greg Clayton20d338f2010-11-18 05:57:03 +0000644
Chris Lattner24943d22010-06-08 16:52:24 +0000645 StreamString strm;
646
Chris Lattner24943d22010-06-08 16:52:24 +0000647 // See if the GDB server supports the qHostInfo information
648 const char *vendor = m_gdb_comm.GetVendorString().AsCString();
649 const char *os_type = m_gdb_comm.GetOSString().AsCString();
Greg Claytonfc7920f2011-02-09 03:09:55 +0000650 ArchSpec target_arch (GetTarget().GetArchitecture());
651 ArchSpec gdb_remote_arch (m_gdb_comm.GetHostArchitecture());
652
Greg Claytonc62176d2011-02-09 03:12:09 +0000653 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytonfc7920f2011-02-09 03:09:55 +0000654 // ARM executables and shared libraries can have mixed ARM architectures.
655 // You can have an armv6 executable, and if the host is armv7, then the
656 // system will load the best possible architecture for all shared libraries
657 // it has, so we really need to take the remote host architecture as our
658 // defacto architecture in this case.
659
Greg Clayton940b1032011-02-23 00:35:02 +0000660 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
661 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytonfc7920f2011-02-09 03:09:55 +0000662 {
663 GetTarget().SetArchitecture (gdb_remote_arch);
664 target_arch = gdb_remote_arch;
665 }
666
Greg Clayton395fc332011-02-15 21:59:32 +0000667 if (vendor)
668 m_target.GetArchitecture().GetTriple().setVendorName(vendor);
669 if (os_type)
670 m_target.GetArchitecture().GetTriple().setOSName(os_type);
Chris Lattner24943d22010-06-08 16:52:24 +0000671 }
672}
673
674void
675ProcessGDBRemote::DidLaunch ()
676{
677 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000678}
679
680Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000681ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000682{
683 Error error;
684 // Clear out and clean up from any current state
685 Clear();
Greg Claytona2f74232011-02-24 22:24:29 +0000686 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000687
Chris Lattner24943d22010-06-08 16:52:24 +0000688 if (attach_pid != LLDB_INVALID_PROCESS_ID)
689 {
Greg Claytona2f74232011-02-24 22:24:29 +0000690 // Make sure we aren't already connected?
691 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000692 {
Greg Claytona2f74232011-02-24 22:24:29 +0000693 char host_port[128];
694 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
695 char connect_url[128];
696 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000697
Greg Claytona2f74232011-02-24 22:24:29 +0000698 error = StartDebugserverProcess (host_port, // debugserver_url
699 NULL, // inferior_argv
700 NULL, // inferior_envp
701 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
702 NULL, // Don't send any attach by process name option to debugserver
703 false, // Don't send any attach wait_for_launch flag as an option to debugserver
704 arch_spec);
705
706 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000707 {
Greg Claytona2f74232011-02-24 22:24:29 +0000708 const char *error_string = error.AsCString();
709 if (error_string == NULL)
710 error_string = "unable to launch " DEBUGSERVER_BASENAME;
711
712 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000713 }
Greg Claytona2f74232011-02-24 22:24:29 +0000714 else
715 {
716 error = ConnectToDebugserver (connect_url);
717 }
718 }
719
720 if (error.Success())
721 {
722 char packet[64];
723 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
724
725 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000726 }
727 }
Chris Lattner24943d22010-06-08 16:52:24 +0000728 return error;
729}
730
731size_t
732ProcessGDBRemote::AttachInputReaderCallback
733(
734 void *baton,
735 InputReader *reader,
736 lldb::InputReaderAction notification,
737 const char *bytes,
738 size_t bytes_len
739)
740{
741 if (notification == eInputReaderGotToken)
742 {
743 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
744 if (gdb_process->m_waiting_for_attach)
745 gdb_process->m_waiting_for_attach = false;
746 reader->SetIsDone(true);
747 return 1;
748 }
749 return 0;
750}
751
752Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000753ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000754{
755 Error error;
756 // Clear out and clean up from any current state
757 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000758
Chris Lattner24943d22010-06-08 16:52:24 +0000759 if (process_name && process_name[0])
760 {
Greg Claytona2f74232011-02-24 22:24:29 +0000761 // Make sure we aren't already connected?
762 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000763 {
Chris Lattner24943d22010-06-08 16:52:24 +0000764
Greg Claytona2f74232011-02-24 22:24:29 +0000765 const ArchSpec &arch_spec = GetTarget().GetArchitecture();
766
767 char host_port[128];
768 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
769 char connect_url[128];
770 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
771
772 error = StartDebugserverProcess (host_port, // debugserver_url
773 NULL, // inferior_argv
774 NULL, // inferior_envp
775 LLDB_INVALID_PROCESS_ID, // Don't send any attach to pid options to debugserver
776 NULL, // Don't send any attach by process name option to debugserver
777 false, // Don't send any attach wait_for_launch flag as an option to debugserver
778 arch_spec);
779 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000780 {
Greg Claytona2f74232011-02-24 22:24:29 +0000781 const char *error_string = error.AsCString();
782 if (error_string == NULL)
783 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000784
Greg Claytona2f74232011-02-24 22:24:29 +0000785 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000786 }
Greg Claytona2f74232011-02-24 22:24:29 +0000787 else
788 {
789 error = ConnectToDebugserver (connect_url);
790 }
791 }
792
793 if (error.Success())
794 {
795 StreamString packet;
796
797 if (wait_for_launch)
798 packet.PutCString("vAttachWait");
799 else
800 packet.PutCString("vAttachName");
801 packet.PutChar(';');
802 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
803
804 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
805
Chris Lattner24943d22010-06-08 16:52:24 +0000806 }
807 }
Chris Lattner24943d22010-06-08 16:52:24 +0000808 return error;
809}
810
Chris Lattner24943d22010-06-08 16:52:24 +0000811
812void
813ProcessGDBRemote::DidAttach ()
814{
Greg Claytone71e2582011-02-04 01:58:07 +0000815 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000816}
817
818Error
819ProcessGDBRemote::WillResume ()
820{
Greg Claytonc1f45872011-02-12 06:28:37 +0000821 m_continue_c_tids.clear();
822 m_continue_C_tids.clear();
823 m_continue_s_tids.clear();
824 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000825 return Error();
826}
827
828Error
829ProcessGDBRemote::DoResume ()
830{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000831 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000832 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
833 if (log)
834 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000835
836 Listener listener ("gdb-remote.resume-packet-sent");
837 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
838 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000839 StreamString continue_packet;
840 bool continue_packet_error = false;
841 if (m_gdb_comm.HasAnyVContSupport ())
842 {
843 continue_packet.PutCString ("vCont");
844
845 if (!m_continue_c_tids.empty())
846 {
847 if (m_gdb_comm.GetVContSupported ('c'))
848 {
849 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)
850 continue_packet.Printf(";c:%4.4x", *t_pos);
851 }
852 else
853 continue_packet_error = true;
854 }
855
856 if (!continue_packet_error && !m_continue_C_tids.empty())
857 {
858 if (m_gdb_comm.GetVContSupported ('C'))
859 {
860 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)
861 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
862 }
863 else
864 continue_packet_error = true;
865 }
Greg Claytonb749a262010-12-03 06:02:24 +0000866
Greg Claytonc1f45872011-02-12 06:28:37 +0000867 if (!continue_packet_error && !m_continue_s_tids.empty())
868 {
869 if (m_gdb_comm.GetVContSupported ('s'))
870 {
871 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)
872 continue_packet.Printf(";s:%4.4x", *t_pos);
873 }
874 else
875 continue_packet_error = true;
876 }
877
878 if (!continue_packet_error && !m_continue_S_tids.empty())
879 {
880 if (m_gdb_comm.GetVContSupported ('S'))
881 {
882 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)
883 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
884 }
885 else
886 continue_packet_error = true;
887 }
888
889 if (continue_packet_error)
890 continue_packet.GetString().clear();
891 }
892 else
893 continue_packet_error = true;
894
895 if (continue_packet_error)
896 {
897 continue_packet_error = false;
898 // Either no vCont support, or we tried to use part of the vCont
899 // packet that wasn't supported by the remote GDB server.
900 // We need to try and make a simple packet that can do our continue
901 const size_t num_threads = GetThreadList().GetSize();
902 const size_t num_continue_c_tids = m_continue_c_tids.size();
903 const size_t num_continue_C_tids = m_continue_C_tids.size();
904 const size_t num_continue_s_tids = m_continue_s_tids.size();
905 const size_t num_continue_S_tids = m_continue_S_tids.size();
906 if (num_continue_c_tids > 0)
907 {
908 if (num_continue_c_tids == num_threads)
909 {
910 // All threads are resuming...
911 SetCurrentGDBRemoteThreadForRun (-1);
912 continue_packet.PutChar ('c');
913 }
914 else if (num_continue_c_tids == 1 &&
915 num_continue_C_tids == 0 &&
916 num_continue_s_tids == 0 &&
917 num_continue_S_tids == 0 )
918 {
919 // Only one thread is continuing
920 SetCurrentGDBRemoteThreadForRun (m_continue_c_tids.front());
921 continue_packet.PutChar ('c');
922 }
923 else
924 {
925 // We can't represent this continue packet....
926 continue_packet_error = true;
927 }
928 }
929
930 if (!continue_packet_error && num_continue_C_tids > 0)
931 {
932 if (num_continue_C_tids == num_threads)
933 {
934 const int continue_signo = m_continue_C_tids.front().second;
935 if (num_continue_C_tids > 1)
936 {
937 for (size_t i=1; i<num_threads; ++i)
938 {
939 if (m_continue_C_tids[i].second != continue_signo)
940 continue_packet_error = true;
941 }
942 }
943 if (!continue_packet_error)
944 {
945 // Add threads continuing with the same signo...
946 SetCurrentGDBRemoteThreadForRun (-1);
947 continue_packet.Printf("C%2.2x", continue_signo);
948 }
949 }
950 else if (num_continue_c_tids == 0 &&
951 num_continue_C_tids == 1 &&
952 num_continue_s_tids == 0 &&
953 num_continue_S_tids == 0 )
954 {
955 // Only one thread is continuing with signal
956 SetCurrentGDBRemoteThreadForRun (m_continue_C_tids.front().first);
957 continue_packet.Printf("C%2.2x", m_continue_C_tids.front().second);
958 }
959 else
960 {
961 // We can't represent this continue packet....
962 continue_packet_error = true;
963 }
964 }
965
966 if (!continue_packet_error && num_continue_s_tids > 0)
967 {
968 if (num_continue_s_tids == num_threads)
969 {
970 // All threads are resuming...
971 SetCurrentGDBRemoteThreadForRun (-1);
972 continue_packet.PutChar ('s');
973 }
974 else if (num_continue_c_tids == 0 &&
975 num_continue_C_tids == 0 &&
976 num_continue_s_tids == 1 &&
977 num_continue_S_tids == 0 )
978 {
979 // Only one thread is stepping
980 SetCurrentGDBRemoteThreadForRun (m_continue_s_tids.front());
981 continue_packet.PutChar ('s');
982 }
983 else
984 {
985 // We can't represent this continue packet....
986 continue_packet_error = true;
987 }
988 }
989
990 if (!continue_packet_error && num_continue_S_tids > 0)
991 {
992 if (num_continue_S_tids == num_threads)
993 {
994 const int step_signo = m_continue_S_tids.front().second;
995 // Are all threads trying to step with the same signal?
996 if (num_continue_S_tids > 1)
997 {
998 for (size_t i=1; i<num_threads; ++i)
999 {
1000 if (m_continue_S_tids[i].second != step_signo)
1001 continue_packet_error = true;
1002 }
1003 }
1004 if (!continue_packet_error)
1005 {
1006 // Add threads stepping with the same signo...
1007 SetCurrentGDBRemoteThreadForRun (-1);
1008 continue_packet.Printf("S%2.2x", step_signo);
1009 }
1010 }
1011 else if (num_continue_c_tids == 0 &&
1012 num_continue_C_tids == 0 &&
1013 num_continue_s_tids == 0 &&
1014 num_continue_S_tids == 1 )
1015 {
1016 // Only one thread is stepping with signal
1017 SetCurrentGDBRemoteThreadForRun (m_continue_S_tids.front().first);
1018 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1019 }
1020 else
1021 {
1022 // We can't represent this continue packet....
1023 continue_packet_error = true;
1024 }
1025 }
1026 }
1027
1028 if (continue_packet_error)
1029 {
1030 error.SetErrorString ("can't make continue packet for this resume");
1031 }
1032 else
1033 {
1034 EventSP event_sp;
1035 TimeValue timeout;
1036 timeout = TimeValue::Now();
1037 timeout.OffsetWithSeconds (5);
1038 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1039
1040 if (listener.WaitForEvent (&timeout, event_sp) == false)
1041 error.SetErrorString("Resume timed out.");
1042 }
Greg Claytonb749a262010-12-03 06:02:24 +00001043 }
1044
Jim Ingham3ae449a2010-11-17 02:32:00 +00001045 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001046}
1047
1048size_t
1049ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1050{
1051 const uint8_t *trap_opcode = NULL;
1052 uint32_t trap_opcode_size = 0;
1053
1054 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 };
1055 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE };
1056 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 };
1057 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
1058
Greg Clayton940b1032011-02-23 00:35:02 +00001059 const llvm::Triple::ArchType machine = GetTarget().GetArchitecture().GetMachine();
1060 switch (machine)
Chris Lattner24943d22010-06-08 16:52:24 +00001061 {
Greg Clayton940b1032011-02-23 00:35:02 +00001062 case llvm::Triple::x86:
1063 case llvm::Triple::x86_64:
Greg Claytoncf015052010-06-11 03:25:34 +00001064 trap_opcode = g_i386_breakpoint_opcode;
1065 trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
1066 break;
1067
Greg Clayton940b1032011-02-23 00:35:02 +00001068 case llvm::Triple::arm:
Greg Claytoncf015052010-06-11 03:25:34 +00001069 // TODO: fill this in for ARM. We need to dig up the symbol for
1070 // the address in the breakpoint locaiton and figure out if it is
1071 // an ARM or Thumb breakpoint.
1072 trap_opcode = g_arm_breakpoint_opcode;
1073 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1074 break;
1075
Greg Clayton940b1032011-02-23 00:35:02 +00001076 case llvm::Triple::ppc:
1077 case llvm::Triple::ppc64:
Greg Claytoncf015052010-06-11 03:25:34 +00001078 trap_opcode = g_ppc_breakpoint_opcode;
1079 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
1080 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001081
Greg Claytoncf015052010-06-11 03:25:34 +00001082 default:
1083 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()");
1084 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001085 }
1086
1087 if (trap_opcode && trap_opcode_size)
1088 {
1089 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1090 return trap_opcode_size;
1091 }
1092 return 0;
1093}
1094
1095uint32_t
1096ProcessGDBRemote::UpdateThreadListIfNeeded ()
1097{
1098 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001099 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001100 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001101 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
1102
Greg Clayton5205f0b2010-09-03 17:10:42 +00001103 Mutex::Locker locker (m_thread_list.GetMutex ());
Chris Lattner24943d22010-06-08 16:52:24 +00001104 const uint32_t stop_id = GetStopID();
1105 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1106 {
1107 // Update the thread list's stop id immediately so we don't recurse into this function.
1108 ThreadList curr_thread_list (this);
1109 curr_thread_list.SetStopID(stop_id);
1110
1111 Error err;
1112 StringExtractorGDBRemote response;
1113 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false);
1114 response.IsNormalPacket();
1115 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false))
1116 {
1117 char ch = response.GetChar();
1118 if (ch == 'l')
1119 break;
1120 if (ch == 'm')
1121 {
1122 do
1123 {
1124 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1125
1126 if (tid != LLDB_INVALID_THREAD_ID)
1127 {
1128 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
Greg Claytona875b642011-01-09 21:07:35 +00001129 if (!thread_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001130 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1131 curr_thread_list.AddThread(thread_sp);
1132 }
1133
1134 ch = response.GetChar();
1135 } while (ch == ',');
1136 }
1137 }
1138
1139 m_thread_list = curr_thread_list;
1140
1141 SetThreadStopInfo (m_last_stop_packet);
1142 }
1143 return GetThreadList().GetSize(false);
1144}
1145
1146
1147StateType
1148ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1149{
1150 const char stop_type = stop_packet.GetChar();
1151 switch (stop_type)
1152 {
1153 case 'T':
1154 case 'S':
1155 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001156 if (GetStopID() == 0)
1157 {
1158 // Our first stop, make sure we have a process ID, and also make
1159 // sure we know about our registers
1160 if (GetID() == LLDB_INVALID_PROCESS_ID)
1161 {
1162 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (1);
1163 if (pid != LLDB_INVALID_PROCESS_ID)
1164 SetID (pid);
1165 }
1166 BuildDynamicRegisterInfo (true);
1167 }
Chris Lattner24943d22010-06-08 16:52:24 +00001168 // Stop with signal and thread info
1169 const uint8_t signo = stop_packet.GetHexU8();
1170 std::string name;
1171 std::string value;
1172 std::string thread_name;
1173 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001174 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001175 uint32_t tid = LLDB_INVALID_THREAD_ID;
1176 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1177 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001178 ThreadSP thread_sp;
1179
Chris Lattner24943d22010-06-08 16:52:24 +00001180 while (stop_packet.GetNameColonValue(name, value))
1181 {
1182 if (name.compare("metype") == 0)
1183 {
1184 // exception type in big endian hex
1185 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1186 }
1187 else if (name.compare("mecount") == 0)
1188 {
1189 // exception count in big endian hex
1190 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1191 }
1192 else if (name.compare("medata") == 0)
1193 {
1194 // exception data in big endian hex
1195 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1196 }
1197 else if (name.compare("thread") == 0)
1198 {
1199 // thread in big endian hex
1200 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001201 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001202 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001203 if (!thread_sp)
1204 {
1205 // Create the thread if we need to
1206 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1207 m_thread_list.AddThread(thread_sp);
1208 }
Chris Lattner24943d22010-06-08 16:52:24 +00001209 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001210 else if (name.compare("hexname") == 0)
1211 {
1212 StringExtractor name_extractor;
1213 // Swap "value" over into "name_extractor"
1214 name_extractor.GetStringRef().swap(value);
1215 // Now convert the HEX bytes into a string value
1216 name_extractor.GetHexByteString (value);
1217 thread_name.swap (value);
1218 }
Chris Lattner24943d22010-06-08 16:52:24 +00001219 else if (name.compare("name") == 0)
1220 {
1221 thread_name.swap (value);
1222 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001223 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001224 {
1225 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1226 }
Greg Claytona875b642011-01-09 21:07:35 +00001227 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1228 {
1229 // We have a register number that contains an expedited
1230 // register value. Lets supply this register to our thread
1231 // so it won't have to go and read it.
1232 if (thread_sp)
1233 {
1234 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1235
1236 if (reg != UINT32_MAX)
1237 {
1238 StringExtractor reg_value_extractor;
1239 // Swap "value" over into "reg_value_extractor"
1240 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001241 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1242 {
1243 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1244 name.c_str(),
1245 reg,
1246 reg,
1247 reg_value_extractor.GetStringRef().c_str(),
1248 stop_packet.GetStringRef().c_str());
1249 }
Greg Claytona875b642011-01-09 21:07:35 +00001250 }
1251 }
1252 }
Chris Lattner24943d22010-06-08 16:52:24 +00001253 }
Chris Lattner24943d22010-06-08 16:52:24 +00001254
1255 if (thread_sp)
1256 {
1257 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1258
1259 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001260 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001261 if (exc_type != 0)
1262 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001263 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001264
1265 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1266 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001267 exc_data_size,
1268 exc_data_size >= 1 ? exc_data[0] : 0,
1269 exc_data_size >= 2 ? exc_data[1] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001270 }
1271 else if (signo)
1272 {
Greg Clayton643ee732010-08-04 01:40:35 +00001273 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001274 }
1275 else
1276 {
Greg Clayton643ee732010-08-04 01:40:35 +00001277 StopInfoSP invalid_stop_info_sp;
1278 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001279 }
1280 }
1281 return eStateStopped;
1282 }
1283 break;
1284
1285 case 'W':
1286 // process exited
1287 return eStateExited;
1288
1289 default:
1290 break;
1291 }
1292 return eStateInvalid;
1293}
1294
1295void
1296ProcessGDBRemote::RefreshStateAfterStop ()
1297{
Jim Ingham7508e732010-08-09 23:31:02 +00001298 // FIXME - add a variable to tell that we're in the middle of attaching if we
1299 // need to know that.
Chris Lattner24943d22010-06-08 16:52:24 +00001300 // We must be attaching if we don't already have a valid architecture
Jim Ingham7508e732010-08-09 23:31:02 +00001301// if (!GetTarget().GetArchitecture().IsValid())
1302// {
1303// Module *exe_module = GetTarget().GetExecutableModule().get();
1304// if (exe_module)
1305// m_arch_spec = exe_module->GetArchitecture();
1306// }
1307
Chris Lattner24943d22010-06-08 16:52:24 +00001308 // Let all threads recover from stopping and do any clean up based
1309 // on the previous thread state (if any).
1310 m_thread_list.RefreshStateAfterStop();
1311
1312 // Discover new threads:
1313 UpdateThreadListIfNeeded ();
1314}
1315
1316Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001317ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001318{
1319 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001320
Greg Claytona4881d02011-01-22 07:12:45 +00001321 bool timed_out = false;
1322 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001323
1324 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001325 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001326 // We are being asked to halt during an attach. We need to just close
1327 // our file handle and debugserver will go away, and we can be done...
1328 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001329 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001330 else
1331 {
1332 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1333 {
1334 if (timed_out)
1335 error.SetErrorString("timed out sending interrupt packet");
1336 else
1337 error.SetErrorString("unknown error sending interrupt packet");
1338 }
1339 }
Chris Lattner24943d22010-06-08 16:52:24 +00001340 return error;
1341}
1342
1343Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001344ProcessGDBRemote::InterruptIfRunning
1345(
1346 bool discard_thread_plans,
1347 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001348 EventSP &stop_event_sp
1349)
Chris Lattner24943d22010-06-08 16:52:24 +00001350{
1351 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001352
Greg Clayton2860ba92011-01-23 19:58:49 +00001353 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1354
Greg Clayton68ca8232011-01-25 02:58:48 +00001355 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001356 const bool is_running = m_gdb_comm.IsRunning();
1357 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001358 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001359 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001360 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001361 is_running);
1362
Greg Clayton2860ba92011-01-23 19:58:49 +00001363 if (discard_thread_plans)
1364 {
1365 if (log)
1366 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1367 m_thread_list.DiscardThreadPlans();
1368 }
1369 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001370 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001371 if (catch_stop_event)
1372 {
1373 if (log)
1374 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1375 PausePrivateStateThread();
1376 paused_private_state_thread = true;
1377 }
1378
Greg Clayton4fb400f2010-09-27 21:07:38 +00001379 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001380 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001381 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001382
Greg Clayton72e1c782011-01-22 23:43:18 +00001383 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001384 {
1385 if (timed_out)
1386 error.SetErrorString("timed out sending interrupt packet");
1387 else
1388 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001389 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001390 ResumePrivateStateThread();
1391 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001392 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001393
Greg Clayton72e1c782011-01-22 23:43:18 +00001394 if (catch_stop_event)
1395 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001396 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001397 TimeValue timeout_time;
1398 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001399 timeout_time.OffsetWithSeconds(5);
1400 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001401
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001402 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001403 if (log)
1404 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001405
Greg Clayton2860ba92011-01-23 19:58:49 +00001406 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001407 error.SetErrorString("unable to verify target stopped");
1408 }
1409
Greg Clayton68ca8232011-01-25 02:58:48 +00001410 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001411 {
1412 if (log)
1413 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001414 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001415 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001416 }
Chris Lattner24943d22010-06-08 16:52:24 +00001417 return error;
1418}
1419
Greg Clayton4fb400f2010-09-27 21:07:38 +00001420Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001421ProcessGDBRemote::WillDetach ()
1422{
Greg Clayton2860ba92011-01-23 19:58:49 +00001423 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1424 if (log)
1425 log->Printf ("ProcessGDBRemote::WillDetach()");
1426
Greg Clayton72e1c782011-01-22 23:43:18 +00001427 bool discard_thread_plans = true;
1428 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001429 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001430 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001431}
1432
1433Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001434ProcessGDBRemote::DoDetach()
1435{
1436 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001437 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001438 if (log)
1439 log->Printf ("ProcessGDBRemote::DoDetach()");
1440
1441 DisableAllBreakpointSites ();
1442
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001443 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001444
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001445 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1446 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001447 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001448 if (response_size)
1449 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1450 else
1451 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001452 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001453 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001454 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001455
Greg Clayton4fb400f2010-09-27 21:07:38 +00001456 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001457 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001458
1459 SetPrivateState (eStateDetached);
1460 ResumePrivateStateThread();
1461
1462 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001463 return error;
1464}
Chris Lattner24943d22010-06-08 16:52:24 +00001465
1466Error
1467ProcessGDBRemote::DoDestroy ()
1468{
1469 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001470 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001471 if (log)
1472 log->Printf ("ProcessGDBRemote::DoDestroy()");
1473
1474 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001475 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001476 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001477 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001478 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001479 // We are being asked to halt during an attach. We need to just close
1480 // our file handle and debugserver will go away, and we can be done...
1481 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001482 }
1483 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001484 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001485
1486 StringExtractorGDBRemote response;
1487 bool send_async = true;
1488 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, 2, send_async))
1489 {
1490 char packet_cmd = response.GetChar(0);
1491
1492 if (packet_cmd == 'W' || packet_cmd == 'X')
1493 {
1494 m_last_stop_packet = response;
1495 SetExitStatus(response.GetHexU8(), NULL);
1496 }
1497 }
1498 else
1499 {
1500 SetExitStatus(SIGABRT, NULL);
1501 //error.SetErrorString("kill packet failed");
1502 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001503 }
1504 }
Chris Lattner24943d22010-06-08 16:52:24 +00001505 StopAsyncThread ();
1506 m_gdb_comm.StopReadThread();
1507 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001508 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001509 return error;
1510}
1511
Chris Lattner24943d22010-06-08 16:52:24 +00001512//------------------------------------------------------------------
1513// Process Queries
1514//------------------------------------------------------------------
1515
1516bool
1517ProcessGDBRemote::IsAlive ()
1518{
Greg Clayton58e844b2010-12-08 05:08:21 +00001519 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001520}
1521
1522addr_t
1523ProcessGDBRemote::GetImageInfoAddress()
1524{
1525 if (!m_gdb_comm.IsRunning())
1526 {
1527 StringExtractorGDBRemote response;
1528 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false))
1529 {
1530 if (response.IsNormalPacket())
1531 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1532 }
1533 }
1534 return LLDB_INVALID_ADDRESS;
1535}
1536
Chris Lattner24943d22010-06-08 16:52:24 +00001537//------------------------------------------------------------------
1538// Process Memory
1539//------------------------------------------------------------------
1540size_t
1541ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1542{
1543 if (size > m_max_memory_size)
1544 {
1545 // Keep memory read sizes down to a sane limit. This function will be
1546 // called multiple times in order to complete the task by
1547 // lldb_private::Process so it is ok to do this.
1548 size = m_max_memory_size;
1549 }
1550
1551 char packet[64];
1552 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1553 assert (packet_len + 1 < sizeof(packet));
1554 StringExtractorGDBRemote response;
1555 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1556 {
1557 if (response.IsNormalPacket())
1558 {
1559 error.Clear();
1560 return response.GetHexBytes(buf, size, '\xdd');
1561 }
1562 else if (response.IsErrorPacket())
1563 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1564 else if (response.IsUnsupportedPacket())
1565 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1566 else
1567 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1568 }
1569 else
1570 {
1571 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1572 }
1573 return 0;
1574}
1575
1576size_t
1577ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1578{
1579 StreamString packet;
1580 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001581 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001582 StringExtractorGDBRemote response;
1583 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true))
1584 {
1585 if (response.IsOKPacket())
1586 {
1587 error.Clear();
1588 return size;
1589 }
1590 else if (response.IsErrorPacket())
1591 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
1592 else if (response.IsUnsupportedPacket())
1593 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1594 else
1595 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1596 }
1597 else
1598 {
1599 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1600 }
1601 return 0;
1602}
1603
1604lldb::addr_t
1605ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1606{
1607 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout);
1608 if (allocated_addr == LLDB_INVALID_ADDRESS)
1609 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions);
1610 else
1611 error.Clear();
1612 return allocated_addr;
1613}
1614
1615Error
1616ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1617{
1618 Error error;
1619 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout))
1620 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1621 return error;
1622}
1623
1624
1625//------------------------------------------------------------------
1626// Process STDIO
1627//------------------------------------------------------------------
1628
1629size_t
1630ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1631{
1632 Mutex::Locker locker(m_stdio_mutex);
1633 size_t bytes_available = m_stdout_data.size();
1634 if (bytes_available > 0)
1635 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001636 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1637 if (log)
1638 log->Printf ("ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001639 if (bytes_available > buf_size)
1640 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001641 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001642 m_stdout_data.erase(0, buf_size);
1643 bytes_available = buf_size;
1644 }
1645 else
1646 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001647 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001648 m_stdout_data.clear();
1649
1650 //ResetEventBits(eBroadcastBitSTDOUT);
1651 }
1652 }
1653 return bytes_available;
1654}
1655
1656size_t
1657ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1658{
1659 // Can we get STDERR through the remote protocol?
1660 return 0;
1661}
1662
1663size_t
1664ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1665{
1666 if (m_stdio_communication.IsConnected())
1667 {
1668 ConnectionStatus status;
1669 m_stdio_communication.Write(src, src_len, status, NULL);
1670 }
1671 return 0;
1672}
1673
1674Error
1675ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1676{
1677 Error error;
1678 assert (bp_site != NULL);
1679
Greg Claytone005f2c2010-11-06 01:53:30 +00001680 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001681 user_id_t site_id = bp_site->GetID();
1682 const addr_t addr = bp_site->GetLoadAddress();
1683 if (log)
1684 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1685
1686 if (bp_site->IsEnabled())
1687 {
1688 if (log)
1689 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1690 return error;
1691 }
1692 else
1693 {
1694 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1695
1696 if (bp_site->HardwarePreferred())
1697 {
1698 // Try and set hardware breakpoint, and if that fails, fall through
1699 // and set a software breakpoint?
1700 }
1701
1702 if (m_z0_supported)
1703 {
1704 char packet[64];
1705 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size);
1706 assert (packet_len + 1 < sizeof(packet));
1707 StringExtractorGDBRemote response;
1708 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1709 {
1710 if (response.IsUnsupportedPacket())
1711 {
1712 // Disable z packet support and try again
1713 m_z0_supported = 0;
1714 return EnableBreakpoint (bp_site);
1715 }
1716 else if (response.IsOKPacket())
1717 {
1718 bp_site->SetEnabled(true);
1719 bp_site->SetType (BreakpointSite::eExternal);
1720 return error;
1721 }
1722 else
1723 {
1724 uint8_t error_byte = response.GetError();
1725 if (error_byte)
1726 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1727 }
1728 }
1729 }
1730 else
1731 {
1732 return EnableSoftwareBreakpoint (bp_site);
1733 }
1734 }
1735
1736 if (log)
1737 {
1738 const char *err_string = error.AsCString();
1739 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1740 bp_site->GetLoadAddress(),
1741 err_string ? err_string : "NULL");
1742 }
1743 // We shouldn't reach here on a successful breakpoint enable...
1744 if (error.Success())
1745 error.SetErrorToGenericError();
1746 return error;
1747}
1748
1749Error
1750ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1751{
1752 Error error;
1753 assert (bp_site != NULL);
1754 addr_t addr = bp_site->GetLoadAddress();
1755 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001756 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001757 if (log)
1758 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1759
1760 if (bp_site->IsEnabled())
1761 {
1762 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1763
1764 if (bp_site->IsHardware())
1765 {
1766 // TODO: disable hardware breakpoint...
1767 }
1768 else
1769 {
1770 if (m_z0_supported)
1771 {
1772 char packet[64];
1773 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size);
1774 assert (packet_len + 1 < sizeof(packet));
1775 StringExtractorGDBRemote response;
1776 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true))
1777 {
1778 if (response.IsUnsupportedPacket())
1779 {
1780 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported.");
1781 }
1782 else if (response.IsOKPacket())
1783 {
1784 if (log)
1785 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr);
1786 bp_site->SetEnabled(false);
1787 return error;
1788 }
1789 else
1790 {
1791 uint8_t error_byte = response.GetError();
1792 if (error_byte)
1793 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte);
1794 }
1795 }
1796 }
1797 else
1798 {
1799 return DisableSoftwareBreakpoint (bp_site);
1800 }
1801 }
1802 }
1803 else
1804 {
1805 if (log)
1806 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1807 return error;
1808 }
1809
1810 if (error.Success())
1811 error.SetErrorToGenericError();
1812 return error;
1813}
1814
1815Error
1816ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1817{
1818 Error error;
1819 if (wp)
1820 {
1821 user_id_t watchID = wp->GetID();
1822 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001823 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001824 if (log)
1825 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1826 if (wp->IsEnabled())
1827 {
1828 if (log)
1829 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1830 return error;
1831 }
1832 else
1833 {
1834 // Pass down an appropriate z/Z packet...
1835 error.SetErrorString("watchpoints not supported");
1836 }
1837 }
1838 else
1839 {
1840 error.SetErrorString("Watchpoint location argument was NULL.");
1841 }
1842 if (error.Success())
1843 error.SetErrorToGenericError();
1844 return error;
1845}
1846
1847Error
1848ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1849{
1850 Error error;
1851 if (wp)
1852 {
1853 user_id_t watchID = wp->GetID();
1854
Greg Claytone005f2c2010-11-06 01:53:30 +00001855 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001856
1857 addr_t addr = wp->GetLoadAddress();
1858 if (log)
1859 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1860
1861 if (wp->IsHardware())
1862 {
1863 // Pass down an appropriate z/Z packet...
1864 error.SetErrorString("watchpoints not supported");
1865 }
1866 // TODO: clear software watchpoints if we implement them
1867 }
1868 else
1869 {
1870 error.SetErrorString("Watchpoint location argument was NULL.");
1871 }
1872 if (error.Success())
1873 error.SetErrorToGenericError();
1874 return error;
1875}
1876
1877void
1878ProcessGDBRemote::Clear()
1879{
1880 m_flags = 0;
1881 m_thread_list.Clear();
1882 {
1883 Mutex::Locker locker(m_stdio_mutex);
1884 m_stdout_data.clear();
1885 }
Chris Lattner24943d22010-06-08 16:52:24 +00001886}
1887
1888Error
1889ProcessGDBRemote::DoSignal (int signo)
1890{
1891 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001892 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001893 if (log)
1894 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1895
1896 if (!m_gdb_comm.SendAsyncSignal (signo))
1897 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1898 return error;
1899}
1900
Chris Lattner24943d22010-06-08 16:52:24 +00001901Error
1902ProcessGDBRemote::StartDebugserverProcess
1903(
1904 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
1905 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument
1906 char const *inferior_envp[], // Environment to pass along to the inferior program
Greg Clayton23cf0c72010-11-08 04:29:11 +00001907 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 +00001908 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name"
1909 bool wait_for_launch, // Wait for the process named "attach_name" to launch
Greg Claytona2f74232011-02-24 22:24:29 +00001910 const ArchSpec& inferior_arch // The arch of the inferior that we will launch
Chris Lattner24943d22010-06-08 16:52:24 +00001911)
1912{
1913 Error error;
1914 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
1915 {
1916 // If we locate debugserver, keep that located version around
1917 static FileSpec g_debugserver_file_spec;
1918
1919 FileSpec debugserver_file_spec;
1920 char debugserver_path[PATH_MAX];
1921
1922 // Always check to see if we have an environment override for the path
1923 // to the debugserver to use and use it if we do.
1924 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1925 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00001926 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001927 else
1928 debugserver_file_spec = g_debugserver_file_spec;
1929 bool debugserver_exists = debugserver_file_spec.Exists();
1930 if (!debugserver_exists)
1931 {
1932 // The debugserver binary is in the LLDB.framework/Resources
1933 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00001934 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00001935 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001936 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00001937 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00001938 if (debugserver_exists)
1939 {
1940 g_debugserver_file_spec = debugserver_file_spec;
1941 }
1942 else
1943 {
1944 g_debugserver_file_spec.Clear();
1945 debugserver_file_spec.Clear();
1946 }
Chris Lattner24943d22010-06-08 16:52:24 +00001947 }
1948 }
1949
1950 if (debugserver_exists)
1951 {
1952 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1953
1954 m_stdio_communication.Clear();
1955 posix_spawnattr_t attr;
1956
Greg Claytone005f2c2010-11-06 01:53:30 +00001957 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001958
1959 Error local_err; // Errors that don't affect the spawning.
1960 if (log)
Greg Clayton940b1032011-02-23 00:35:02 +00001961 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )",
1962 __FUNCTION__,
1963 debugserver_path,
1964 inferior_argv,
1965 inferior_envp,
1966 inferior_arch.GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +00001967 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1968 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00001969 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )");
Chris Lattner24943d22010-06-08 16:52:24 +00001970 if (error.Fail())
Greg Clayton940b1032011-02-23 00:35:02 +00001971 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001972
Chris Lattner24943d22010-06-08 16:52:24 +00001973 Args debugserver_args;
1974 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00001975
Chris Lattner24943d22010-06-08 16:52:24 +00001976 // Start args with "debugserver /file/path -r --"
1977 debugserver_args.AppendArgument(debugserver_path);
1978 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00001979 // use native registers, not the GDB registers
1980 debugserver_args.AppendArgument("--native-regs");
1981 // make debugserver run in its own session so signals generated by
1982 // special terminal key sequences (^C) don't affect debugserver
1983 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00001984
Chris Lattner24943d22010-06-08 16:52:24 +00001985 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1986 if (env_debugserver_log_file)
1987 {
1988 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1989 debugserver_args.AppendArgument(arg_cstr);
1990 }
1991
1992 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1993 if (env_debugserver_log_flags)
1994 {
1995 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1996 debugserver_args.AppendArgument(arg_cstr);
1997 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00001998// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001999// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002000
2001 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002002 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002003 {
Greg Claytona2f74232011-02-24 22:24:29 +00002004 // Terminate the debugserver args so we can now append the inferior args
2005 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002006
Greg Claytona2f74232011-02-24 22:24:29 +00002007 for (int i = 0; inferior_argv[i] != NULL; ++i)
2008 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002009 }
2010 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2011 {
2012 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2013 debugserver_args.AppendArgument (arg_cstr);
2014 }
2015 else if (attach_name && attach_name[0])
2016 {
2017 if (wait_for_launch)
2018 debugserver_args.AppendArgument ("--waitfor");
2019 else
2020 debugserver_args.AppendArgument ("--attach");
2021 debugserver_args.AppendArgument (attach_name);
2022 }
2023
2024 Error file_actions_err;
2025 posix_spawn_file_actions_t file_actions;
2026#if DONT_CLOSE_DEBUGSERVER_STDIO
2027 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below.");
2028#else
2029 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
2030 if (file_actions_err.Success())
2031 {
2032 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO);
2033 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO);
2034 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO);
2035 }
2036#endif
2037
2038 if (log)
2039 {
2040 StreamString strm;
2041 debugserver_args.Dump (&strm);
2042 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2043 }
2044
Greg Clayton72e1c782011-01-22 23:43:18 +00002045 error.SetError (::posix_spawnp (&m_debugserver_pid,
2046 debugserver_path,
2047 file_actions_err.Success() ? &file_actions : NULL,
2048 &attr,
2049 debugserver_args.GetArgumentVector(),
2050 (char * const*)inferior_envp),
2051 eErrorTypePOSIX);
2052
Greg Claytone9d0df42010-07-02 01:29:13 +00002053
2054 ::posix_spawnattr_destroy (&attr);
2055
Chris Lattner24943d22010-06-08 16:52:24 +00002056 if (file_actions_err.Success())
2057 ::posix_spawn_file_actions_destroy (&file_actions);
2058
2059 // We have seen some cases where posix_spawnp was returning a valid
2060 // looking pid even when an error was returned, so clear it out
2061 if (error.Fail())
2062 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2063
2064 if (error.Fail() || log)
Greg Claytone005f2c2010-11-06 01:53:30 +00002065 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 +00002066
Chris Lattner24943d22010-06-08 16:52:24 +00002067 }
2068 else
2069 {
2070 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2071 }
2072
2073 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2074 StartAsyncThread ();
2075 }
2076 return error;
2077}
2078
2079bool
2080ProcessGDBRemote::MonitorDebugserverProcess
2081(
2082 void *callback_baton,
2083 lldb::pid_t debugserver_pid,
2084 int signo, // Zero for no signal
2085 int exit_status // Exit value of process if signal is zero
2086)
2087{
2088 // We pass in the ProcessGDBRemote inferior process it and name it
2089 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2090 // pointer value itself, thus we need the double cast...
2091
2092 // "debugserver_pid" argument passed in is the process ID for
2093 // debugserver that we are tracking...
2094
Greg Clayton75ccf502010-08-21 02:22:51 +00002095 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002096
2097 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2098 if (log)
2099 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2100
Greg Clayton75ccf502010-08-21 02:22:51 +00002101 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002102 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002103 // Sleep for a half a second to make sure our inferior process has
2104 // time to set its exit status before we set it incorrectly when
2105 // both the debugserver and the inferior process shut down.
2106 usleep (500000);
2107 // If our process hasn't yet exited, debugserver might have died.
2108 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002109 const StateType state = process->GetState();
2110
2111 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2112 state != eStateInvalid &&
2113 state != eStateUnloaded &&
2114 state != eStateExited &&
2115 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002116 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002117 char error_str[1024];
2118 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002119 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002120 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2121 if (signal_cstr)
2122 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002123 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002124 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002125 }
2126 else
2127 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002128 ::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 +00002129 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002130
2131 process->SetExitStatus (-1, error_str);
2132 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002133 // Debugserver has exited we need to let our ProcessGDBRemote
2134 // know that it no longer has a debugserver instance
2135 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2136 // We are returning true to this function below, so we can
2137 // forget about the monitor handle.
2138 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002139 }
2140 return true;
2141}
2142
2143void
2144ProcessGDBRemote::KillDebugserverProcess ()
2145{
2146 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2147 {
2148 ::kill (m_debugserver_pid, SIGINT);
2149 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2150 }
2151}
2152
2153void
2154ProcessGDBRemote::Initialize()
2155{
2156 static bool g_initialized = false;
2157
2158 if (g_initialized == false)
2159 {
2160 g_initialized = true;
2161 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2162 GetPluginDescriptionStatic(),
2163 CreateInstance);
2164
2165 Log::Callbacks log_callbacks = {
2166 ProcessGDBRemoteLog::DisableLog,
2167 ProcessGDBRemoteLog::EnableLog,
2168 ProcessGDBRemoteLog::ListLogCategories
2169 };
2170
2171 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2172 }
2173}
2174
2175bool
2176ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid)
2177{
2178 if (m_curr_tid == tid)
2179 return true;
2180
2181 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002182 int packet_len;
2183 if (tid <= 0)
2184 packet_len = ::snprintf (packet, sizeof(packet), "Hg%i", tid);
2185 else
2186 packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid);
Chris Lattner24943d22010-06-08 16:52:24 +00002187 assert (packet_len + 1 < sizeof(packet));
2188 StringExtractorGDBRemote response;
2189 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2190 {
2191 if (response.IsOKPacket())
2192 {
2193 m_curr_tid = tid;
2194 return true;
2195 }
2196 }
2197 return false;
2198}
2199
2200bool
2201ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid)
2202{
2203 if (m_curr_tid_run == tid)
2204 return true;
2205
2206 char packet[32];
Greg Claytonc1f45872011-02-12 06:28:37 +00002207 int packet_len;
2208 if (tid <= 0)
2209 packet_len = ::snprintf (packet, sizeof(packet), "Hc%i", tid);
2210 else
2211 packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid);
2212
Chris Lattner24943d22010-06-08 16:52:24 +00002213 assert (packet_len + 1 < sizeof(packet));
2214 StringExtractorGDBRemote response;
2215 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false))
2216 {
2217 if (response.IsOKPacket())
2218 {
2219 m_curr_tid_run = tid;
2220 return true;
2221 }
2222 }
2223 return false;
2224}
2225
2226void
2227ProcessGDBRemote::ResetGDBRemoteState ()
2228{
2229 // Reset and GDB remote state
2230 m_curr_tid = LLDB_INVALID_THREAD_ID;
2231 m_curr_tid_run = LLDB_INVALID_THREAD_ID;
2232 m_z0_supported = 1;
2233}
2234
2235
2236bool
2237ProcessGDBRemote::StartAsyncThread ()
2238{
2239 ResetGDBRemoteState ();
2240
Greg Claytone005f2c2010-11-06 01:53:30 +00002241 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002242
2243 if (log)
2244 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2245
2246 // Create a thread that watches our internal state and controls which
2247 // events make it to clients (into the DCProcess event queue).
2248 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002249 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002250}
2251
2252void
2253ProcessGDBRemote::StopAsyncThread ()
2254{
Greg Claytone005f2c2010-11-06 01:53:30 +00002255 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002256
2257 if (log)
2258 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2259
2260 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2261
2262 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002263 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002264 {
2265 Host::ThreadJoin (m_async_thread, NULL, NULL);
2266 }
2267}
2268
2269
2270void *
2271ProcessGDBRemote::AsyncThread (void *arg)
2272{
2273 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2274
Greg Claytone005f2c2010-11-06 01:53:30 +00002275 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002276 if (log)
2277 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2278
2279 Listener listener ("ProcessGDBRemote::AsyncThread");
2280 EventSP event_sp;
2281 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2282 eBroadcastBitAsyncThreadShouldExit;
2283
2284 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2285 {
Greg Claytona2f74232011-02-24 22:24:29 +00002286 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2287
Chris Lattner24943d22010-06-08 16:52:24 +00002288 bool done = false;
2289 while (!done)
2290 {
2291 if (log)
2292 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2293 if (listener.WaitForEvent (NULL, event_sp))
2294 {
2295 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002296 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002297 {
Greg Claytona2f74232011-02-24 22:24:29 +00002298 if (log)
2299 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002300
Greg Claytona2f74232011-02-24 22:24:29 +00002301 switch (event_type)
2302 {
2303 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002304 {
Greg Claytona2f74232011-02-24 22:24:29 +00002305 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002306
Greg Claytona2f74232011-02-24 22:24:29 +00002307 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002308 {
Greg Claytona2f74232011-02-24 22:24:29 +00002309 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2310 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2311 if (log)
2312 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002313
Greg Claytona2f74232011-02-24 22:24:29 +00002314 if (::strstr (continue_cstr, "vAttach") == NULL)
2315 process->SetPrivateState(eStateRunning);
2316 StringExtractorGDBRemote response;
2317 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002318
Greg Claytona2f74232011-02-24 22:24:29 +00002319 switch (stop_state)
2320 {
2321 case eStateStopped:
2322 case eStateCrashed:
2323 case eStateSuspended:
2324 process->m_last_stop_packet = response;
2325 process->m_last_stop_packet.SetFilePos (0);
2326 process->SetPrivateState (stop_state);
2327 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002328
Greg Claytona2f74232011-02-24 22:24:29 +00002329 case eStateExited:
2330 process->m_last_stop_packet = response;
2331 process->m_last_stop_packet.SetFilePos (0);
2332 response.SetFilePos(1);
2333 process->SetExitStatus(response.GetHexU8(), NULL);
2334 done = true;
2335 break;
2336
2337 case eStateInvalid:
2338 process->SetExitStatus(-1, "lost connection");
2339 break;
2340
2341 default:
2342 process->SetPrivateState (stop_state);
2343 break;
2344 }
Chris Lattner24943d22010-06-08 16:52:24 +00002345 }
2346 }
Greg Claytona2f74232011-02-24 22:24:29 +00002347 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002348
Greg Claytona2f74232011-02-24 22:24:29 +00002349 case eBroadcastBitAsyncThreadShouldExit:
2350 if (log)
2351 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2352 done = true;
2353 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002354
Greg Claytona2f74232011-02-24 22:24:29 +00002355 default:
2356 if (log)
2357 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2358 done = true;
2359 break;
2360 }
2361 }
2362 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2363 {
2364 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2365 {
2366 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002367 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002368 }
Chris Lattner24943d22010-06-08 16:52:24 +00002369 }
2370 }
2371 else
2372 {
2373 if (log)
2374 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2375 done = true;
2376 }
2377 }
2378 }
2379
2380 if (log)
2381 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2382
2383 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2384 return NULL;
2385}
2386
Chris Lattner24943d22010-06-08 16:52:24 +00002387const char *
2388ProcessGDBRemote::GetDispatchQueueNameForThread
2389(
2390 addr_t thread_dispatch_qaddr,
2391 std::string &dispatch_queue_name
2392)
2393{
2394 dispatch_queue_name.clear();
2395 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2396 {
2397 // Cache the dispatch_queue_offsets_addr value so we don't always have
2398 // to look it up
2399 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2400 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002401 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2402 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton537a7a82010-10-20 20:54:39 +00002403 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false)));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002404 if (module_sp)
2405 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2406
2407 if (dispatch_queue_offsets_symbol == NULL)
2408 {
Greg Clayton537a7a82010-10-20 20:54:39 +00002409 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002410 if (module_sp)
2411 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2412 }
Chris Lattner24943d22010-06-08 16:52:24 +00002413 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002414 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002415
2416 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2417 return NULL;
2418 }
2419
2420 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002421 DataExtractor data (memory_buffer,
2422 sizeof(memory_buffer),
2423 m_target.GetArchitecture().GetByteOrder(),
2424 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002425
2426 // Excerpt from src/queue_private.h
2427 struct dispatch_queue_offsets_s
2428 {
2429 uint16_t dqo_version;
2430 uint16_t dqo_label;
2431 uint16_t dqo_label_size;
2432 } dispatch_queue_offsets;
2433
2434
2435 Error error;
2436 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2437 {
2438 uint32_t data_offset = 0;
2439 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2440 {
2441 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2442 {
2443 data_offset = 0;
2444 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2445 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2446 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2447 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2448 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2449 dispatch_queue_name.erase (bytes_read);
2450 }
2451 }
2452 }
2453 }
2454 if (dispatch_queue_name.empty())
2455 return NULL;
2456 return dispatch_queue_name.c_str();
2457}
2458
Jim Ingham7508e732010-08-09 23:31:02 +00002459uint32_t
2460ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2461{
2462 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2463 // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2464 if (m_local_debugserver)
2465 {
2466 return Host::ListProcessesMatchingName (name, matches, pids);
2467 }
2468 else
2469 {
2470 // FIXME: Implement talking to the remote debugserver.
2471 return 0;
2472 }
2473
2474}
Jim Ingham55e01d82011-01-22 01:33:44 +00002475
2476bool
2477ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2478 lldb_private::StoppointCallbackContext *context,
2479 lldb::user_id_t break_id,
2480 lldb::user_id_t break_loc_id)
2481{
2482 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2483 // run so I can stop it if that's what I want to do.
2484 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2485 if (log)
2486 log->Printf("Hit New Thread Notification breakpoint.");
2487 return false;
2488}
2489
2490
2491bool
2492ProcessGDBRemote::StartNoticingNewThreads()
2493{
2494 static const char *bp_names[] =
2495 {
2496 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002497 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002498 "_pthread_start",
2499 NULL
2500 };
2501
2502 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2503 size_t num_bps = m_thread_observation_bps.size();
2504 if (num_bps != 0)
2505 {
2506 for (int i = 0; i < num_bps; i++)
2507 {
2508 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2509 if (break_sp)
2510 {
2511 if (log)
2512 log->Printf("Enabled noticing new thread breakpoint.");
2513 break_sp->SetEnabled(true);
2514 }
2515 }
2516 }
2517 else
2518 {
2519 for (int i = 0; bp_names[i] != NULL; i++)
2520 {
2521 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2522 if (breakpoint)
2523 {
2524 if (log)
2525 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2526 m_thread_observation_bps.push_back(breakpoint->GetID());
2527 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2528 }
2529 else
2530 {
2531 if (log)
2532 log->Printf("Failed to create new thread notification breakpoint.");
2533 return false;
2534 }
2535 }
2536 }
2537
2538 return true;
2539}
2540
2541bool
2542ProcessGDBRemote::StopNoticingNewThreads()
2543{
Jim Inghamff276fe2011-02-08 05:19:01 +00002544 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2545 if (log)
2546 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002547 size_t num_bps = m_thread_observation_bps.size();
2548 if (num_bps != 0)
2549 {
2550 for (int i = 0; i < num_bps; i++)
2551 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002552
2553 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2554 if (break_sp)
2555 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002556 break_sp->SetEnabled(false);
2557 }
2558 }
2559 }
2560 return true;
2561}
2562
2563