blob: d39d1a5a63102b4b33d0dd98c2e3c796d7addc6d [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>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Sean Callanan483d00a2012-07-19 18:07:36 +000014#include <netinet/in.h>
Greg Clayton989816b2011-05-14 01:50:35 +000015#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000017#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000018#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000019
20// C++ Includes
21#include <algorithm>
22#include <map>
23
24// Other libraries and framework includes
25
Johnny Chenecd4feb2011-10-14 00:42:25 +000026#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000027#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Core/ArchSpec.h"
29#include "lldb/Core/Debugger.h"
30#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000031#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "lldb/Core/InputReader.h"
33#include "lldb/Core/Module.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000034#include "lldb/Core/ModuleSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/PluginManager.h"
36#include "lldb/Core/State.h"
Greg Clayton33559462012-04-13 21:24:18 +000037#include "lldb/Core/StreamFile.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Core/StreamString.h"
39#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000040#include "lldb/Core/Value.h"
Jason Molendab0e3c7c2012-09-29 08:03:33 +000041#include "lldb/Host/Symbols.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042#include "lldb/Host/TimeValue.h"
43#include "lldb/Symbol/ObjectFile.h"
44#include "lldb/Target/DynamicLoader.h"
45#include "lldb/Target/Target.h"
46#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000047#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000048#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049
50// Project includes
51#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000052#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molenda3aeb2862012-07-25 03:40:06 +000053#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham06b84492012-07-04 00:35:43 +000054#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000055#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000056#include "GDBRemoteRegisterContext.h"
57#include "ProcessGDBRemote.h"
58#include "ProcessGDBRemoteLog.h"
59#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000060
Greg Clayton451fa822012-04-09 22:46:21 +000061namespace lldb
62{
63 // Provide a function that can easily dump the packet history if we know a
64 // ProcessGDBRemote * value (which we can get from logs or from debugging).
65 // We need the function in the lldb namespace so it makes it into the final
66 // executable since the LLDB shared library only exports stuff in the lldb
67 // namespace. This allows you to attach with a debugger and call this
68 // function and get the packet history dumped to a file.
69 void
70 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
71 {
Greg Clayton33559462012-04-13 21:24:18 +000072 lldb_private::StreamFile strm;
73 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
74 if (error.Success())
75 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000076 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000077}
Chris Lattner24943d22010-06-08 16:52:24 +000078
Chris Lattner24943d22010-06-08 16:52:24 +000079
80#define DEBUGSERVER_BASENAME "debugserver"
81using namespace lldb;
82using namespace lldb_private;
83
Jim Inghamf9600482011-03-29 21:45:47 +000084static bool rand_initialized = false;
85
Sean Callanan483d00a2012-07-19 18:07:36 +000086// TODO Randomly assigning a port is unsafe. We should get an unused
87// ephemeral port from the kernel and make sure we reserve it before passing
88// it to debugserver.
89
90#if defined (__APPLE__)
91#define LOW_PORT (IPPORT_RESERVED)
92#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
93#else
94#define LOW_PORT (1024u)
95#define HIGH_PORT (49151u)
96#endif
97
Chris Lattner24943d22010-06-08 16:52:24 +000098static inline uint16_t
99get_random_port ()
100{
Jim Inghamf9600482011-03-29 21:45:47 +0000101 if (!rand_initialized)
102 {
Stephen Wilson60f19d52011-03-30 00:12:40 +0000103 time_t seed = time(NULL);
104
Jim Inghamf9600482011-03-29 21:45:47 +0000105 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +0000106 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +0000107 }
Sean Callanan483d00a2012-07-19 18:07:36 +0000108 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner24943d22010-06-08 16:52:24 +0000109}
110
111
112const char *
113ProcessGDBRemote::GetPluginNameStatic()
114{
Greg Claytonb1888f22011-03-19 01:12:21 +0000115 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000116}
117
118const char *
119ProcessGDBRemote::GetPluginDescriptionStatic()
120{
121 return "GDB Remote protocol based debugging plug-in.";
122}
123
124void
125ProcessGDBRemote::Terminate()
126{
127 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
128}
129
130
Greg Clayton46c9a352012-02-09 06:16:32 +0000131lldb::ProcessSP
132ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000133{
Greg Clayton46c9a352012-02-09 06:16:32 +0000134 lldb::ProcessSP process_sp;
135 if (crash_file_path == NULL)
136 process_sp.reset (new ProcessGDBRemote (target, listener));
137 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000138}
139
140bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000141ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000142{
Greg Clayton61ddf562011-10-21 21:41:45 +0000143 if (plugin_specified_by_name)
144 return true;
145
Chris Lattner24943d22010-06-08 16:52:24 +0000146 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000147 Module *exe_module = target.GetExecutableModulePointer();
148 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000149 {
150 ObjectFile *exe_objfile = exe_module->GetObjectFile();
151 // We can't debug core files...
152 switch (exe_objfile->GetType())
153 {
154 case ObjectFile::eTypeInvalid:
155 case ObjectFile::eTypeCoreFile:
156 case ObjectFile::eTypeDebugInfo:
157 case ObjectFile::eTypeObjectFile:
158 case ObjectFile::eTypeSharedLibrary:
159 case ObjectFile::eTypeStubLibrary:
160 return false;
161 case ObjectFile::eTypeExecutable:
162 case ObjectFile::eTypeDynamicLinker:
163 case ObjectFile::eTypeUnknown:
164 break;
165 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000166 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000167 }
Jim Ingham7508e732010-08-09 23:31:02 +0000168 // However, if there is no executable module, we return true since we might be preparing to attach.
169 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000170}
171
172//----------------------------------------------------------------------
173// ProcessGDBRemote constructor
174//----------------------------------------------------------------------
175ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
176 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000177 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000178 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000179 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000180 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000181 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000182 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000183 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000184 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000185 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000186 m_continue_c_tids (),
187 m_continue_C_tids (),
188 m_continue_s_tids (),
189 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000190 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000191 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000192 m_addr_to_mmap_size (),
193 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000194 m_waiting_for_attach (false),
195 m_destroy_tried_resuming (false)
Chris Lattner24943d22010-06-08 16:52:24 +0000196{
Greg Claytonff39f742011-04-01 00:29:43 +0000197 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
198 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000199 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000200}
201
202//----------------------------------------------------------------------
203// Destructor
204//----------------------------------------------------------------------
205ProcessGDBRemote::~ProcessGDBRemote()
206{
207 // m_mach_process.UnregisterNotificationCallbacks (this);
208 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000209 // We need to call finalize on the process before destroying ourselves
210 // to make sure all of the broadcaster cleanup goes as planned. If we
211 // destruct this class, then Process::~Process() might have problems
212 // trying to fully destroy the broadcaster.
213 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000214}
215
216//----------------------------------------------------------------------
217// PluginInterface
218//----------------------------------------------------------------------
219const char *
220ProcessGDBRemote::GetPluginName()
221{
222 return "Process debugging plug-in that uses the GDB remote protocol";
223}
224
225const char *
226ProcessGDBRemote::GetShortPluginName()
227{
228 return GetPluginNameStatic();
229}
230
231uint32_t
232ProcessGDBRemote::GetPluginVersion()
233{
234 return 1;
235}
236
237void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000238ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000239{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000240 if (!force && m_register_info.GetNumRegisters() > 0)
241 return;
242
243 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000244 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000245 uint32_t reg_offset = 0;
246 uint32_t reg_num = 0;
Greg Clayton4a379b12012-07-17 03:23:13 +0000247 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton61d043b2011-03-22 04:00:09 +0000248 response_type == StringExtractorGDBRemote::eResponse;
249 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000250 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000251 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
252 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000253 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000254 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000255 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000256 response_type = response.GetResponseType();
257 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000258 {
259 std::string name;
260 std::string value;
261 ConstString reg_name;
262 ConstString alt_name;
263 ConstString set_name;
264 RegisterInfo reg_info = { NULL, // Name
265 NULL, // Alt name
266 0, // byte size
267 reg_offset, // offset
268 eEncodingUint, // encoding
269 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000270 {
271 LLDB_INVALID_REGNUM, // GCC reg num
272 LLDB_INVALID_REGNUM, // DWARF reg num
273 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000274 reg_num, // GDB reg num
275 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000276 },
277 NULL,
278 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000279 };
280
281 while (response.GetNameColonValue(name, value))
282 {
283 if (name.compare("name") == 0)
284 {
285 reg_name.SetCString(value.c_str());
286 }
287 else if (name.compare("alt-name") == 0)
288 {
289 alt_name.SetCString(value.c_str());
290 }
291 else if (name.compare("bitsize") == 0)
292 {
293 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
294 }
295 else if (name.compare("offset") == 0)
296 {
297 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000298 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000299 {
300 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000301 }
302 }
303 else if (name.compare("encoding") == 0)
304 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000305 const Encoding encoding = Args::StringToEncoding (value.c_str());
306 if (encoding != eEncodingInvalid)
307 reg_info.encoding = encoding;
Chris Lattner24943d22010-06-08 16:52:24 +0000308 }
309 else if (name.compare("format") == 0)
310 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000311 Format format = eFormatInvalid;
312 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
313 reg_info.format = format;
314 else if (value.compare("binary") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000315 reg_info.format = eFormatBinary;
316 else if (value.compare("decimal") == 0)
317 reg_info.format = eFormatDecimal;
318 else if (value.compare("hex") == 0)
319 reg_info.format = eFormatHex;
320 else if (value.compare("float") == 0)
321 reg_info.format = eFormatFloat;
322 else if (value.compare("vector-sint8") == 0)
323 reg_info.format = eFormatVectorOfSInt8;
324 else if (value.compare("vector-uint8") == 0)
325 reg_info.format = eFormatVectorOfUInt8;
326 else if (value.compare("vector-sint16") == 0)
327 reg_info.format = eFormatVectorOfSInt16;
328 else if (value.compare("vector-uint16") == 0)
329 reg_info.format = eFormatVectorOfUInt16;
330 else if (value.compare("vector-sint32") == 0)
331 reg_info.format = eFormatVectorOfSInt32;
332 else if (value.compare("vector-uint32") == 0)
333 reg_info.format = eFormatVectorOfUInt32;
334 else if (value.compare("vector-float32") == 0)
335 reg_info.format = eFormatVectorOfFloat32;
336 else if (value.compare("vector-uint128") == 0)
337 reg_info.format = eFormatVectorOfUInt128;
338 }
339 else if (name.compare("set") == 0)
340 {
341 set_name.SetCString(value.c_str());
342 }
343 else if (name.compare("gcc") == 0)
344 {
345 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
346 }
347 else if (name.compare("dwarf") == 0)
348 {
349 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
350 }
351 else if (name.compare("generic") == 0)
352 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000353 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000354 }
355 }
356
Jason Molenda53d96862010-06-11 23:44:18 +0000357 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000358 assert (reg_info.byte_size != 0);
359 reg_offset += reg_info.byte_size;
360 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
361 }
362 }
363 else
364 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000365 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000366 }
367 }
368
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000369 // We didn't get anything if the accumulated reg_num is zero. See if we are
370 // debugging ARM and fill with a hard coded register set until we can get an
371 // updated debugserver down on the devices.
372 // On the other hand, if the accumulated reg_num is positive, see if we can
373 // add composite registers to the existing primordial ones.
374 bool from_scratch = (reg_num == 0);
375
376 const ArchSpec &target_arch = GetTarget().GetArchitecture();
377 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
378 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000379 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000380 if (remote_arch.IsValid()
381 && remote_arch.GetMachine() == llvm::Triple::arm
382 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
383 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000384 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000385 else if (target_arch.GetMachine() == llvm::Triple::arm)
386 {
387 m_register_info.HardcodeARMRegisters(from_scratch);
388 }
389
Johnny Chend2e30662012-05-22 00:57:05 +0000390 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000391 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
392 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000393 m_register_info.Addx86_64ConvenienceRegisters();
394
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000395 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000396 m_register_info.Finalize ();
397}
398
399Error
400ProcessGDBRemote::WillLaunch (Module* module)
401{
402 return WillLaunchOrAttach ();
403}
404
405Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000406ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000407{
408 return WillLaunchOrAttach ();
409}
410
411Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000412ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000413{
414 return WillLaunchOrAttach ();
415}
416
417Error
Jason Molendafac2e622012-09-29 04:02:01 +0000418ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +0000419{
420 Error error (WillLaunchOrAttach ());
421
422 if (error.Fail())
423 return error;
424
Greg Clayton180546b2011-04-30 01:09:13 +0000425 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000426
427 if (error.Fail())
428 return error;
429 StartAsyncThread ();
430
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000431 RelocateOrLoadKernel (strm);
Jason Molendafac2e622012-09-29 04:02:01 +0000432
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000433 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000434 if (pid == LLDB_INVALID_PROCESS_ID)
435 {
436 // We don't have a valid process ID, so note that we are connected
437 // and could now request to launch or attach, or get remote process
438 // listings...
439 SetPrivateState (eStateConnected);
440 }
441 else
442 {
443 // We have a valid process
444 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000445 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000446 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000447 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000448 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000449 if (state == eStateStopped)
450 {
451 SetPrivateState (state);
452 }
453 else
Greg Claytond9919d32011-12-01 23:28:38 +0000454 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytone71e2582011-02-04 01:58:07 +0000455 }
456 else
Greg Claytond9919d32011-12-01 23:28:38 +0000457 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000458 }
Jason Molendacb740b32012-05-03 22:37:30 +0000459
460 if (error.Success()
461 && !GetTarget().GetArchitecture().IsValid()
462 && m_gdb_comm.GetHostArchitecture().IsValid())
463 {
464 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
465 }
466
Greg Claytone71e2582011-02-04 01:58:07 +0000467 return error;
468}
469
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000470// When we are establishing a connection to a remote system and we have no executable specified,
471// or the executable is a kernel, we may be looking at a KASLR situation (where the kernel has been
472// slid in memory.)
473//
474// This function does several things:
475//
476// 1. If a non-kernel executable is provided, do nothing. If the executable provided is a kernel and
477// it loaded at a non-slid address (FileAddress == LoadAddress), do nothing.
478//
479// 2. When in debug mode the kernel will record its actual load address at a fixed address in memory.
480// Check those addresses, see if there is a kernel binary at them.
481//
482// 3. If we find a kernel in memory and it matches the executable provided, adjust to the slide.
483//
484// 4. If lldb was given no executable at startup, or the one we find in memory does not match the one
485// provided, try to locate a copy of the correct kernel on the host system. Else read it out of memory.
486//
487// gdb would take an additional series of steps where it would scan through memory looking for a kernel
488// to find a slid kernel that was not booted in debug mode (these were also needed back when the kernel
489// didn't record its load address anywhere). With luck we won't need to pull those in to lldb.
490//
491// The obvious location for all of this code would be in the DynamicLoaderDarwinKernel -- but if we're started
492// without any executable binary provided, we won't know to use that plugin.
493
494void
495ProcessGDBRemote::RelocateOrLoadKernel (Stream *strm)
496{
497 // early return if this isn't an "unknown" system (kernel debugging doesn't have a system type)
498 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
499 if (!gdb_remote_arch.IsValid() || gdb_remote_arch.GetTriple().getVendor() != llvm::Triple::UnknownVendor)
500 return;
501
502 Module *exe_module = GetTarget().GetExecutableModulePointer();
503 ObjectFile *exe_objfile = NULL;
504 if (exe_module)
505 exe_objfile = exe_module->GetObjectFile();
506
507 // early return if we have an executable and it is not a kernel--this is very unlikely to be a kernel debug session.
508 if (exe_objfile
509 && (exe_objfile->GetType() != ObjectFile::eTypeExecutable
510 || exe_objfile->GetStrata() != ObjectFile::eStrataKernel))
511 return;
512
513 // See if the kernel is in memory at the File address (slide == 0) -- no work needed, if so.
514 if (exe_objfile && exe_objfile->GetHeaderAddress().IsValid())
515 {
516 ModuleSP memory_module_sp;
517 memory_module_sp = ReadModuleFromMemory (exe_module->GetFileSpec(), exe_objfile->GetHeaderAddress().GetFileAddress(), false, false);
518 if (memory_module_sp.get()
519 && memory_module_sp->GetUUID().IsValid()
520 && memory_module_sp->GetUUID() == exe_module->GetUUID())
521 {
522 bool changed = false;
523 exe_module->SetLoadAddress (GetTarget(), 0, changed);
524 return;
525 }
526 }
527
528 // See if the kernel's load address is stored in the kernel's low globals page; this is
529 // done when a debug boot-arg has been set.
530
531 Error error;
532 uint8_t buf[24];
533 ModuleSP memory_module_sp;
534 addr_t kernel_addr = LLDB_INVALID_ADDRESS;
535
536 // First try the 32-bit
537 if (memory_module_sp.get() == NULL)
538 {
539 DataExtractor data4 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 4);
540 if (DoReadMemory (0xffff0110, buf, 4, error) == 4)
541 {
542 uint32_t offset = 0;
543 kernel_addr = data4.GetU32(&offset);
544 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
545 if (!memory_module_sp.get()
546 || !memory_module_sp->GetUUID().IsValid()
547 || memory_module_sp->GetObjectFile() == NULL
548 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
549 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
550 {
551 memory_module_sp.reset();
552 }
553 }
554 }
555
556 // Now try the 64-bit location
557 if (memory_module_sp.get() == NULL)
558 {
559 DataExtractor data8 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 8);
560 if (DoReadMemory (0xffffff8000002010ULL, buf, 8, error) == 8)
561 {
562 uint32_t offset = 0;
563 kernel_addr = data8.GetU32(&offset);
564 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
565 if (!memory_module_sp.get()
566 || !memory_module_sp->GetUUID().IsValid()
567 || memory_module_sp->GetObjectFile() == NULL
568 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
569 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
570 {
571 memory_module_sp.reset();
572 }
573 }
574 }
575
576 if (memory_module_sp.get())
577 {
578 if (strm)
579 {
580 char uuidbuf[64];
581 strm->Printf ("Kernel UUID: %s\n", memory_module_sp->GetUUID().GetAsCString (uuidbuf, sizeof (uuidbuf)));
582 strm->Printf ("Load Address: 0x%llx\n", kernel_addr);
583 strm->Flush ();
584 }
585
586 // Did the user already give us the correct binary? Don't re-load it if so, just set the load addr.
587 if (exe_module && exe_objfile && exe_module->GetUUID() == memory_module_sp->GetUUID())
588 {
589 bool changed = false;
590 addr_t slide = kernel_addr - exe_objfile->GetHeaderAddress().GetFileAddress();
591 exe_module->SetLoadAddress (GetTarget(), slide, changed);
592 if (changed)
593 {
594 ModuleList modlist;
595 modlist.Append (GetTarget().GetExecutableModule());
596 GetTarget().ModulesDidLoad (modlist);
597 }
598 return;
599 }
600
601 // OK try to find a kernel on the local system, or get it from memory
602 LoadKernel (strm, memory_module_sp->GetUUID(), kernel_addr);
603 }
604}
605
606void
607ProcessGDBRemote::LoadKernel (Stream *strm, UUID kernel_uuid, addr_t kernel_load_addr)
608{
609
610 // First try to find the kernel binary by calling Symbols::DownloadObjectAndSymbolFile
611 ModuleSpec sym_spec;
612 sym_spec.GetUUID() = kernel_uuid;
613 if (Symbols::DownloadObjectAndSymbolFile (sym_spec)
614 && sym_spec.GetArchitecture().IsValid()
615 && sym_spec.GetSymbolFileSpec().Exists())
616 {
617 ModuleSP kernel_sp = GetTarget().GetSharedModule (sym_spec);
618 if (kernel_sp.get())
619 {
620 GetTarget().SetExecutableModule(kernel_sp, false);
621 if (kernel_sp->GetObjectFile() && kernel_sp->GetObjectFile()->GetHeaderAddress().IsValid())
622 {
623 addr_t slide = kernel_load_addr - kernel_sp->GetObjectFile()->GetHeaderAddress().GetFileAddress();
624 bool changed = false;
625 kernel_sp->SetLoadAddress (GetTarget(), slide, changed);
626 if (changed)
627 {
628 ModuleList modlist;
629 modlist.Append (kernel_sp);
630 GetTarget().ModulesDidLoad (modlist);
631 }
632 if (strm)
633 {
634 strm->Printf ("Loaded kernel file %s/%s\n",
635 kernel_sp->GetFileSpec().GetDirectory().AsCString(),
636 kernel_sp->GetFileSpec().GetFilename().AsCString());
637 strm->Flush ();
638 }
639 return;
640 }
641 }
642 }
643
644 // If nothing better, load the kernel binary out of memory - this is likely slow and may not get us symbols.
645 ModuleSP memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_load_addr, true, true);
646 if (memory_module_sp.get()
647 && memory_module_sp->GetUUID().IsValid()
648 && memory_module_sp->GetObjectFile()
649 && memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable
650 && memory_module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel)
651 {
652 bool changed;
653 uint64_t slide = kernel_load_addr - memory_module_sp->GetObjectFile()->GetHeaderAddress().GetFileAddress();
654 memory_module_sp->SetLoadAddress (GetTarget(), slide, changed);
655 GetTarget().SetExecutableModule(memory_module_sp, false);
656 }
657}
658
Greg Claytone71e2582011-02-04 01:58:07 +0000659Error
Chris Lattner24943d22010-06-08 16:52:24 +0000660ProcessGDBRemote::WillLaunchOrAttach ()
661{
662 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000663 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000664 return error;
665}
666
667//----------------------------------------------------------------------
668// Process Control
669//----------------------------------------------------------------------
670Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000671ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000672{
Greg Clayton4b407112010-09-30 21:49:03 +0000673 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000674
675 uint32_t launch_flags = launch_info.GetFlags().Get();
676 const char *stdin_path = NULL;
677 const char *stdout_path = NULL;
678 const char *stderr_path = NULL;
679 const char *working_dir = launch_info.GetWorkingDirectory();
680
681 const ProcessLaunchInfo::FileAction *file_action;
682 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
683 if (file_action)
684 {
685 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
686 stdin_path = file_action->GetPath();
687 }
688 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
689 if (file_action)
690 {
691 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
692 stdout_path = file_action->GetPath();
693 }
694 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
695 if (file_action)
696 {
697 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
698 stderr_path = file_action->GetPath();
699 }
700
Chris Lattner24943d22010-06-08 16:52:24 +0000701 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
702 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
703 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000704 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000705
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000706 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000707 if (object_file)
708 {
Chris Lattner24943d22010-06-08 16:52:24 +0000709 char host_port[128];
710 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000711 char connect_url[128];
712 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000713
Greg Claytona2f74232011-02-24 22:24:29 +0000714 // Make sure we aren't already connected?
715 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000716 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000717 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000718 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000719 {
Johnny Chenc143d622011-08-09 18:56:45 +0000720 if (log)
721 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000722 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000723 }
Chris Lattner24943d22010-06-08 16:52:24 +0000724
Greg Claytone71e2582011-02-04 01:58:07 +0000725 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000726 }
727
728 if (error.Success())
729 {
730 lldb_utility::PseudoTerminal pty;
731 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000732
733 // If the debugserver is local and we aren't disabling STDIO, lets use
734 // a pseudo terminal to instead of relying on the 'O' packets for stdio
735 // since 'O' packets can really slow down debugging if the inferior
736 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000737 PlatformSP platform_sp (m_target.GetPlatform());
738 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000739 {
740 const char *slave_name = NULL;
741 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000742 {
Greg Claytona2f74232011-02-24 22:24:29 +0000743 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
744 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000745 }
Greg Claytona2f74232011-02-24 22:24:29 +0000746 if (stdin_path == NULL)
747 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000748
Greg Claytona2f74232011-02-24 22:24:29 +0000749 if (stdout_path == NULL)
750 stdout_path = slave_name;
751
752 if (stderr_path == NULL)
753 stderr_path = slave_name;
754 }
755
Greg Claytonafb81862011-03-02 21:34:46 +0000756 // Set STDIN to /dev/null if we want STDIO disabled or if either
757 // STDOUT or STDERR have been set to something and STDIN hasn't
758 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000759 stdin_path = "/dev/null";
760
Greg Claytonafb81862011-03-02 21:34:46 +0000761 // Set STDOUT to /dev/null if we want STDIO disabled or if either
762 // STDIN or STDERR have been set to something and STDOUT hasn't
763 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000764 stdout_path = "/dev/null";
765
Greg Claytonafb81862011-03-02 21:34:46 +0000766 // Set STDERR to /dev/null if we want STDIO disabled or if either
767 // STDIN or STDOUT have been set to something and STDERR hasn't
768 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000769 stderr_path = "/dev/null";
770
771 if (stdin_path)
772 m_gdb_comm.SetSTDIN (stdin_path);
773 if (stdout_path)
774 m_gdb_comm.SetSTDOUT (stdout_path);
775 if (stderr_path)
776 m_gdb_comm.SetSTDERR (stderr_path);
777
778 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
779
Greg Claytona4582402011-05-08 04:53:50 +0000780 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000781
782 if (working_dir && working_dir[0])
783 {
784 m_gdb_comm.SetWorkingDir (working_dir);
785 }
786
787 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000788 const Args &environment = launch_info.GetEnvironmentEntries();
789 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000790 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000791 size_t num_environment_entries = environment.GetArgumentCount();
792 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000793 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000794 const char *env_entry = environment.GetArgumentAtIndex(i);
795 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000796 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000797 }
Greg Claytona2f74232011-02-24 22:24:29 +0000798 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000799
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000800 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000801 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000802 if (arg_packet_err == 0)
803 {
804 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000805 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000806 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000807 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000808 }
809 else
810 {
Greg Claytona2f74232011-02-24 22:24:29 +0000811 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000812 }
Greg Claytona2f74232011-02-24 22:24:29 +0000813 }
814 else
815 {
Greg Clayton9c236732011-10-26 00:56:27 +0000816 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000817 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000818
819 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000820
Greg Claytona2f74232011-02-24 22:24:29 +0000821 if (GetID() == LLDB_INVALID_PROCESS_ID)
822 {
Johnny Chenc143d622011-08-09 18:56:45 +0000823 if (log)
824 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000825 KillDebugserverProcess ();
826 return error;
827 }
828
Greg Clayton261a18b2011-06-02 22:22:38 +0000829 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000830 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000831 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000832
833 if (!disable_stdio)
834 {
835 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000836 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000837 }
Chris Lattner24943d22010-06-08 16:52:24 +0000838 }
839 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000840 else
841 {
Johnny Chenc143d622011-08-09 18:56:45 +0000842 if (log)
843 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000844 }
Chris Lattner24943d22010-06-08 16:52:24 +0000845 }
846 else
847 {
848 // Set our user ID to an invalid process ID.
849 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000850 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
851 exe_module->GetFileSpec().GetFilename().AsCString(),
852 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000853 }
Chris Lattner24943d22010-06-08 16:52:24 +0000854 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000855
Chris Lattner24943d22010-06-08 16:52:24 +0000856}
857
858
859Error
Greg Claytone71e2582011-02-04 01:58:07 +0000860ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000861{
862 Error error;
863 // Sleep and wait a bit for debugserver to start to listen...
864 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
865 if (conn_ap.get())
866 {
Chris Lattner24943d22010-06-08 16:52:24 +0000867 const uint32_t max_retry_count = 50;
868 uint32_t retry_count = 0;
869 while (!m_gdb_comm.IsConnected())
870 {
Greg Claytone71e2582011-02-04 01:58:07 +0000871 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000872 {
873 m_gdb_comm.SetConnection (conn_ap.release());
874 break;
875 }
876 retry_count++;
877
878 if (retry_count >= max_retry_count)
879 break;
880
881 usleep (100000);
882 }
883 }
884
885 if (!m_gdb_comm.IsConnected())
886 {
887 if (error.Success())
888 error.SetErrorString("not connected to remote gdb server");
889 return error;
890 }
891
Greg Clayton24bc5d92011-03-30 18:16:51 +0000892 // We always seem to be able to open a connection to a local port
893 // so we need to make sure we can then send data to it. If we can't
894 // then we aren't actually connected to anything, so try and do the
895 // handshake with the remote GDB server and make sure that goes
896 // alright.
897 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000898 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000899 m_gdb_comm.Disconnect();
900 if (error.Success())
901 error.SetErrorString("not connected to remote gdb server");
902 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000903 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000904 m_gdb_comm.ResetDiscoverableSettings();
905 m_gdb_comm.QueryNoAckModeSupported ();
906 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000907 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000908 m_gdb_comm.GetHostInfo ();
909 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000910 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000911
912 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
913 for (size_t idx = 0; idx < num_cmds; idx++)
914 {
915 StringExtractorGDBRemote response;
916 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx));
917 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
918 }
Chris Lattner24943d22010-06-08 16:52:24 +0000919 return error;
920}
921
922void
923ProcessGDBRemote::DidLaunchOrAttach ()
924{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000925 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
926 if (log)
927 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000928 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000929 {
930 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
931
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000932 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000933
Chris Lattner24943d22010-06-08 16:52:24 +0000934 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000935
Greg Claytoncb8977d2011-03-23 00:09:55 +0000936 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
937 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000938 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000939 ArchSpec &target_arch = GetTarget().GetArchitecture();
940
941 if (target_arch.IsValid())
942 {
943 // If the remote host is ARM and we have apple as the vendor, then
944 // ARM executables and shared libraries can have mixed ARM architectures.
945 // You can have an armv6 executable, and if the host is armv7, then the
946 // system will load the best possible architecture for all shared libraries
947 // it has, so we really need to take the remote host architecture as our
948 // defacto architecture in this case.
949
950 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
951 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
952 {
953 target_arch = gdb_remote_arch;
954 }
955 else
956 {
957 // Fill in what is missing in the triple
958 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
959 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000960 if (target_triple.getVendorName().size() == 0)
961 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000962 target_triple.setVendor (remote_triple.getVendor());
963
Greg Clayton2f085c62011-05-15 01:25:55 +0000964 if (target_triple.getOSName().size() == 0)
965 {
966 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000967
Greg Clayton2f085c62011-05-15 01:25:55 +0000968 if (target_triple.getEnvironmentName().size() == 0)
969 target_triple.setEnvironment (remote_triple.getEnvironment());
970 }
971 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000972 }
973 }
974 else
975 {
976 // The target doesn't have a valid architecture yet, set it from
977 // the architecture we got from the remote GDB server
978 target_arch = gdb_remote_arch;
979 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000980 }
Chris Lattner24943d22010-06-08 16:52:24 +0000981 }
982}
983
984void
985ProcessGDBRemote::DidLaunch ()
986{
987 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000988}
989
990Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000991ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000992{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000993 ProcessAttachInfo attach_info;
994 return DoAttachToProcessWithID(attach_pid, attach_info);
995}
996
997Error
998ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
999{
Chris Lattner24943d22010-06-08 16:52:24 +00001000 Error error;
1001 // Clear out and clean up from any current state
1002 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001003 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1004 {
Greg Claytona2f74232011-02-24 22:24:29 +00001005 // Make sure we aren't already connected?
1006 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001007 {
Greg Claytona2f74232011-02-24 22:24:29 +00001008 char host_port[128];
1009 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1010 char connect_url[128];
1011 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +00001012
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001013 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +00001014
1015 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001016 {
Greg Claytona2f74232011-02-24 22:24:29 +00001017 const char *error_string = error.AsCString();
1018 if (error_string == NULL)
1019 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1020
1021 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001022 }
Greg Claytona2f74232011-02-24 22:24:29 +00001023 else
1024 {
1025 error = ConnectToDebugserver (connect_url);
1026 }
1027 }
1028
1029 if (error.Success())
1030 {
1031 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +00001032 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +00001033 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +00001034 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +00001035 }
1036 }
Chris Lattner24943d22010-06-08 16:52:24 +00001037 return error;
1038}
1039
1040size_t
1041ProcessGDBRemote::AttachInputReaderCallback
1042(
1043 void *baton,
1044 InputReader *reader,
1045 lldb::InputReaderAction notification,
1046 const char *bytes,
1047 size_t bytes_len
1048)
1049{
1050 if (notification == eInputReaderGotToken)
1051 {
1052 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
1053 if (gdb_process->m_waiting_for_attach)
1054 gdb_process->m_waiting_for_attach = false;
1055 reader->SetIsDone(true);
1056 return 1;
1057 }
1058 return 0;
1059}
1060
1061Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001062ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00001063{
1064 Error error;
1065 // Clear out and clean up from any current state
1066 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001067
Chris Lattner24943d22010-06-08 16:52:24 +00001068 if (process_name && process_name[0])
1069 {
Greg Claytona2f74232011-02-24 22:24:29 +00001070 // Make sure we aren't already connected?
1071 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001072 {
Greg Claytona2f74232011-02-24 22:24:29 +00001073 char host_port[128];
1074 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1075 char connect_url[128];
1076 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1077
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001078 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +00001079 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001080 {
Greg Claytona2f74232011-02-24 22:24:29 +00001081 const char *error_string = error.AsCString();
1082 if (error_string == NULL)
1083 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +00001084
Greg Claytona2f74232011-02-24 22:24:29 +00001085 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001086 }
Greg Claytona2f74232011-02-24 22:24:29 +00001087 else
1088 {
1089 error = ConnectToDebugserver (connect_url);
1090 }
1091 }
1092
1093 if (error.Success())
1094 {
1095 StreamString packet;
1096
1097 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +00001098 {
1099 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1100 {
1101 packet.PutCString ("vAttachWait");
1102 }
1103 else
1104 {
1105 if (attach_info.GetIgnoreExisting())
1106 packet.PutCString("vAttachWait");
1107 else
1108 packet.PutCString ("vAttachOrWait");
1109 }
1110 }
Greg Claytona2f74232011-02-24 22:24:29 +00001111 else
1112 packet.PutCString("vAttachName");
1113 packet.PutChar(';');
1114 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1115
1116 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1117
Chris Lattner24943d22010-06-08 16:52:24 +00001118 }
1119 }
Chris Lattner24943d22010-06-08 16:52:24 +00001120 return error;
1121}
1122
Chris Lattner24943d22010-06-08 16:52:24 +00001123
1124void
1125ProcessGDBRemote::DidAttach ()
1126{
Greg Claytone71e2582011-02-04 01:58:07 +00001127 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +00001128}
1129
1130Error
1131ProcessGDBRemote::WillResume ()
1132{
Greg Claytonc1f45872011-02-12 06:28:37 +00001133 m_continue_c_tids.clear();
1134 m_continue_C_tids.clear();
1135 m_continue_s_tids.clear();
1136 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001137 return Error();
1138}
1139
1140Error
1141ProcessGDBRemote::DoResume ()
1142{
Jim Ingham3ae449a2010-11-17 02:32:00 +00001143 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001144 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1145 if (log)
1146 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +00001147
1148 Listener listener ("gdb-remote.resume-packet-sent");
1149 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1150 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001151 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1152
Greg Claytonc1f45872011-02-12 06:28:37 +00001153 StreamString continue_packet;
1154 bool continue_packet_error = false;
1155 if (m_gdb_comm.HasAnyVContSupport ())
1156 {
1157 continue_packet.PutCString ("vCont");
1158
1159 if (!m_continue_c_tids.empty())
1160 {
1161 if (m_gdb_comm.GetVContSupported ('c'))
1162 {
1163 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)
Greg Claytond9919d32011-12-01 23:28:38 +00001164 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001165 }
1166 else
1167 continue_packet_error = true;
1168 }
1169
1170 if (!continue_packet_error && !m_continue_C_tids.empty())
1171 {
1172 if (m_gdb_comm.GetVContSupported ('C'))
1173 {
1174 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)
Greg Claytond9919d32011-12-01 23:28:38 +00001175 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001176 }
1177 else
1178 continue_packet_error = true;
1179 }
Greg Claytonb749a262010-12-03 06:02:24 +00001180
Greg Claytonc1f45872011-02-12 06:28:37 +00001181 if (!continue_packet_error && !m_continue_s_tids.empty())
1182 {
1183 if (m_gdb_comm.GetVContSupported ('s'))
1184 {
1185 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)
Greg Claytond9919d32011-12-01 23:28:38 +00001186 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001187 }
1188 else
1189 continue_packet_error = true;
1190 }
1191
1192 if (!continue_packet_error && !m_continue_S_tids.empty())
1193 {
1194 if (m_gdb_comm.GetVContSupported ('S'))
1195 {
1196 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)
Greg Claytond9919d32011-12-01 23:28:38 +00001197 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001198 }
1199 else
1200 continue_packet_error = true;
1201 }
1202
1203 if (continue_packet_error)
1204 continue_packet.GetString().clear();
1205 }
1206 else
1207 continue_packet_error = true;
1208
1209 if (continue_packet_error)
1210 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001211 // Either no vCont support, or we tried to use part of the vCont
1212 // packet that wasn't supported by the remote GDB server.
1213 // We need to try and make a simple packet that can do our continue
1214 const size_t num_threads = GetThreadList().GetSize();
1215 const size_t num_continue_c_tids = m_continue_c_tids.size();
1216 const size_t num_continue_C_tids = m_continue_C_tids.size();
1217 const size_t num_continue_s_tids = m_continue_s_tids.size();
1218 const size_t num_continue_S_tids = m_continue_S_tids.size();
1219 if (num_continue_c_tids > 0)
1220 {
1221 if (num_continue_c_tids == num_threads)
1222 {
1223 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001224 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001225 continue_packet.PutChar ('c');
1226 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001227 }
1228 else if (num_continue_c_tids == 1 &&
1229 num_continue_C_tids == 0 &&
1230 num_continue_s_tids == 0 &&
1231 num_continue_S_tids == 0 )
1232 {
1233 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001234 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001235 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001236 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001237 }
1238 }
1239
Greg Claytonde1dd812011-06-24 03:21:43 +00001240 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001241 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001242 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1243 num_continue_C_tids > 0 &&
1244 num_continue_s_tids == 0 &&
1245 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001246 {
1247 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001248 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001249 if (num_continue_C_tids > 1)
1250 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001251 // More that one thread with a signal, yet we don't have
1252 // vCont support and we are being asked to resume each
1253 // thread with a signal, we need to make sure they are
1254 // all the same signal, or we can't issue the continue
1255 // accurately with the current support...
1256 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001257 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001258 continue_packet_error = false;
1259 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1260 {
1261 if (m_continue_C_tids[i].second != continue_signo)
1262 continue_packet_error = true;
1263 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001264 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001265 if (!continue_packet_error)
1266 m_gdb_comm.SetCurrentThreadForRun (-1);
1267 }
1268 else
1269 {
1270 // Set the continue thread ID
1271 continue_packet_error = false;
1272 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001273 }
1274 if (!continue_packet_error)
1275 {
1276 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001277 continue_packet.Printf("C%2.2x", continue_signo);
1278 }
1279 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001280 }
1281
Greg Claytonde1dd812011-06-24 03:21:43 +00001282 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001283 {
1284 if (num_continue_s_tids == num_threads)
1285 {
1286 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001287 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001288 continue_packet.PutChar ('s');
1289 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001290 }
1291 else if (num_continue_c_tids == 0 &&
1292 num_continue_C_tids == 0 &&
1293 num_continue_s_tids == 1 &&
1294 num_continue_S_tids == 0 )
1295 {
1296 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001297 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001298 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001299 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001300 }
1301 }
1302
1303 if (!continue_packet_error && num_continue_S_tids > 0)
1304 {
1305 if (num_continue_S_tids == num_threads)
1306 {
1307 const int step_signo = m_continue_S_tids.front().second;
1308 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001309 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001310 if (num_continue_S_tids > 1)
1311 {
1312 for (size_t i=1; i<num_threads; ++i)
1313 {
1314 if (m_continue_S_tids[i].second != step_signo)
1315 continue_packet_error = true;
1316 }
1317 }
1318 if (!continue_packet_error)
1319 {
1320 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001321 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001322 continue_packet.Printf("S%2.2x", step_signo);
1323 }
1324 }
1325 else if (num_continue_c_tids == 0 &&
1326 num_continue_C_tids == 0 &&
1327 num_continue_s_tids == 0 &&
1328 num_continue_S_tids == 1 )
1329 {
1330 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001331 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001332 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001333 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001334 }
1335 }
1336 }
1337
1338 if (continue_packet_error)
1339 {
1340 error.SetErrorString ("can't make continue packet for this resume");
1341 }
1342 else
1343 {
1344 EventSP event_sp;
1345 TimeValue timeout;
1346 timeout = TimeValue::Now();
1347 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001348 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1349 {
1350 error.SetErrorString ("Trying to resume but the async thread is dead.");
1351 if (log)
1352 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1353 return error;
1354 }
1355
Greg Claytonc1f45872011-02-12 06:28:37 +00001356 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1357
1358 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001359 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001360 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001361 if (log)
1362 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1363 }
1364 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1365 {
1366 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1367 if (log)
1368 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1369 return error;
1370 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001371 }
Greg Claytonb749a262010-12-03 06:02:24 +00001372 }
1373
Jim Ingham3ae449a2010-11-17 02:32:00 +00001374 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001375}
1376
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001377void
1378ProcessGDBRemote::ClearThreadIDList ()
1379{
Greg Claytonff3448e2012-04-13 02:11:32 +00001380 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001381 m_thread_ids.clear();
1382}
1383
1384bool
1385ProcessGDBRemote::UpdateThreadIDList ()
1386{
Greg Claytonff3448e2012-04-13 02:11:32 +00001387 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001388 bool sequence_mutex_unavailable = false;
1389 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1390 if (sequence_mutex_unavailable)
1391 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001392 return false; // We just didn't get the list
1393 }
1394 return true;
1395}
1396
Greg Claytonae932352012-04-10 00:18:59 +00001397bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001398ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001399{
1400 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001401 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001402 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001403 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001404
1405 size_t num_thread_ids = m_thread_ids.size();
1406 // The "m_thread_ids" thread ID list should always be updated after each stop
1407 // reply packet, but in case it isn't, update it here.
1408 if (num_thread_ids == 0)
1409 {
1410 if (!UpdateThreadIDList ())
1411 return false;
1412 num_thread_ids = m_thread_ids.size();
1413 }
Chris Lattner24943d22010-06-08 16:52:24 +00001414
Greg Clayton37f962e2011-08-22 02:49:39 +00001415 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001416 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001417 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001418 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001419 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001420 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1421 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001422 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001423 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001424 }
Chris Lattner24943d22010-06-08 16:52:24 +00001425 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001426
Greg Claytonae932352012-04-10 00:18:59 +00001427 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001428}
1429
1430
1431StateType
1432ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1433{
Greg Clayton261a18b2011-06-02 22:22:38 +00001434 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001435 const char stop_type = stop_packet.GetChar();
1436 switch (stop_type)
1437 {
1438 case 'T':
1439 case 'S':
1440 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001441 if (GetStopID() == 0)
1442 {
1443 // Our first stop, make sure we have a process ID, and also make
1444 // sure we know about our registers
1445 if (GetID() == LLDB_INVALID_PROCESS_ID)
1446 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001447 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001448 if (pid != LLDB_INVALID_PROCESS_ID)
1449 SetID (pid);
1450 }
1451 BuildDynamicRegisterInfo (true);
1452 }
Chris Lattner24943d22010-06-08 16:52:24 +00001453 // Stop with signal and thread info
1454 const uint8_t signo = stop_packet.GetHexU8();
1455 std::string name;
1456 std::string value;
1457 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001458 std::string reason;
1459 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001460 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001461 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001462 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001463 ThreadSP thread_sp;
1464
Chris Lattner24943d22010-06-08 16:52:24 +00001465 while (stop_packet.GetNameColonValue(name, value))
1466 {
1467 if (name.compare("metype") == 0)
1468 {
1469 // exception type in big endian hex
1470 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1471 }
Chris Lattner24943d22010-06-08 16:52:24 +00001472 else if (name.compare("medata") == 0)
1473 {
1474 // exception data in big endian hex
1475 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1476 }
1477 else if (name.compare("thread") == 0)
1478 {
1479 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001480 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001481 // m_thread_list does have its own mutex, but we need to
1482 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1483 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001484 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001485 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001486 if (!thread_sp)
1487 {
1488 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001489 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001490 m_thread_list.AddThread(thread_sp);
1491 }
Chris Lattner24943d22010-06-08 16:52:24 +00001492 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001493 else if (name.compare("threads") == 0)
1494 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001495 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001496 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001497 // A comma separated list of all threads in the current
1498 // process that includes the thread for this stop reply
1499 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001500 size_t comma_pos;
1501 lldb::tid_t tid;
1502 while ((comma_pos = value.find(',')) != std::string::npos)
1503 {
1504 value[comma_pos] = '\0';
1505 // thread in big endian hex
1506 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1507 if (tid != LLDB_INVALID_THREAD_ID)
1508 m_thread_ids.push_back (tid);
1509 value.erase(0, comma_pos + 1);
1510
1511 }
1512 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1513 if (tid != LLDB_INVALID_THREAD_ID)
1514 m_thread_ids.push_back (tid);
1515 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001516 else if (name.compare("hexname") == 0)
1517 {
1518 StringExtractor name_extractor;
1519 // Swap "value" over into "name_extractor"
1520 name_extractor.GetStringRef().swap(value);
1521 // Now convert the HEX bytes into a string value
1522 name_extractor.GetHexByteString (value);
1523 thread_name.swap (value);
1524 }
Chris Lattner24943d22010-06-08 16:52:24 +00001525 else if (name.compare("name") == 0)
1526 {
1527 thread_name.swap (value);
1528 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001529 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001530 {
1531 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1532 }
Greg Clayton65611552011-06-04 01:26:29 +00001533 else if (name.compare("reason") == 0)
1534 {
1535 reason.swap(value);
1536 }
1537 else if (name.compare("description") == 0)
1538 {
1539 StringExtractor desc_extractor;
1540 // Swap "value" over into "name_extractor"
1541 desc_extractor.GetStringRef().swap(value);
1542 // Now convert the HEX bytes into a string value
1543 desc_extractor.GetHexByteString (thread_name);
1544 }
Greg Claytona875b642011-01-09 21:07:35 +00001545 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1546 {
1547 // We have a register number that contains an expedited
1548 // register value. Lets supply this register to our thread
1549 // so it won't have to go and read it.
1550 if (thread_sp)
1551 {
1552 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1553
1554 if (reg != UINT32_MAX)
1555 {
1556 StringExtractor reg_value_extractor;
1557 // Swap "value" over into "reg_value_extractor"
1558 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001559 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1560 {
1561 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1562 name.c_str(),
1563 reg,
1564 reg,
1565 reg_value_extractor.GetStringRef().c_str(),
1566 stop_packet.GetStringRef().c_str());
1567 }
Greg Claytona875b642011-01-09 21:07:35 +00001568 }
1569 }
1570 }
Chris Lattner24943d22010-06-08 16:52:24 +00001571 }
Chris Lattner24943d22010-06-08 16:52:24 +00001572
1573 if (thread_sp)
1574 {
1575 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1576
1577 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001578 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001579 if (exc_type != 0)
1580 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001581 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001582
1583 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1584 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001585 exc_data_size,
1586 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001587 exc_data_size >= 2 ? exc_data[1] : 0,
1588 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001589 }
Greg Clayton65611552011-06-04 01:26:29 +00001590 else
Chris Lattner24943d22010-06-08 16:52:24 +00001591 {
Greg Clayton65611552011-06-04 01:26:29 +00001592 bool handled = false;
1593 if (!reason.empty())
1594 {
1595 if (reason.compare("trace") == 0)
1596 {
1597 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1598 handled = true;
1599 }
1600 else if (reason.compare("breakpoint") == 0)
1601 {
1602 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001603 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001604 if (bp_site_sp)
1605 {
1606 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1607 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1608 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001609 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001610 if (bp_site_sp->ValidForThisThread (gdb_thread))
1611 {
1612 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001613 }
1614 else
1615 {
1616 StopInfoSP invalid_stop_info_sp;
1617 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001618 }
1619 }
1620
Greg Clayton65611552011-06-04 01:26:29 +00001621 }
1622 else if (reason.compare("trap") == 0)
1623 {
1624 // Let the trap just use the standard signal stop reason below...
1625 }
1626 else if (reason.compare("watchpoint") == 0)
1627 {
1628 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1629 // TODO: locate the watchpoint somehow...
1630 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1631 handled = true;
1632 }
1633 else if (reason.compare("exception") == 0)
1634 {
1635 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1636 handled = true;
1637 }
1638 }
1639
1640 if (signo)
1641 {
1642 if (signo == SIGTRAP)
1643 {
1644 // Currently we are going to assume SIGTRAP means we are either
1645 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001646 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001647 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001648 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001649
Greg Clayton65611552011-06-04 01:26:29 +00001650 if (bp_site_sp)
1651 {
1652 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1653 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1654 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1655 if (bp_site_sp->ValidForThisThread (gdb_thread))
1656 {
1657 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001658 }
1659 else
1660 {
1661 StopInfoSP invalid_stop_info_sp;
1662 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001663 }
1664 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001665 else
Greg Clayton65611552011-06-04 01:26:29 +00001666 {
1667 // TODO: check for breakpoint or trap opcode in case there is a hard
1668 // coded software trap
1669 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton65611552011-06-04 01:26:29 +00001670 }
1671 }
1672 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001673 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001674 }
1675 else
1676 {
Greg Clayton643ee732010-08-04 01:40:35 +00001677 StopInfoSP invalid_stop_info_sp;
1678 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001679 }
Greg Clayton65611552011-06-04 01:26:29 +00001680
1681 if (!description.empty())
1682 {
1683 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1684 if (stop_info_sp)
1685 {
1686 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001687 }
Greg Clayton65611552011-06-04 01:26:29 +00001688 else
1689 {
1690 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1691 }
1692 }
1693 }
Chris Lattner24943d22010-06-08 16:52:24 +00001694 }
1695 return eStateStopped;
1696 }
1697 break;
1698
1699 case 'W':
1700 // process exited
1701 return eStateExited;
1702
1703 default:
1704 break;
1705 }
1706 return eStateInvalid;
1707}
1708
1709void
1710ProcessGDBRemote::RefreshStateAfterStop ()
1711{
Greg Claytonff3448e2012-04-13 02:11:32 +00001712 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001713 m_thread_ids.clear();
1714 // Set the thread stop info. It might have a "threads" key whose value is
1715 // a list of all thread IDs in the current process, so m_thread_ids might
1716 // get set.
1717 SetThreadStopInfo (m_last_stop_packet);
1718 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1719 if (m_thread_ids.empty())
1720 {
1721 // No, we need to fetch the thread list manually
1722 UpdateThreadIDList();
1723 }
1724
Chris Lattner24943d22010-06-08 16:52:24 +00001725 // Let all threads recover from stopping and do any clean up based
1726 // on the previous thread state (if any).
1727 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001728
Chris Lattner24943d22010-06-08 16:52:24 +00001729}
1730
1731Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001732ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001733{
1734 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001735
Greg Claytona4881d02011-01-22 07:12:45 +00001736 bool timed_out = false;
1737 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001738
1739 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001740 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001741 // We are being asked to halt during an attach. We need to just close
1742 // our file handle and debugserver will go away, and we can be done...
1743 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001744 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001745 else
1746 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001747 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001748 {
1749 if (timed_out)
1750 error.SetErrorString("timed out sending interrupt packet");
1751 else
1752 error.SetErrorString("unknown error sending interrupt packet");
1753 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001754
1755 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001756 }
Chris Lattner24943d22010-06-08 16:52:24 +00001757 return error;
1758}
1759
1760Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001761ProcessGDBRemote::InterruptIfRunning
1762(
1763 bool discard_thread_plans,
1764 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001765 EventSP &stop_event_sp
1766)
Chris Lattner24943d22010-06-08 16:52:24 +00001767{
1768 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001769
Greg Clayton2860ba92011-01-23 19:58:49 +00001770 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1771
Greg Clayton68ca8232011-01-25 02:58:48 +00001772 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001773 const bool is_running = m_gdb_comm.IsRunning();
1774 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001775 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001776 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001777 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001778 is_running);
1779
Greg Clayton2860ba92011-01-23 19:58:49 +00001780 if (discard_thread_plans)
1781 {
1782 if (log)
1783 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1784 m_thread_list.DiscardThreadPlans();
1785 }
1786 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001787 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001788 if (catch_stop_event)
1789 {
1790 if (log)
1791 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1792 PausePrivateStateThread();
1793 paused_private_state_thread = true;
1794 }
1795
Greg Clayton4fb400f2010-09-27 21:07:38 +00001796 bool timed_out = false;
1797 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001798
Greg Clayton05e4d972012-03-29 01:55:41 +00001799 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001800 {
1801 if (timed_out)
1802 error.SetErrorString("timed out sending interrupt packet");
1803 else
1804 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001805 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001806 ResumePrivateStateThread();
1807 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001808 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001809
Greg Clayton72e1c782011-01-22 23:43:18 +00001810 if (catch_stop_event)
1811 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001812 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001813 TimeValue timeout_time;
1814 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001815 timeout_time.OffsetWithSeconds(5);
1816 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001817
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001818 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001819 if (log)
1820 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001821
Greg Clayton2860ba92011-01-23 19:58:49 +00001822 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001823 error.SetErrorString("unable to verify target stopped");
1824 }
1825
Greg Clayton68ca8232011-01-25 02:58:48 +00001826 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001827 {
1828 if (log)
1829 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001830 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001831 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001832 }
Chris Lattner24943d22010-06-08 16:52:24 +00001833 return error;
1834}
1835
Greg Clayton4fb400f2010-09-27 21:07:38 +00001836Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001837ProcessGDBRemote::WillDetach ()
1838{
Greg Clayton2860ba92011-01-23 19:58:49 +00001839 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1840 if (log)
1841 log->Printf ("ProcessGDBRemote::WillDetach()");
1842
Greg Clayton72e1c782011-01-22 23:43:18 +00001843 bool discard_thread_plans = true;
1844 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001845 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001846
1847 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1848 // needed. This shouldn't be a feature of a particular plugin.
1849
Greg Clayton68ca8232011-01-25 02:58:48 +00001850 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001851}
1852
1853Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001854ProcessGDBRemote::DoDetach()
1855{
1856 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001857 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001858 if (log)
1859 log->Printf ("ProcessGDBRemote::DoDetach()");
1860
1861 DisableAllBreakpointSites ();
1862
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001863 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001864
Greg Clayton516f0842012-04-11 00:24:49 +00001865 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001866 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001867 {
Greg Clayton516f0842012-04-11 00:24:49 +00001868 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001869 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1870 else
1871 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001872 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001873 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001874 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001875
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001876 SetPrivateState (eStateDetached);
1877 ResumePrivateStateThread();
1878
1879 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001880 return error;
1881}
Chris Lattner24943d22010-06-08 16:52:24 +00001882
Jim Ingham06b84492012-07-04 00:35:43 +00001883
Chris Lattner24943d22010-06-08 16:52:24 +00001884Error
1885ProcessGDBRemote::DoDestroy ()
1886{
1887 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001888 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001889 if (log)
1890 log->Printf ("ProcessGDBRemote::DoDestroy()");
1891
Jim Ingham06b84492012-07-04 00:35:43 +00001892 // There is a bug in older iOS debugservers where they don't shut down the process
1893 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1894 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1895 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1896 // destroy it again.
1897 //
1898 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1899 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1900 // the debugservers with this bug are equal. There really should be a better way to test this!
1901 //
1902 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1903 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1904 // just do the straight-forward kill.
1905 //
1906 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1907 // necessary (or helpful) to do any of this.
1908
1909 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1910 {
1911 PlatformSP platform_sp = GetTarget().GetPlatform();
1912
1913 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1914 if (platform_sp
1915 && platform_sp->GetName()
1916 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1917 {
1918 if (m_destroy_tried_resuming)
1919 {
1920 if (log)
1921 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1922 }
1923 else
1924 {
1925 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1926 // but we really need it to happen here and it doesn't matter if we do it twice.
1927 m_thread_list.DiscardThreadPlans();
1928 DisableAllBreakpointSites();
1929
1930 bool stop_looks_like_crash = false;
1931 ThreadList &threads = GetThreadList();
1932
1933 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001934 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001935
1936 size_t num_threads = threads.GetSize();
1937 for (size_t i = 0; i < num_threads; i++)
1938 {
1939 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1940 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1941 StopReason reason = eStopReasonInvalid;
1942 if (stop_info_sp)
1943 reason = stop_info_sp->GetStopReason();
1944 if (reason == eStopReasonBreakpoint
1945 || reason == eStopReasonException)
1946 {
1947 if (log)
1948 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1949 thread_sp->GetID(),
1950 stop_info_sp->GetDescription());
1951 stop_looks_like_crash = true;
1952 break;
1953 }
1954 }
1955 }
1956
1957 if (stop_looks_like_crash)
1958 {
1959 if (log)
1960 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1961 m_destroy_tried_resuming = true;
1962
1963 // If we are going to run again before killing, it would be good to suspend all the threads
1964 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1965 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1966 // have to run the risk of letting those threads proceed a bit.
1967
1968 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001969 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001970
1971 size_t num_threads = threads.GetSize();
1972 for (size_t i = 0; i < num_threads; i++)
1973 {
1974 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1975 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1976 StopReason reason = eStopReasonInvalid;
1977 if (stop_info_sp)
1978 reason = stop_info_sp->GetStopReason();
1979 if (reason != eStopReasonBreakpoint
1980 && reason != eStopReasonException)
1981 {
1982 if (log)
1983 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1984 thread_sp->GetID());
1985 thread_sp->SetResumeState(eStateSuspended);
1986 }
1987 }
1988 }
1989 Resume ();
1990 return Destroy();
1991 }
1992 }
1993 }
1994 }
1995
Chris Lattner24943d22010-06-08 16:52:24 +00001996 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001997 int exit_status = SIGABRT;
1998 std::string exit_string;
1999
Greg Claytona4881d02011-01-22 07:12:45 +00002000 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00002001 {
Jim Ingham8226e942011-10-28 01:11:35 +00002002 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00002003 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002004
2005 StringExtractorGDBRemote response;
2006 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00002007 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2008
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002009 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002010 {
2011 char packet_cmd = response.GetChar(0);
2012
2013 if (packet_cmd == 'W' || packet_cmd == 'X')
2014 {
Greg Clayton06709002011-12-06 04:51:14 +00002015 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002016 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00002017 exit_status = response.GetHexU8();
2018 }
2019 else
2020 {
2021 if (log)
2022 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2023 exit_string.assign("got unexpected response to k packet: ");
2024 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002025 }
2026 }
2027 else
2028 {
Jim Ingham8247e622012-06-06 00:32:39 +00002029 if (log)
2030 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2031 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002032 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00002033
2034 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00002035 }
Jim Ingham8247e622012-06-06 00:32:39 +00002036 else
2037 {
2038 if (log)
2039 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00002040 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00002041 }
Greg Clayton72e1c782011-01-22 23:43:18 +00002042 }
Jim Ingham8247e622012-06-06 00:32:39 +00002043 else
2044 {
2045 // If we missed setting the exit status on the way out, do it here.
2046 // NB set exit status can be called multiple times, the first one sets the status.
2047 exit_string.assign("destroying when not connected to debugserver");
2048 }
2049
2050 SetExitStatus(exit_status, exit_string.c_str());
2051
Chris Lattner24943d22010-06-08 16:52:24 +00002052 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002053 KillDebugserverProcess ();
2054 return error;
2055}
2056
Chris Lattner24943d22010-06-08 16:52:24 +00002057//------------------------------------------------------------------
2058// Process Queries
2059//------------------------------------------------------------------
2060
2061bool
2062ProcessGDBRemote::IsAlive ()
2063{
Greg Clayton58e844b2010-12-08 05:08:21 +00002064 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00002065}
2066
2067addr_t
2068ProcessGDBRemote::GetImageInfoAddress()
2069{
Greg Clayton516f0842012-04-11 00:24:49 +00002070 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00002071}
2072
Chris Lattner24943d22010-06-08 16:52:24 +00002073//------------------------------------------------------------------
2074// Process Memory
2075//------------------------------------------------------------------
2076size_t
2077ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2078{
2079 if (size > m_max_memory_size)
2080 {
2081 // Keep memory read sizes down to a sane limit. This function will be
2082 // called multiple times in order to complete the task by
2083 // lldb_private::Process so it is ok to do this.
2084 size = m_max_memory_size;
2085 }
2086
2087 char packet[64];
Greg Clayton851e30e2012-09-18 18:04:04 +00002088 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%llx", (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00002089 assert (packet_len + 1 < sizeof(packet));
2090 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002091 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002092 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002093 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002094 {
2095 error.Clear();
2096 return response.GetHexBytes(buf, size, '\xdd');
2097 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002098 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002099 error.SetErrorString("memory read failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002100 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002101 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002102 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002103 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002104 }
2105 else
2106 {
2107 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
2108 }
2109 return 0;
2110}
2111
2112size_t
2113ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2114{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002115 if (size > m_max_memory_size)
2116 {
2117 // Keep memory read sizes down to a sane limit. This function will be
2118 // called multiple times in order to complete the task by
2119 // lldb_private::Process so it is ok to do this.
2120 size = m_max_memory_size;
2121 }
2122
Chris Lattner24943d22010-06-08 16:52:24 +00002123 StreamString packet;
Greg Clayton851e30e2012-09-18 18:04:04 +00002124 packet.Printf("M%llx,%llx:", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00002125 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00002126 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002127 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002128 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002129 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002130 {
2131 error.Clear();
2132 return size;
2133 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002134 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002135 error.SetErrorString("memory write failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002136 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002137 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002138 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002139 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002140 }
2141 else
2142 {
2143 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
2144 }
2145 return 0;
2146}
2147
2148lldb::addr_t
2149ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2150{
Greg Clayton989816b2011-05-14 01:50:35 +00002151 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2152
Greg Clayton2f085c62011-05-15 01:25:55 +00002153 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00002154 switch (supported)
2155 {
2156 case eLazyBoolCalculate:
2157 case eLazyBoolYes:
2158 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2159 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2160 return allocated_addr;
2161
2162 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002163 // Call mmap() to create memory in the inferior..
2164 unsigned prot = 0;
2165 if (permissions & lldb::ePermissionsReadable)
2166 prot |= eMmapProtRead;
2167 if (permissions & lldb::ePermissionsWritable)
2168 prot |= eMmapProtWrite;
2169 if (permissions & lldb::ePermissionsExecutable)
2170 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00002171
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002172 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2173 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2174 m_addr_to_mmap_size[allocated_addr] = size;
2175 else
2176 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002177 break;
2178 }
2179
Chris Lattner24943d22010-06-08 16:52:24 +00002180 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton851e30e2012-09-18 18:04:04 +00002181 error.SetErrorStringWithFormat("unable to allocate %llu bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002182 else
2183 error.Clear();
2184 return allocated_addr;
2185}
2186
2187Error
Greg Claytona9385532011-11-18 07:03:08 +00002188ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2189 MemoryRegionInfo &region_info)
2190{
2191
2192 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2193 return error;
2194}
2195
2196Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002197ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2198{
2199
2200 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2201 return error;
2202}
2203
2204Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002205ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2206{
2207 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2208 return error;
2209}
2210
2211Error
Chris Lattner24943d22010-06-08 16:52:24 +00002212ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2213{
2214 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002215 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2216
2217 switch (supported)
2218 {
2219 case eLazyBoolCalculate:
2220 // We should never be deallocating memory without allocating memory
2221 // first so we should never get eLazyBoolCalculate
2222 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2223 break;
2224
2225 case eLazyBoolYes:
2226 if (!m_gdb_comm.DeallocateMemory (addr))
2227 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2228 break;
2229
2230 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002231 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002232 {
2233 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002234 if (pos != m_addr_to_mmap_size.end() &&
2235 InferiorCallMunmap(this, addr, pos->second))
2236 m_addr_to_mmap_size.erase (pos);
2237 else
2238 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002239 }
2240 break;
2241 }
2242
Chris Lattner24943d22010-06-08 16:52:24 +00002243 return error;
2244}
2245
2246
2247//------------------------------------------------------------------
2248// Process STDIO
2249//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002250size_t
2251ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2252{
2253 if (m_stdio_communication.IsConnected())
2254 {
2255 ConnectionStatus status;
2256 m_stdio_communication.Write(src, src_len, status, NULL);
2257 }
2258 return 0;
2259}
2260
2261Error
2262ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2263{
2264 Error error;
2265 assert (bp_site != NULL);
2266
Greg Claytone005f2c2010-11-06 01:53:30 +00002267 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002268 user_id_t site_id = bp_site->GetID();
2269 const addr_t addr = bp_site->GetLoadAddress();
2270 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002271 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002272
2273 if (bp_site->IsEnabled())
2274 {
2275 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002276 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002277 return error;
2278 }
2279 else
2280 {
2281 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2282
2283 if (bp_site->HardwarePreferred())
2284 {
2285 // Try and set hardware breakpoint, and if that fails, fall through
2286 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002287 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002288 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002289 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002290 {
2291 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002292 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002293 return error;
2294 }
Chris Lattner24943d22010-06-08 16:52:24 +00002295 }
2296 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002297
2298 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002299 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002300 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2301 {
2302 bp_site->SetEnabled(true);
2303 bp_site->SetType (BreakpointSite::eExternal);
2304 return error;
2305 }
Chris Lattner24943d22010-06-08 16:52:24 +00002306 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002307
2308 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002309 }
2310
2311 if (log)
2312 {
2313 const char *err_string = error.AsCString();
2314 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2315 bp_site->GetLoadAddress(),
2316 err_string ? err_string : "NULL");
2317 }
2318 // We shouldn't reach here on a successful breakpoint enable...
2319 if (error.Success())
2320 error.SetErrorToGenericError();
2321 return error;
2322}
2323
2324Error
2325ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2326{
2327 Error error;
2328 assert (bp_site != NULL);
2329 addr_t addr = bp_site->GetLoadAddress();
2330 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002331 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002332 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002333 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002334
2335 if (bp_site->IsEnabled())
2336 {
2337 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2338
Greg Claytonb72d0f02011-04-12 05:54:46 +00002339 BreakpointSite::Type bp_type = bp_site->GetType();
2340 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002341 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002342 case BreakpointSite::eSoftware:
2343 error = DisableSoftwareBreakpoint (bp_site);
2344 break;
2345
2346 case BreakpointSite::eHardware:
2347 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2348 error.SetErrorToGenericError();
2349 break;
2350
2351 case BreakpointSite::eExternal:
2352 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2353 error.SetErrorToGenericError();
2354 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002355 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002356 if (error.Success())
2357 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002358 }
2359 else
2360 {
2361 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002362 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002363 return error;
2364 }
2365
2366 if (error.Success())
2367 error.SetErrorToGenericError();
2368 return error;
2369}
2370
Johnny Chen21900fb2011-09-06 22:38:36 +00002371// Pre-requisite: wp != NULL.
2372static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002373GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002374{
2375 assert(wp);
2376 bool watch_read = wp->WatchpointRead();
2377 bool watch_write = wp->WatchpointWrite();
2378
2379 // watch_read and watch_write cannot both be false.
2380 assert(watch_read || watch_write);
2381 if (watch_read && watch_write)
2382 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002383 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002384 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002385 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002386 return eWatchpointWrite;
2387}
2388
Chris Lattner24943d22010-06-08 16:52:24 +00002389Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002390ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002391{
2392 Error error;
2393 if (wp)
2394 {
2395 user_id_t watchID = wp->GetID();
2396 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002397 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002398 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002399 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002400 if (wp->IsEnabled())
2401 {
2402 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002403 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002404 return error;
2405 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002406
2407 GDBStoppointType type = GetGDBStoppointType(wp);
2408 // Pass down an appropriate z/Z packet...
2409 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002410 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002411 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2412 {
2413 wp->SetEnabled(true);
2414 return error;
2415 }
2416 else
2417 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002418 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002419 else
2420 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002421 }
2422 else
2423 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002424 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002425 }
2426 if (error.Success())
2427 error.SetErrorToGenericError();
2428 return error;
2429}
2430
2431Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002432ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002433{
2434 Error error;
2435 if (wp)
2436 {
2437 user_id_t watchID = wp->GetID();
2438
Greg Claytone005f2c2010-11-06 01:53:30 +00002439 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002440
2441 addr_t addr = wp->GetLoadAddress();
2442 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002443 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002444
Johnny Chen21900fb2011-09-06 22:38:36 +00002445 if (!wp->IsEnabled())
2446 {
2447 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002448 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002449 // See also 'class WatchpointSentry' within StopInfo.cpp.
2450 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2451 // the watchpoint object to intelligently process this action.
2452 wp->SetEnabled(false);
Johnny Chen21900fb2011-09-06 22:38:36 +00002453 return error;
2454 }
2455
Chris Lattner24943d22010-06-08 16:52:24 +00002456 if (wp->IsHardware())
2457 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002458 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002459 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002460 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2461 {
2462 wp->SetEnabled(false);
2463 return error;
2464 }
2465 else
2466 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002467 }
2468 // TODO: clear software watchpoints if we implement them
2469 }
2470 else
2471 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002472 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002473 }
2474 if (error.Success())
2475 error.SetErrorToGenericError();
2476 return error;
2477}
2478
2479void
2480ProcessGDBRemote::Clear()
2481{
2482 m_flags = 0;
2483 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002484}
2485
2486Error
2487ProcessGDBRemote::DoSignal (int signo)
2488{
2489 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002490 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002491 if (log)
2492 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2493
2494 if (!m_gdb_comm.SendAsyncSignal (signo))
2495 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2496 return error;
2497}
2498
Chris Lattner24943d22010-06-08 16:52:24 +00002499Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002500ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2501{
2502 ProcessLaunchInfo launch_info;
2503 return StartDebugserverProcess(debugserver_url, launch_info);
2504}
2505
2506Error
2507ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner24943d22010-06-08 16:52:24 +00002508{
2509 Error error;
2510 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2511 {
2512 // If we locate debugserver, keep that located version around
2513 static FileSpec g_debugserver_file_spec;
2514
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002515 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002516 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002517 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002518
2519 // Always check to see if we have an environment override for the path
2520 // to the debugserver to use and use it if we do.
2521 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2522 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002523 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002524 else
2525 debugserver_file_spec = g_debugserver_file_spec;
2526 bool debugserver_exists = debugserver_file_spec.Exists();
2527 if (!debugserver_exists)
2528 {
2529 // The debugserver binary is in the LLDB.framework/Resources
2530 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002531 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002532 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002533 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002534 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002535 if (debugserver_exists)
2536 {
2537 g_debugserver_file_spec = debugserver_file_spec;
2538 }
2539 else
2540 {
2541 g_debugserver_file_spec.Clear();
2542 debugserver_file_spec.Clear();
2543 }
Chris Lattner24943d22010-06-08 16:52:24 +00002544 }
2545 }
2546
2547 if (debugserver_exists)
2548 {
2549 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2550
2551 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002552
Greg Claytone005f2c2010-11-06 01:53:30 +00002553 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002554
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002555 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002556 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002557
Chris Lattner24943d22010-06-08 16:52:24 +00002558 // Start args with "debugserver /file/path -r --"
2559 debugserver_args.AppendArgument(debugserver_path);
2560 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002561 // use native registers, not the GDB registers
2562 debugserver_args.AppendArgument("--native-regs");
2563 // make debugserver run in its own session so signals generated by
2564 // special terminal key sequences (^C) don't affect debugserver
2565 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002566
Chris Lattner24943d22010-06-08 16:52:24 +00002567 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2568 if (env_debugserver_log_file)
2569 {
2570 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2571 debugserver_args.AppendArgument(arg_cstr);
2572 }
2573
2574 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2575 if (env_debugserver_log_flags)
2576 {
2577 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2578 debugserver_args.AppendArgument(arg_cstr);
2579 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00002580 debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2581 debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002582
Greg Claytonb72d0f02011-04-12 05:54:46 +00002583 // We currently send down all arguments, attach pids, or attach
2584 // process names in dedicated GDB server packets, so we don't need
2585 // to pass them as arguments. This is currently because of all the
2586 // things we need to setup prior to launching: the environment,
2587 // current working dir, file actions, etc.
2588#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002589 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002590 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002591 {
Greg Claytona2f74232011-02-24 22:24:29 +00002592 // Terminate the debugserver args so we can now append the inferior args
2593 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002594
Greg Claytona2f74232011-02-24 22:24:29 +00002595 for (int i = 0; inferior_argv[i] != NULL; ++i)
2596 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002597 }
2598 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2599 {
2600 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2601 debugserver_args.AppendArgument (arg_cstr);
2602 }
2603 else if (attach_name && attach_name[0])
2604 {
2605 if (wait_for_launch)
2606 debugserver_args.AppendArgument ("--waitfor");
2607 else
2608 debugserver_args.AppendArgument ("--attach");
2609 debugserver_args.AppendArgument (attach_name);
2610 }
Chris Lattner24943d22010-06-08 16:52:24 +00002611#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002612
2613 ProcessLaunchInfo::FileAction file_action;
2614
2615 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2616 // to "/dev/null" if we run into any problems.
2617 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002618 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002619 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002620 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002621 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002622 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002623
2624 if (log)
2625 {
2626 StreamString strm;
2627 debugserver_args.Dump (&strm);
2628 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2629 }
2630
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002631 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2632 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002633
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002634 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002635
Greg Claytonb72d0f02011-04-12 05:54:46 +00002636 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002637 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002638 else
Chris Lattner24943d22010-06-08 16:52:24 +00002639 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2640
2641 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002642 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002643 }
2644 else
2645 {
Greg Clayton9c236732011-10-26 00:56:27 +00002646 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002647 }
2648
2649 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2650 StartAsyncThread ();
2651 }
2652 return error;
2653}
2654
2655bool
2656ProcessGDBRemote::MonitorDebugserverProcess
2657(
2658 void *callback_baton,
2659 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002660 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002661 int signo, // Zero for no signal
2662 int exit_status // Exit value of process if signal is zero
2663)
2664{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002665 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2666 // and might not exist anymore, so we need to carefully try to get the
2667 // target for this process first since we have a race condition when
2668 // we are done running between getting the notice that the inferior
2669 // process has died and the debugserver that was debugging this process.
2670 // In our test suite, we are also continually running process after
2671 // process, so we must be very careful to make sure:
2672 // 1 - process object hasn't been deleted already
2673 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002674
2675 // "debugserver_pid" argument passed in is the process ID for
2676 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002677 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002678
Greg Clayton75ccf502010-08-21 02:22:51 +00002679 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002680
Greg Clayton1c4642c2011-11-16 05:37:56 +00002681 // Get a shared pointer to the target that has a matching process pointer.
2682 // This target could be gone, or the target could already have a new process
2683 // object inside of it
2684 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2685
Greg Clayton72e1c782011-01-22 23:43:18 +00002686 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002687 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%llu, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton72e1c782011-01-22 23:43:18 +00002688
Greg Clayton1c4642c2011-11-16 05:37:56 +00002689 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002690 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002691 // We found a process in a target that matches, but another thread
2692 // might be in the process of launching a new process that will
2693 // soon replace it, so get a shared pointer to the process so we
2694 // can keep it alive.
2695 ProcessSP process_sp (target_sp->GetProcessSP());
2696 // Now we have a shared pointer to the process that can't go away on us
2697 // so we now make sure it was the same as the one passed in, and also make
2698 // sure that our previous "process *" didn't get deleted and have a new
2699 // "process *" created in its place with the same pointer. To verify this
2700 // we make sure the process has our debugserver process ID. If we pass all
2701 // of these tests, then we are sure that this process is the one we were
2702 // looking for.
2703 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002704 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002705 // Sleep for a half a second to make sure our inferior process has
2706 // time to set its exit status before we set it incorrectly when
2707 // both the debugserver and the inferior process shut down.
2708 usleep (500000);
2709 // If our process hasn't yet exited, debugserver might have died.
2710 // If the process did exit, the we are reaping it.
2711 const StateType state = process->GetState();
2712
2713 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2714 state != eStateInvalid &&
2715 state != eStateUnloaded &&
2716 state != eStateExited &&
2717 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002718 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002719 char error_str[1024];
2720 if (signo)
2721 {
2722 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2723 if (signal_cstr)
2724 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2725 else
2726 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2727 }
Chris Lattner24943d22010-06-08 16:52:24 +00002728 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002729 {
2730 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2731 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002732
Greg Clayton1c4642c2011-11-16 05:37:56 +00002733 process->SetExitStatus (-1, error_str);
2734 }
2735 // Debugserver has exited we need to let our ProcessGDBRemote
2736 // know that it no longer has a debugserver instance
2737 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002738 }
Chris Lattner24943d22010-06-08 16:52:24 +00002739 }
2740 return true;
2741}
2742
2743void
2744ProcessGDBRemote::KillDebugserverProcess ()
2745{
2746 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2747 {
2748 ::kill (m_debugserver_pid, SIGINT);
2749 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2750 }
2751}
2752
2753void
2754ProcessGDBRemote::Initialize()
2755{
2756 static bool g_initialized = false;
2757
2758 if (g_initialized == false)
2759 {
2760 g_initialized = true;
2761 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2762 GetPluginDescriptionStatic(),
2763 CreateInstance);
2764
2765 Log::Callbacks log_callbacks = {
2766 ProcessGDBRemoteLog::DisableLog,
2767 ProcessGDBRemoteLog::EnableLog,
2768 ProcessGDBRemoteLog::ListLogCategories
2769 };
2770
2771 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2772 }
2773}
2774
2775bool
Chris Lattner24943d22010-06-08 16:52:24 +00002776ProcessGDBRemote::StartAsyncThread ()
2777{
Greg Claytone005f2c2010-11-06 01:53:30 +00002778 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002779
2780 if (log)
2781 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2782
2783 // Create a thread that watches our internal state and controls which
2784 // events make it to clients (into the DCProcess event queue).
2785 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002786 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002787}
2788
2789void
2790ProcessGDBRemote::StopAsyncThread ()
2791{
Greg Claytone005f2c2010-11-06 01:53:30 +00002792 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002793
2794 if (log)
2795 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2796
2797 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002798
2799 // This will shut down the async thread.
2800 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002801
2802 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002803 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002804 {
2805 Host::ThreadJoin (m_async_thread, NULL, NULL);
2806 }
2807}
2808
2809
2810void *
2811ProcessGDBRemote::AsyncThread (void *arg)
2812{
2813 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2814
Greg Claytone005f2c2010-11-06 01:53:30 +00002815 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002816 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002817 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002818
2819 Listener listener ("ProcessGDBRemote::AsyncThread");
2820 EventSP event_sp;
2821 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2822 eBroadcastBitAsyncThreadShouldExit;
2823
2824 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2825 {
Greg Claytona2f74232011-02-24 22:24:29 +00002826 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2827
Chris Lattner24943d22010-06-08 16:52:24 +00002828 bool done = false;
2829 while (!done)
2830 {
2831 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002832 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002833 if (listener.WaitForEvent (NULL, event_sp))
2834 {
2835 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002836 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002837 {
Greg Claytona2f74232011-02-24 22:24:29 +00002838 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002839 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002840
Greg Claytona2f74232011-02-24 22:24:29 +00002841 switch (event_type)
2842 {
2843 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002844 {
Greg Claytona2f74232011-02-24 22:24:29 +00002845 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002846
Greg Claytona2f74232011-02-24 22:24:29 +00002847 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002848 {
Greg Claytona2f74232011-02-24 22:24:29 +00002849 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2850 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2851 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002852 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002853
Greg Claytona2f74232011-02-24 22:24:29 +00002854 if (::strstr (continue_cstr, "vAttach") == NULL)
2855 process->SetPrivateState(eStateRunning);
2856 StringExtractorGDBRemote response;
2857 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002858
Greg Clayton67b402c2012-05-16 02:48:06 +00002859 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2860 // The thread ID list might be contained within the "response", or the stop reply packet that
2861 // caused the stop. So clear it now before we give the stop reply packet to the process
2862 // using the process->SetLastStopPacket()...
2863 process->ClearThreadIDList ();
2864
Greg Claytona2f74232011-02-24 22:24:29 +00002865 switch (stop_state)
2866 {
2867 case eStateStopped:
2868 case eStateCrashed:
2869 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002870 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002871 process->SetPrivateState (stop_state);
2872 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002873
Greg Claytona2f74232011-02-24 22:24:29 +00002874 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002875 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002876 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002877 response.SetFilePos(1);
2878 process->SetExitStatus(response.GetHexU8(), NULL);
2879 done = true;
2880 break;
2881
2882 case eStateInvalid:
2883 process->SetExitStatus(-1, "lost connection");
2884 break;
2885
2886 default:
2887 process->SetPrivateState (stop_state);
2888 break;
2889 }
Chris Lattner24943d22010-06-08 16:52:24 +00002890 }
2891 }
Greg Claytona2f74232011-02-24 22:24:29 +00002892 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002893
Greg Claytona2f74232011-02-24 22:24:29 +00002894 case eBroadcastBitAsyncThreadShouldExit:
2895 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002896 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002897 done = true;
2898 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002899
Greg Claytona2f74232011-02-24 22:24:29 +00002900 default:
2901 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002902 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Claytona2f74232011-02-24 22:24:29 +00002903 done = true;
2904 break;
2905 }
2906 }
2907 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2908 {
2909 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2910 {
2911 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002912 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002913 }
Chris Lattner24943d22010-06-08 16:52:24 +00002914 }
2915 }
2916 else
2917 {
2918 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002919 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002920 done = true;
2921 }
2922 }
2923 }
2924
2925 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002926 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002927
2928 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2929 return NULL;
2930}
2931
Chris Lattner24943d22010-06-08 16:52:24 +00002932const char *
2933ProcessGDBRemote::GetDispatchQueueNameForThread
2934(
2935 addr_t thread_dispatch_qaddr,
2936 std::string &dispatch_queue_name
2937)
2938{
2939 dispatch_queue_name.clear();
2940 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2941 {
2942 // Cache the dispatch_queue_offsets_addr value so we don't always have
2943 // to look it up
2944 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2945 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002946 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2947 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002948 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2949 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002950 if (module_sp)
2951 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2952
2953 if (dispatch_queue_offsets_symbol == NULL)
2954 {
Greg Clayton444fe992012-02-26 05:51:37 +00002955 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2956 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002957 if (module_sp)
2958 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2959 }
Chris Lattner24943d22010-06-08 16:52:24 +00002960 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002961 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002962
2963 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2964 return NULL;
2965 }
2966
2967 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002968 DataExtractor data (memory_buffer,
2969 sizeof(memory_buffer),
2970 m_target.GetArchitecture().GetByteOrder(),
2971 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002972
2973 // Excerpt from src/queue_private.h
2974 struct dispatch_queue_offsets_s
2975 {
2976 uint16_t dqo_version;
2977 uint16_t dqo_label;
2978 uint16_t dqo_label_size;
2979 } dispatch_queue_offsets;
2980
2981
2982 Error error;
2983 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2984 {
2985 uint32_t data_offset = 0;
2986 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2987 {
2988 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2989 {
2990 data_offset = 0;
2991 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2992 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2993 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2994 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2995 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2996 dispatch_queue_name.erase (bytes_read);
2997 }
2998 }
2999 }
3000 }
3001 if (dispatch_queue_name.empty())
3002 return NULL;
3003 return dispatch_queue_name.c_str();
3004}
3005
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003006//uint32_t
3007//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3008//{
3009// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3010// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3011// if (m_local_debugserver)
3012// {
3013// return Host::ListProcessesMatchingName (name, matches, pids);
3014// }
3015// else
3016// {
3017// // FIXME: Implement talking to the remote debugserver.
3018// return 0;
3019// }
3020//
3021//}
3022//
Jim Ingham55e01d82011-01-22 01:33:44 +00003023bool
3024ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3025 lldb_private::StoppointCallbackContext *context,
3026 lldb::user_id_t break_id,
3027 lldb::user_id_t break_loc_id)
3028{
3029 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3030 // run so I can stop it if that's what I want to do.
3031 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3032 if (log)
3033 log->Printf("Hit New Thread Notification breakpoint.");
3034 return false;
3035}
3036
3037
3038bool
3039ProcessGDBRemote::StartNoticingNewThreads()
3040{
Jim Ingham55e01d82011-01-22 01:33:44 +00003041 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003042 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003043 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003044 if (log && log->GetVerbose())
3045 log->Printf("Enabled noticing new thread breakpoint.");
3046 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003047 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003048 else
Jim Ingham55e01d82011-01-22 01:33:44 +00003049 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003050 PlatformSP platform_sp (m_target.GetPlatform());
3051 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003052 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003053 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3054 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003055 {
Jim Ingham6bb73372011-10-15 00:21:37 +00003056 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003057 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3058 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003059 }
3060 else
3061 {
3062 if (log)
3063 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00003064 }
3065 }
3066 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003067 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00003068}
3069
3070bool
3071ProcessGDBRemote::StopNoticingNewThreads()
3072{
Jim Inghamff276fe2011-02-08 05:19:01 +00003073 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00003074 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00003075 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003076
3077 if (m_thread_create_bp_sp)
3078 m_thread_create_bp_sp->SetEnabled(false);
3079
Jim Ingham55e01d82011-01-22 01:33:44 +00003080 return true;
3081}
3082
3083