blob: 4dba00bb43ff87a7b56dc380bde11bc8f5688454 [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>
Greg Clayton989816b2011-05-14 01:50:35 +000014#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000016#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000017#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000018
19// C++ Includes
20#include <algorithm>
21#include <map>
22
23// Other libraries and framework includes
24
Johnny Chenecd4feb2011-10-14 00:42:25 +000025#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000026#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Core/ArchSpec.h"
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000030#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Core/InputReader.h"
32#include "lldb/Core/Module.h"
33#include "lldb/Core/PluginManager.h"
34#include "lldb/Core/State.h"
35#include "lldb/Core/StreamString.h"
36#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000037#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Host/TimeValue.h"
39#include "lldb/Symbol/ObjectFile.h"
40#include "lldb/Target/DynamicLoader.h"
41#include "lldb/Target/Target.h"
42#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000043#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000044#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045
46// Project includes
47#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000048#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000049#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000050#include "GDBRemoteRegisterContext.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000054#include "StopInfoMachException.h"
55
Greg Clayton451fa822012-04-09 22:46:21 +000056namespace lldb
57{
58 // Provide a function that can easily dump the packet history if we know a
59 // ProcessGDBRemote * value (which we can get from logs or from debugging).
60 // We need the function in the lldb namespace so it makes it into the final
61 // executable since the LLDB shared library only exports stuff in the lldb
62 // namespace. This allows you to attach with a debugger and call this
63 // function and get the packet history dumped to a file.
64 void
65 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
66 {
67 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (path);
68 }
69};
Chris Lattner24943d22010-06-08 16:52:24 +000070
Chris Lattner24943d22010-06-08 16:52:24 +000071
72#define DEBUGSERVER_BASENAME "debugserver"
73using namespace lldb;
74using namespace lldb_private;
75
Jim Inghamf9600482011-03-29 21:45:47 +000076static bool rand_initialized = false;
77
Chris Lattner24943d22010-06-08 16:52:24 +000078static inline uint16_t
79get_random_port ()
80{
Jim Inghamf9600482011-03-29 21:45:47 +000081 if (!rand_initialized)
82 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000083 time_t seed = time(NULL);
84
Jim Inghamf9600482011-03-29 21:45:47 +000085 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000086 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000087 }
Stephen Wilson50daf772011-03-25 18:16:28 +000088 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000089}
90
91
92const char *
93ProcessGDBRemote::GetPluginNameStatic()
94{
Greg Claytonb1888f22011-03-19 01:12:21 +000095 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000096}
97
98const char *
99ProcessGDBRemote::GetPluginDescriptionStatic()
100{
101 return "GDB Remote protocol based debugging plug-in.";
102}
103
104void
105ProcessGDBRemote::Terminate()
106{
107 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
108}
109
110
Greg Clayton46c9a352012-02-09 06:16:32 +0000111lldb::ProcessSP
112ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000113{
Greg Clayton46c9a352012-02-09 06:16:32 +0000114 lldb::ProcessSP process_sp;
115 if (crash_file_path == NULL)
116 process_sp.reset (new ProcessGDBRemote (target, listener));
117 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000118}
119
120bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000121ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000122{
Greg Clayton61ddf562011-10-21 21:41:45 +0000123 if (plugin_specified_by_name)
124 return true;
125
Chris Lattner24943d22010-06-08 16:52:24 +0000126 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000127 Module *exe_module = target.GetExecutableModulePointer();
128 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000129 {
130 ObjectFile *exe_objfile = exe_module->GetObjectFile();
131 // We can't debug core files...
132 switch (exe_objfile->GetType())
133 {
134 case ObjectFile::eTypeInvalid:
135 case ObjectFile::eTypeCoreFile:
136 case ObjectFile::eTypeDebugInfo:
137 case ObjectFile::eTypeObjectFile:
138 case ObjectFile::eTypeSharedLibrary:
139 case ObjectFile::eTypeStubLibrary:
140 return false;
141 case ObjectFile::eTypeExecutable:
142 case ObjectFile::eTypeDynamicLinker:
143 case ObjectFile::eTypeUnknown:
144 break;
145 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000146 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000147 }
Jim Ingham7508e732010-08-09 23:31:02 +0000148 // However, if there is no executable module, we return true since we might be preparing to attach.
149 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000150}
151
152//----------------------------------------------------------------------
153// ProcessGDBRemote constructor
154//----------------------------------------------------------------------
155ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
156 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000157 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000158 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000159 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000160 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000161 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000162 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000163 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000164 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000165 m_thread_ids (),
166 m_thread_ids_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonc1f45872011-02-12 06:28:37 +0000167 m_continue_c_tids (),
168 m_continue_C_tids (),
169 m_continue_s_tids (),
170 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000171 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000172 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000173 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000174 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000175{
Greg Claytonff39f742011-04-01 00:29:43 +0000176 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
177 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000178 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000179}
180
181//----------------------------------------------------------------------
182// Destructor
183//----------------------------------------------------------------------
184ProcessGDBRemote::~ProcessGDBRemote()
185{
186 // m_mach_process.UnregisterNotificationCallbacks (this);
187 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000188 // We need to call finalize on the process before destroying ourselves
189 // to make sure all of the broadcaster cleanup goes as planned. If we
190 // destruct this class, then Process::~Process() might have problems
191 // trying to fully destroy the broadcaster.
192 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000193}
194
195//----------------------------------------------------------------------
196// PluginInterface
197//----------------------------------------------------------------------
198const char *
199ProcessGDBRemote::GetPluginName()
200{
201 return "Process debugging plug-in that uses the GDB remote protocol";
202}
203
204const char *
205ProcessGDBRemote::GetShortPluginName()
206{
207 return GetPluginNameStatic();
208}
209
210uint32_t
211ProcessGDBRemote::GetPluginVersion()
212{
213 return 1;
214}
215
216void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000217ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000218{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000219 if (!force && m_register_info.GetNumRegisters() > 0)
220 return;
221
222 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000223 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000224 uint32_t reg_offset = 0;
225 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000226 StringExtractorGDBRemote::ResponseType response_type;
227 for (response_type = StringExtractorGDBRemote::eResponse;
228 response_type == StringExtractorGDBRemote::eResponse;
229 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000230 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000231 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
232 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000233 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000234 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000235 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000236 response_type = response.GetResponseType();
237 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000238 {
239 std::string name;
240 std::string value;
241 ConstString reg_name;
242 ConstString alt_name;
243 ConstString set_name;
244 RegisterInfo reg_info = { NULL, // Name
245 NULL, // Alt name
246 0, // byte size
247 reg_offset, // offset
248 eEncodingUint, // encoding
249 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000250 {
251 LLDB_INVALID_REGNUM, // GCC reg num
252 LLDB_INVALID_REGNUM, // DWARF reg num
253 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000254 reg_num, // GDB reg num
255 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000256 },
257 NULL,
258 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000259 };
260
261 while (response.GetNameColonValue(name, value))
262 {
263 if (name.compare("name") == 0)
264 {
265 reg_name.SetCString(value.c_str());
266 }
267 else if (name.compare("alt-name") == 0)
268 {
269 alt_name.SetCString(value.c_str());
270 }
271 else if (name.compare("bitsize") == 0)
272 {
273 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
274 }
275 else if (name.compare("offset") == 0)
276 {
277 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000278 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000279 {
280 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000281 }
282 }
283 else if (name.compare("encoding") == 0)
284 {
285 if (value.compare("uint") == 0)
286 reg_info.encoding = eEncodingUint;
287 else if (value.compare("sint") == 0)
288 reg_info.encoding = eEncodingSint;
289 else if (value.compare("ieee754") == 0)
290 reg_info.encoding = eEncodingIEEE754;
291 else if (value.compare("vector") == 0)
292 reg_info.encoding = eEncodingVector;
293 }
294 else if (name.compare("format") == 0)
295 {
296 if (value.compare("binary") == 0)
297 reg_info.format = eFormatBinary;
298 else if (value.compare("decimal") == 0)
299 reg_info.format = eFormatDecimal;
300 else if (value.compare("hex") == 0)
301 reg_info.format = eFormatHex;
302 else if (value.compare("float") == 0)
303 reg_info.format = eFormatFloat;
304 else if (value.compare("vector-sint8") == 0)
305 reg_info.format = eFormatVectorOfSInt8;
306 else if (value.compare("vector-uint8") == 0)
307 reg_info.format = eFormatVectorOfUInt8;
308 else if (value.compare("vector-sint16") == 0)
309 reg_info.format = eFormatVectorOfSInt16;
310 else if (value.compare("vector-uint16") == 0)
311 reg_info.format = eFormatVectorOfUInt16;
312 else if (value.compare("vector-sint32") == 0)
313 reg_info.format = eFormatVectorOfSInt32;
314 else if (value.compare("vector-uint32") == 0)
315 reg_info.format = eFormatVectorOfUInt32;
316 else if (value.compare("vector-float32") == 0)
317 reg_info.format = eFormatVectorOfFloat32;
318 else if (value.compare("vector-uint128") == 0)
319 reg_info.format = eFormatVectorOfUInt128;
320 }
321 else if (name.compare("set") == 0)
322 {
323 set_name.SetCString(value.c_str());
324 }
325 else if (name.compare("gcc") == 0)
326 {
327 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
328 }
329 else if (name.compare("dwarf") == 0)
330 {
331 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
332 }
333 else if (name.compare("generic") == 0)
334 {
335 if (value.compare("pc") == 0)
336 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
337 else if (value.compare("sp") == 0)
338 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
339 else if (value.compare("fp") == 0)
340 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
341 else if (value.compare("ra") == 0)
342 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
343 else if (value.compare("flags") == 0)
344 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000345 else if (value.find("arg") == 0)
346 {
347 if (value.size() == 4)
348 {
349 switch (value[3])
350 {
351 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
352 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
353 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
354 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
355 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
356 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
357 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
358 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
359 }
360 }
361 }
Chris Lattner24943d22010-06-08 16:52:24 +0000362 }
363 }
364
Jason Molenda53d96862010-06-11 23:44:18 +0000365 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000366 assert (reg_info.byte_size != 0);
367 reg_offset += reg_info.byte_size;
368 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
369 }
370 }
371 else
372 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000373 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000374 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000375 }
376 }
377
378 if (reg_num == 0)
379 {
380 // We didn't get anything. See if we are debugging ARM and fill with
381 // a hard coded register set until we can get an updated debugserver
382 // down on the devices.
Jason Molenda428b5502011-10-06 01:45:46 +0000383
384 if (!GetTarget().GetArchitecture().IsValid()
385 && m_gdb_comm.GetHostArchitecture().IsValid()
386 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm
387 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
388 {
Chris Lattner24943d22010-06-08 16:52:24 +0000389 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000390 }
391 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
392 {
393 m_register_info.HardcodeARMRegisters();
394 }
Chris Lattner24943d22010-06-08 16:52:24 +0000395 }
396 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
Greg Claytone71e2582011-02-04 01:58:07 +0000418ProcessGDBRemote::DoConnectRemote (const char *remote_url)
419{
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
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000431 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000432 if (pid == LLDB_INVALID_PROCESS_ID)
433 {
434 // We don't have a valid process ID, so note that we are connected
435 // and could now request to launch or attach, or get remote process
436 // listings...
437 SetPrivateState (eStateConnected);
438 }
439 else
440 {
441 // We have a valid process
442 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000443 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000444 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000445 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000446 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000447 if (state == eStateStopped)
448 {
449 SetPrivateState (state);
450 }
451 else
Greg Claytond9919d32011-12-01 23:28:38 +0000452 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 +0000453 }
454 else
Greg Claytond9919d32011-12-01 23:28:38 +0000455 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 +0000456 }
457 return error;
458}
459
460Error
Chris Lattner24943d22010-06-08 16:52:24 +0000461ProcessGDBRemote::WillLaunchOrAttach ()
462{
463 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000464 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000465 return error;
466}
467
468//----------------------------------------------------------------------
469// Process Control
470//----------------------------------------------------------------------
471Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000472ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000473{
Greg Clayton4b407112010-09-30 21:49:03 +0000474 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000475
476 uint32_t launch_flags = launch_info.GetFlags().Get();
477 const char *stdin_path = NULL;
478 const char *stdout_path = NULL;
479 const char *stderr_path = NULL;
480 const char *working_dir = launch_info.GetWorkingDirectory();
481
482 const ProcessLaunchInfo::FileAction *file_action;
483 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
484 if (file_action)
485 {
486 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
487 stdin_path = file_action->GetPath();
488 }
489 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
490 if (file_action)
491 {
492 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
493 stdout_path = file_action->GetPath();
494 }
495 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
496 if (file_action)
497 {
498 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
499 stderr_path = file_action->GetPath();
500 }
501
Chris Lattner24943d22010-06-08 16:52:24 +0000502 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
503 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
504 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000505 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000506
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000507 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000508 if (object_file)
509 {
Chris Lattner24943d22010-06-08 16:52:24 +0000510 char host_port[128];
511 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000512 char connect_url[128];
513 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000514
Greg Claytona2f74232011-02-24 22:24:29 +0000515 // Make sure we aren't already connected?
516 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000517 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000518 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000519 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000520 {
Johnny Chenc143d622011-08-09 18:56:45 +0000521 if (log)
522 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000523 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000524 }
Chris Lattner24943d22010-06-08 16:52:24 +0000525
Greg Claytone71e2582011-02-04 01:58:07 +0000526 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000527 }
528
529 if (error.Success())
530 {
531 lldb_utility::PseudoTerminal pty;
532 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000533
534 // If the debugserver is local and we aren't disabling STDIO, lets use
535 // a pseudo terminal to instead of relying on the 'O' packets for stdio
536 // since 'O' packets can really slow down debugging if the inferior
537 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000538 PlatformSP platform_sp (m_target.GetPlatform());
539 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000540 {
541 const char *slave_name = NULL;
542 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000543 {
Greg Claytona2f74232011-02-24 22:24:29 +0000544 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
545 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000546 }
Greg Claytona2f74232011-02-24 22:24:29 +0000547 if (stdin_path == NULL)
548 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000549
Greg Claytona2f74232011-02-24 22:24:29 +0000550 if (stdout_path == NULL)
551 stdout_path = slave_name;
552
553 if (stderr_path == NULL)
554 stderr_path = slave_name;
555 }
556
Greg Claytonafb81862011-03-02 21:34:46 +0000557 // Set STDIN to /dev/null if we want STDIO disabled or if either
558 // STDOUT or STDERR have been set to something and STDIN hasn't
559 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000560 stdin_path = "/dev/null";
561
Greg Claytonafb81862011-03-02 21:34:46 +0000562 // Set STDOUT to /dev/null if we want STDIO disabled or if either
563 // STDIN or STDERR have been set to something and STDOUT hasn't
564 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000565 stdout_path = "/dev/null";
566
Greg Claytonafb81862011-03-02 21:34:46 +0000567 // Set STDERR to /dev/null if we want STDIO disabled or if either
568 // STDIN or STDOUT have been set to something and STDERR hasn't
569 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000570 stderr_path = "/dev/null";
571
572 if (stdin_path)
573 m_gdb_comm.SetSTDIN (stdin_path);
574 if (stdout_path)
575 m_gdb_comm.SetSTDOUT (stdout_path);
576 if (stderr_path)
577 m_gdb_comm.SetSTDERR (stderr_path);
578
579 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
580
Greg Claytona4582402011-05-08 04:53:50 +0000581 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000582
583 if (working_dir && working_dir[0])
584 {
585 m_gdb_comm.SetWorkingDir (working_dir);
586 }
587
588 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000589 const Args &environment = launch_info.GetEnvironmentEntries();
590 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000591 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000592 size_t num_environment_entries = environment.GetArgumentCount();
593 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000594 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000595 const char *env_entry = environment.GetArgumentAtIndex(i);
596 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000597 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000598 }
Greg Claytona2f74232011-02-24 22:24:29 +0000599 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000600
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000601 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000602 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000603 if (arg_packet_err == 0)
604 {
605 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000606 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000607 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000608 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000609 }
610 else
611 {
Greg Claytona2f74232011-02-24 22:24:29 +0000612 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000613 }
Greg Claytona2f74232011-02-24 22:24:29 +0000614 }
615 else
616 {
Greg Clayton9c236732011-10-26 00:56:27 +0000617 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000618 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000619
620 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000621
Greg Claytona2f74232011-02-24 22:24:29 +0000622 if (GetID() == LLDB_INVALID_PROCESS_ID)
623 {
Johnny Chenc143d622011-08-09 18:56:45 +0000624 if (log)
625 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000626 KillDebugserverProcess ();
627 return error;
628 }
629
Greg Clayton261a18b2011-06-02 22:22:38 +0000630 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000631 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000632 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000633
634 if (!disable_stdio)
635 {
636 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000637 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000638 }
Chris Lattner24943d22010-06-08 16:52:24 +0000639 }
640 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000641 else
642 {
Johnny Chenc143d622011-08-09 18:56:45 +0000643 if (log)
644 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000645 }
Chris Lattner24943d22010-06-08 16:52:24 +0000646 }
647 else
648 {
649 // Set our user ID to an invalid process ID.
650 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000651 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
652 exe_module->GetFileSpec().GetFilename().AsCString(),
653 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000654 }
Chris Lattner24943d22010-06-08 16:52:24 +0000655 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000656
Chris Lattner24943d22010-06-08 16:52:24 +0000657}
658
659
660Error
Greg Claytone71e2582011-02-04 01:58:07 +0000661ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000662{
663 Error error;
664 // Sleep and wait a bit for debugserver to start to listen...
665 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
666 if (conn_ap.get())
667 {
Chris Lattner24943d22010-06-08 16:52:24 +0000668 const uint32_t max_retry_count = 50;
669 uint32_t retry_count = 0;
670 while (!m_gdb_comm.IsConnected())
671 {
Greg Claytone71e2582011-02-04 01:58:07 +0000672 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000673 {
674 m_gdb_comm.SetConnection (conn_ap.release());
675 break;
676 }
677 retry_count++;
678
679 if (retry_count >= max_retry_count)
680 break;
681
682 usleep (100000);
683 }
684 }
685
686 if (!m_gdb_comm.IsConnected())
687 {
688 if (error.Success())
689 error.SetErrorString("not connected to remote gdb server");
690 return error;
691 }
692
Greg Clayton24bc5d92011-03-30 18:16:51 +0000693 // We always seem to be able to open a connection to a local port
694 // so we need to make sure we can then send data to it. If we can't
695 // then we aren't actually connected to anything, so try and do the
696 // handshake with the remote GDB server and make sure that goes
697 // alright.
698 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000699 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000700 m_gdb_comm.Disconnect();
701 if (error.Success())
702 error.SetErrorString("not connected to remote gdb server");
703 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000704 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000705 m_gdb_comm.ResetDiscoverableSettings();
706 m_gdb_comm.QueryNoAckModeSupported ();
707 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000708 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000709 m_gdb_comm.GetHostInfo ();
710 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000711 return error;
712}
713
714void
715ProcessGDBRemote::DidLaunchOrAttach ()
716{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000717 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
718 if (log)
719 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000720 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000721 {
722 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
723
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000724 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000725
Chris Lattner24943d22010-06-08 16:52:24 +0000726 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000727
Greg Claytoncb8977d2011-03-23 00:09:55 +0000728 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
729 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000730 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000731 ArchSpec &target_arch = GetTarget().GetArchitecture();
732
733 if (target_arch.IsValid())
734 {
735 // If the remote host is ARM and we have apple as the vendor, then
736 // ARM executables and shared libraries can have mixed ARM architectures.
737 // You can have an armv6 executable, and if the host is armv7, then the
738 // system will load the best possible architecture for all shared libraries
739 // it has, so we really need to take the remote host architecture as our
740 // defacto architecture in this case.
741
742 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
743 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
744 {
745 target_arch = gdb_remote_arch;
746 }
747 else
748 {
749 // Fill in what is missing in the triple
750 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
751 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000752 if (target_triple.getVendorName().size() == 0)
753 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000754 target_triple.setVendor (remote_triple.getVendor());
755
Greg Clayton2f085c62011-05-15 01:25:55 +0000756 if (target_triple.getOSName().size() == 0)
757 {
758 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000759
Greg Clayton2f085c62011-05-15 01:25:55 +0000760 if (target_triple.getEnvironmentName().size() == 0)
761 target_triple.setEnvironment (remote_triple.getEnvironment());
762 }
763 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000764 }
765 }
766 else
767 {
768 // The target doesn't have a valid architecture yet, set it from
769 // the architecture we got from the remote GDB server
770 target_arch = gdb_remote_arch;
771 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000772 }
Chris Lattner24943d22010-06-08 16:52:24 +0000773 }
774}
775
776void
777ProcessGDBRemote::DidLaunch ()
778{
779 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000780}
781
782Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000783ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000784{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000785 ProcessAttachInfo attach_info;
786 return DoAttachToProcessWithID(attach_pid, attach_info);
787}
788
789Error
790ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
791{
Chris Lattner24943d22010-06-08 16:52:24 +0000792 Error error;
793 // Clear out and clean up from any current state
794 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000795 if (attach_pid != LLDB_INVALID_PROCESS_ID)
796 {
Greg Claytona2f74232011-02-24 22:24:29 +0000797 // Make sure we aren't already connected?
798 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000799 {
Greg Claytona2f74232011-02-24 22:24:29 +0000800 char host_port[128];
801 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
802 char connect_url[128];
803 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000804
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000805 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000806
807 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000808 {
Greg Claytona2f74232011-02-24 22:24:29 +0000809 const char *error_string = error.AsCString();
810 if (error_string == NULL)
811 error_string = "unable to launch " DEBUGSERVER_BASENAME;
812
813 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000814 }
Greg Claytona2f74232011-02-24 22:24:29 +0000815 else
816 {
817 error = ConnectToDebugserver (connect_url);
818 }
819 }
820
821 if (error.Success())
822 {
823 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000824 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000825 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000826 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000827 }
828 }
Chris Lattner24943d22010-06-08 16:52:24 +0000829 return error;
830}
831
832size_t
833ProcessGDBRemote::AttachInputReaderCallback
834(
835 void *baton,
836 InputReader *reader,
837 lldb::InputReaderAction notification,
838 const char *bytes,
839 size_t bytes_len
840)
841{
842 if (notification == eInputReaderGotToken)
843 {
844 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
845 if (gdb_process->m_waiting_for_attach)
846 gdb_process->m_waiting_for_attach = false;
847 reader->SetIsDone(true);
848 return 1;
849 }
850 return 0;
851}
852
853Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000854ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000855{
856 Error error;
857 // Clear out and clean up from any current state
858 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000859
Chris Lattner24943d22010-06-08 16:52:24 +0000860 if (process_name && process_name[0])
861 {
Greg Claytona2f74232011-02-24 22:24:29 +0000862 // Make sure we aren't already connected?
863 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000864 {
Greg Claytona2f74232011-02-24 22:24:29 +0000865 char host_port[128];
866 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
867 char connect_url[128];
868 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
869
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000870 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000871 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000872 {
Greg Claytona2f74232011-02-24 22:24:29 +0000873 const char *error_string = error.AsCString();
874 if (error_string == NULL)
875 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000876
Greg Claytona2f74232011-02-24 22:24:29 +0000877 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000878 }
Greg Claytona2f74232011-02-24 22:24:29 +0000879 else
880 {
881 error = ConnectToDebugserver (connect_url);
882 }
883 }
884
885 if (error.Success())
886 {
887 StreamString packet;
888
889 if (wait_for_launch)
890 packet.PutCString("vAttachWait");
891 else
892 packet.PutCString("vAttachName");
893 packet.PutChar(';');
894 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
895
896 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
897
Chris Lattner24943d22010-06-08 16:52:24 +0000898 }
899 }
Chris Lattner24943d22010-06-08 16:52:24 +0000900 return error;
901}
902
Chris Lattner24943d22010-06-08 16:52:24 +0000903
904void
905ProcessGDBRemote::DidAttach ()
906{
Greg Claytone71e2582011-02-04 01:58:07 +0000907 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000908}
909
910Error
911ProcessGDBRemote::WillResume ()
912{
Greg Claytonc1f45872011-02-12 06:28:37 +0000913 m_continue_c_tids.clear();
914 m_continue_C_tids.clear();
915 m_continue_s_tids.clear();
916 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000917 return Error();
918}
919
920Error
921ProcessGDBRemote::DoResume ()
922{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000923 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000924 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
925 if (log)
926 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000927
928 Listener listener ("gdb-remote.resume-packet-sent");
929 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
930 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000931 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
932
Greg Claytonc1f45872011-02-12 06:28:37 +0000933 StreamString continue_packet;
934 bool continue_packet_error = false;
935 if (m_gdb_comm.HasAnyVContSupport ())
936 {
937 continue_packet.PutCString ("vCont");
938
939 if (!m_continue_c_tids.empty())
940 {
941 if (m_gdb_comm.GetVContSupported ('c'))
942 {
943 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 +0000944 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000945 }
946 else
947 continue_packet_error = true;
948 }
949
950 if (!continue_packet_error && !m_continue_C_tids.empty())
951 {
952 if (m_gdb_comm.GetVContSupported ('C'))
953 {
954 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 +0000955 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000956 }
957 else
958 continue_packet_error = true;
959 }
Greg Claytonb749a262010-12-03 06:02:24 +0000960
Greg Claytonc1f45872011-02-12 06:28:37 +0000961 if (!continue_packet_error && !m_continue_s_tids.empty())
962 {
963 if (m_gdb_comm.GetVContSupported ('s'))
964 {
965 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 +0000966 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000967 }
968 else
969 continue_packet_error = true;
970 }
971
972 if (!continue_packet_error && !m_continue_S_tids.empty())
973 {
974 if (m_gdb_comm.GetVContSupported ('S'))
975 {
976 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 +0000977 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000978 }
979 else
980 continue_packet_error = true;
981 }
982
983 if (continue_packet_error)
984 continue_packet.GetString().clear();
985 }
986 else
987 continue_packet_error = true;
988
989 if (continue_packet_error)
990 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000991 // Either no vCont support, or we tried to use part of the vCont
992 // packet that wasn't supported by the remote GDB server.
993 // We need to try and make a simple packet that can do our continue
994 const size_t num_threads = GetThreadList().GetSize();
995 const size_t num_continue_c_tids = m_continue_c_tids.size();
996 const size_t num_continue_C_tids = m_continue_C_tids.size();
997 const size_t num_continue_s_tids = m_continue_s_tids.size();
998 const size_t num_continue_S_tids = m_continue_S_tids.size();
999 if (num_continue_c_tids > 0)
1000 {
1001 if (num_continue_c_tids == num_threads)
1002 {
1003 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001004 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001005 continue_packet.PutChar ('c');
1006 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001007 }
1008 else if (num_continue_c_tids == 1 &&
1009 num_continue_C_tids == 0 &&
1010 num_continue_s_tids == 0 &&
1011 num_continue_S_tids == 0 )
1012 {
1013 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001014 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001015 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001016 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001017 }
1018 }
1019
Greg Claytonde1dd812011-06-24 03:21:43 +00001020 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001021 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001022 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1023 num_continue_C_tids > 0 &&
1024 num_continue_s_tids == 0 &&
1025 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001026 {
1027 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001028 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001029 if (num_continue_C_tids > 1)
1030 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001031 // More that one thread with a signal, yet we don't have
1032 // vCont support and we are being asked to resume each
1033 // thread with a signal, we need to make sure they are
1034 // all the same signal, or we can't issue the continue
1035 // accurately with the current support...
1036 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001037 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001038 continue_packet_error = false;
1039 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1040 {
1041 if (m_continue_C_tids[i].second != continue_signo)
1042 continue_packet_error = true;
1043 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001044 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001045 if (!continue_packet_error)
1046 m_gdb_comm.SetCurrentThreadForRun (-1);
1047 }
1048 else
1049 {
1050 // Set the continue thread ID
1051 continue_packet_error = false;
1052 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001053 }
1054 if (!continue_packet_error)
1055 {
1056 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001057 continue_packet.Printf("C%2.2x", continue_signo);
1058 }
1059 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001060 }
1061
Greg Claytonde1dd812011-06-24 03:21:43 +00001062 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001063 {
1064 if (num_continue_s_tids == num_threads)
1065 {
1066 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001067 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001068 continue_packet.PutChar ('s');
1069 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001070 }
1071 else if (num_continue_c_tids == 0 &&
1072 num_continue_C_tids == 0 &&
1073 num_continue_s_tids == 1 &&
1074 num_continue_S_tids == 0 )
1075 {
1076 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001077 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001078 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001079 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001080 }
1081 }
1082
1083 if (!continue_packet_error && num_continue_S_tids > 0)
1084 {
1085 if (num_continue_S_tids == num_threads)
1086 {
1087 const int step_signo = m_continue_S_tids.front().second;
1088 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001089 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001090 if (num_continue_S_tids > 1)
1091 {
1092 for (size_t i=1; i<num_threads; ++i)
1093 {
1094 if (m_continue_S_tids[i].second != step_signo)
1095 continue_packet_error = true;
1096 }
1097 }
1098 if (!continue_packet_error)
1099 {
1100 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001101 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001102 continue_packet.Printf("S%2.2x", step_signo);
1103 }
1104 }
1105 else if (num_continue_c_tids == 0 &&
1106 num_continue_C_tids == 0 &&
1107 num_continue_s_tids == 0 &&
1108 num_continue_S_tids == 1 )
1109 {
1110 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001111 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001112 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001113 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001114 }
1115 }
1116 }
1117
1118 if (continue_packet_error)
1119 {
1120 error.SetErrorString ("can't make continue packet for this resume");
1121 }
1122 else
1123 {
1124 EventSP event_sp;
1125 TimeValue timeout;
1126 timeout = TimeValue::Now();
1127 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001128 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1129 {
1130 error.SetErrorString ("Trying to resume but the async thread is dead.");
1131 if (log)
1132 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1133 return error;
1134 }
1135
Greg Claytonc1f45872011-02-12 06:28:37 +00001136 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1137
1138 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001139 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001140 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001141 if (log)
1142 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1143 }
1144 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1145 {
1146 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1147 if (log)
1148 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1149 return error;
1150 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001151 }
Greg Claytonb749a262010-12-03 06:02:24 +00001152 }
1153
Jim Ingham3ae449a2010-11-17 02:32:00 +00001154 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001155}
1156
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001157void
1158ProcessGDBRemote::ClearThreadIDList ()
1159{
1160 Mutex::Locker locker(m_thread_ids_mutex);
1161 m_thread_ids.clear();
1162}
1163
1164bool
1165ProcessGDBRemote::UpdateThreadIDList ()
1166{
1167 Mutex::Locker locker(m_thread_ids_mutex);
1168 bool sequence_mutex_unavailable = false;
1169 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1170 if (sequence_mutex_unavailable)
1171 {
1172#if defined (LLDB_CONFIGURATION_DEBUG)
1173 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1174#endif
1175 return false; // We just didn't get the list
1176 }
1177 return true;
1178}
1179
Greg Claytonae932352012-04-10 00:18:59 +00001180bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001181ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001182{
1183 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001184 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001185 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001186 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001187 // Update the thread list's stop id immediately so we don't recurse into this function.
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001188 Mutex::Locker locker(m_thread_ids_mutex);
1189
1190 size_t num_thread_ids = m_thread_ids.size();
1191 // The "m_thread_ids" thread ID list should always be updated after each stop
1192 // reply packet, but in case it isn't, update it here.
1193 if (num_thread_ids == 0)
1194 {
1195 if (!UpdateThreadIDList ())
1196 return false;
1197 num_thread_ids = m_thread_ids.size();
1198 }
Chris Lattner24943d22010-06-08 16:52:24 +00001199
Greg Clayton37f962e2011-08-22 02:49:39 +00001200 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001201 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001202 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001203 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001204 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001205 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1206 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001207 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001208 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001209 }
Chris Lattner24943d22010-06-08 16:52:24 +00001210 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001211
Greg Claytonae932352012-04-10 00:18:59 +00001212 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001213}
1214
1215
1216StateType
1217ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1218{
Greg Clayton261a18b2011-06-02 22:22:38 +00001219 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001220 const char stop_type = stop_packet.GetChar();
1221 switch (stop_type)
1222 {
1223 case 'T':
1224 case 'S':
1225 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001226 if (GetStopID() == 0)
1227 {
1228 // Our first stop, make sure we have a process ID, and also make
1229 // sure we know about our registers
1230 if (GetID() == LLDB_INVALID_PROCESS_ID)
1231 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001232 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001233 if (pid != LLDB_INVALID_PROCESS_ID)
1234 SetID (pid);
1235 }
1236 BuildDynamicRegisterInfo (true);
1237 }
Chris Lattner24943d22010-06-08 16:52:24 +00001238 // Stop with signal and thread info
1239 const uint8_t signo = stop_packet.GetHexU8();
1240 std::string name;
1241 std::string value;
1242 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001243 std::string reason;
1244 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001245 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001246 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001247 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1248 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001249 ThreadSP thread_sp;
1250
Chris Lattner24943d22010-06-08 16:52:24 +00001251 while (stop_packet.GetNameColonValue(name, value))
1252 {
1253 if (name.compare("metype") == 0)
1254 {
1255 // exception type in big endian hex
1256 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1257 }
1258 else if (name.compare("mecount") == 0)
1259 {
1260 // exception count in big endian hex
1261 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1262 }
1263 else if (name.compare("medata") == 0)
1264 {
1265 // exception data in big endian hex
1266 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1267 }
1268 else if (name.compare("thread") == 0)
1269 {
1270 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001271 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001272 // m_thread_list does have its own mutex, but we need to
1273 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1274 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001275 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001276 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001277 if (!thread_sp)
1278 {
1279 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001280 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001281 m_thread_list.AddThread(thread_sp);
1282 }
Chris Lattner24943d22010-06-08 16:52:24 +00001283 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001284 else if (name.compare("threads") == 0)
1285 {
1286 Mutex::Locker locker(m_thread_ids_mutex);
1287 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001288 // A comma separated list of all threads in the current
1289 // process that includes the thread for this stop reply
1290 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001291 size_t comma_pos;
1292 lldb::tid_t tid;
1293 while ((comma_pos = value.find(',')) != std::string::npos)
1294 {
1295 value[comma_pos] = '\0';
1296 // thread in big endian hex
1297 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1298 if (tid != LLDB_INVALID_THREAD_ID)
1299 m_thread_ids.push_back (tid);
1300 value.erase(0, comma_pos + 1);
1301
1302 }
1303 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1304 if (tid != LLDB_INVALID_THREAD_ID)
1305 m_thread_ids.push_back (tid);
1306 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001307 else if (name.compare("hexname") == 0)
1308 {
1309 StringExtractor name_extractor;
1310 // Swap "value" over into "name_extractor"
1311 name_extractor.GetStringRef().swap(value);
1312 // Now convert the HEX bytes into a string value
1313 name_extractor.GetHexByteString (value);
1314 thread_name.swap (value);
1315 }
Chris Lattner24943d22010-06-08 16:52:24 +00001316 else if (name.compare("name") == 0)
1317 {
1318 thread_name.swap (value);
1319 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001320 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001321 {
1322 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1323 }
Greg Clayton65611552011-06-04 01:26:29 +00001324 else if (name.compare("reason") == 0)
1325 {
1326 reason.swap(value);
1327 }
1328 else if (name.compare("description") == 0)
1329 {
1330 StringExtractor desc_extractor;
1331 // Swap "value" over into "name_extractor"
1332 desc_extractor.GetStringRef().swap(value);
1333 // Now convert the HEX bytes into a string value
1334 desc_extractor.GetHexByteString (thread_name);
1335 }
Greg Claytona875b642011-01-09 21:07:35 +00001336 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1337 {
1338 // We have a register number that contains an expedited
1339 // register value. Lets supply this register to our thread
1340 // so it won't have to go and read it.
1341 if (thread_sp)
1342 {
1343 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1344
1345 if (reg != UINT32_MAX)
1346 {
1347 StringExtractor reg_value_extractor;
1348 // Swap "value" over into "reg_value_extractor"
1349 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001350 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1351 {
1352 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1353 name.c_str(),
1354 reg,
1355 reg,
1356 reg_value_extractor.GetStringRef().c_str(),
1357 stop_packet.GetStringRef().c_str());
1358 }
Greg Claytona875b642011-01-09 21:07:35 +00001359 }
1360 }
1361 }
Chris Lattner24943d22010-06-08 16:52:24 +00001362 }
Chris Lattner24943d22010-06-08 16:52:24 +00001363
1364 if (thread_sp)
1365 {
1366 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1367
1368 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001369 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001370 if (exc_type != 0)
1371 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001372 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001373
1374 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1375 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001376 exc_data_size,
1377 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001378 exc_data_size >= 2 ? exc_data[1] : 0,
1379 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001380 }
Greg Clayton65611552011-06-04 01:26:29 +00001381 else
Chris Lattner24943d22010-06-08 16:52:24 +00001382 {
Greg Clayton65611552011-06-04 01:26:29 +00001383 bool handled = false;
1384 if (!reason.empty())
1385 {
1386 if (reason.compare("trace") == 0)
1387 {
1388 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1389 handled = true;
1390 }
1391 else if (reason.compare("breakpoint") == 0)
1392 {
1393 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001394 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001395 if (bp_site_sp)
1396 {
1397 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1398 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1399 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1400 if (bp_site_sp->ValidForThisThread (gdb_thread))
1401 {
1402 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1403 handled = true;
1404 }
1405 }
1406
1407 if (!handled)
1408 {
1409 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1410 }
1411 }
1412 else if (reason.compare("trap") == 0)
1413 {
1414 // Let the trap just use the standard signal stop reason below...
1415 }
1416 else if (reason.compare("watchpoint") == 0)
1417 {
1418 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1419 // TODO: locate the watchpoint somehow...
1420 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1421 handled = true;
1422 }
1423 else if (reason.compare("exception") == 0)
1424 {
1425 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1426 handled = true;
1427 }
1428 }
1429
1430 if (signo)
1431 {
1432 if (signo == SIGTRAP)
1433 {
1434 // Currently we are going to assume SIGTRAP means we are either
1435 // hitting a breakpoint or hardware single stepping.
1436 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001437 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001438 if (bp_site_sp)
1439 {
1440 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1441 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1442 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1443 if (bp_site_sp->ValidForThisThread (gdb_thread))
1444 {
1445 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1446 handled = true;
1447 }
1448 }
1449 if (!handled)
1450 {
1451 // TODO: check for breakpoint or trap opcode in case there is a hard
1452 // coded software trap
1453 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1454 handled = true;
1455 }
1456 }
1457 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001458 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001459 }
1460 else
1461 {
Greg Clayton643ee732010-08-04 01:40:35 +00001462 StopInfoSP invalid_stop_info_sp;
1463 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001464 }
Greg Clayton65611552011-06-04 01:26:29 +00001465
1466 if (!description.empty())
1467 {
1468 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1469 if (stop_info_sp)
1470 {
1471 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001472 }
Greg Clayton65611552011-06-04 01:26:29 +00001473 else
1474 {
1475 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1476 }
1477 }
1478 }
Chris Lattner24943d22010-06-08 16:52:24 +00001479 }
1480 return eStateStopped;
1481 }
1482 break;
1483
1484 case 'W':
1485 // process exited
1486 return eStateExited;
1487
1488 default:
1489 break;
1490 }
1491 return eStateInvalid;
1492}
1493
1494void
1495ProcessGDBRemote::RefreshStateAfterStop ()
1496{
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001497 Mutex::Locker locker(m_thread_ids_mutex);
1498 m_thread_ids.clear();
1499 // Set the thread stop info. It might have a "threads" key whose value is
1500 // a list of all thread IDs in the current process, so m_thread_ids might
1501 // get set.
1502 SetThreadStopInfo (m_last_stop_packet);
1503 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1504 if (m_thread_ids.empty())
1505 {
1506 // No, we need to fetch the thread list manually
1507 UpdateThreadIDList();
1508 }
1509
Chris Lattner24943d22010-06-08 16:52:24 +00001510 // Let all threads recover from stopping and do any clean up based
1511 // on the previous thread state (if any).
1512 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001513
Chris Lattner24943d22010-06-08 16:52:24 +00001514}
1515
1516Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001517ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001518{
1519 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001520
Greg Claytona4881d02011-01-22 07:12:45 +00001521 bool timed_out = false;
1522 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001523
1524 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001525 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001526 // We are being asked to halt during an attach. We need to just close
1527 // our file handle and debugserver will go away, and we can be done...
1528 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001529 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001530 else
1531 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001532 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001533 {
1534 if (timed_out)
1535 error.SetErrorString("timed out sending interrupt packet");
1536 else
1537 error.SetErrorString("unknown error sending interrupt packet");
1538 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001539
1540 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001541 }
Chris Lattner24943d22010-06-08 16:52:24 +00001542 return error;
1543}
1544
1545Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001546ProcessGDBRemote::InterruptIfRunning
1547(
1548 bool discard_thread_plans,
1549 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001550 EventSP &stop_event_sp
1551)
Chris Lattner24943d22010-06-08 16:52:24 +00001552{
1553 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001554
Greg Clayton2860ba92011-01-23 19:58:49 +00001555 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1556
Greg Clayton68ca8232011-01-25 02:58:48 +00001557 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001558 const bool is_running = m_gdb_comm.IsRunning();
1559 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001560 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001561 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001562 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001563 is_running);
1564
Greg Clayton2860ba92011-01-23 19:58:49 +00001565 if (discard_thread_plans)
1566 {
1567 if (log)
1568 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1569 m_thread_list.DiscardThreadPlans();
1570 }
1571 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001572 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001573 if (catch_stop_event)
1574 {
1575 if (log)
1576 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1577 PausePrivateStateThread();
1578 paused_private_state_thread = true;
1579 }
1580
Greg Clayton4fb400f2010-09-27 21:07:38 +00001581 bool timed_out = false;
1582 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001583
Greg Clayton05e4d972012-03-29 01:55:41 +00001584 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001585 {
1586 if (timed_out)
1587 error.SetErrorString("timed out sending interrupt packet");
1588 else
1589 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001590 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001591 ResumePrivateStateThread();
1592 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001593 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001594
Greg Clayton72e1c782011-01-22 23:43:18 +00001595 if (catch_stop_event)
1596 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001597 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001598 TimeValue timeout_time;
1599 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001600 timeout_time.OffsetWithSeconds(5);
1601 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001602
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001603 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001604 if (log)
1605 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001606
Greg Clayton2860ba92011-01-23 19:58:49 +00001607 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001608 error.SetErrorString("unable to verify target stopped");
1609 }
1610
Greg Clayton68ca8232011-01-25 02:58:48 +00001611 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001612 {
1613 if (log)
1614 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001615 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001616 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001617 }
Chris Lattner24943d22010-06-08 16:52:24 +00001618 return error;
1619}
1620
Greg Clayton4fb400f2010-09-27 21:07:38 +00001621Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001622ProcessGDBRemote::WillDetach ()
1623{
Greg Clayton2860ba92011-01-23 19:58:49 +00001624 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1625 if (log)
1626 log->Printf ("ProcessGDBRemote::WillDetach()");
1627
Greg Clayton72e1c782011-01-22 23:43:18 +00001628 bool discard_thread_plans = true;
1629 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001630 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001631 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001632}
1633
1634Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001635ProcessGDBRemote::DoDetach()
1636{
1637 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001638 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001639 if (log)
1640 log->Printf ("ProcessGDBRemote::DoDetach()");
1641
1642 DisableAllBreakpointSites ();
1643
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001644 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001645
Greg Clayton516f0842012-04-11 00:24:49 +00001646 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001647 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001648 {
Greg Clayton516f0842012-04-11 00:24:49 +00001649 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001650 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1651 else
1652 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001653 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001654 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001655 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001656
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001657 SetPrivateState (eStateDetached);
1658 ResumePrivateStateThread();
1659
1660 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001661 return error;
1662}
Chris Lattner24943d22010-06-08 16:52:24 +00001663
1664Error
1665ProcessGDBRemote::DoDestroy ()
1666{
1667 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001668 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001669 if (log)
1670 log->Printf ("ProcessGDBRemote::DoDestroy()");
1671
1672 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001673 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001674 {
Jim Ingham8226e942011-10-28 01:11:35 +00001675 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001676 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001677
1678 StringExtractorGDBRemote response;
1679 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001680 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001681 {
1682 char packet_cmd = response.GetChar(0);
1683
1684 if (packet_cmd == 'W' || packet_cmd == 'X')
1685 {
Greg Clayton06709002011-12-06 04:51:14 +00001686 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001687 ClearThreadIDList ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001688 SetExitStatus(response.GetHexU8(), NULL);
1689 }
1690 }
1691 else
1692 {
1693 SetExitStatus(SIGABRT, NULL);
1694 //error.SetErrorString("kill packet failed");
1695 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001696 }
1697 }
Chris Lattner24943d22010-06-08 16:52:24 +00001698 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001699 KillDebugserverProcess ();
1700 return error;
1701}
1702
Chris Lattner24943d22010-06-08 16:52:24 +00001703//------------------------------------------------------------------
1704// Process Queries
1705//------------------------------------------------------------------
1706
1707bool
1708ProcessGDBRemote::IsAlive ()
1709{
Greg Clayton58e844b2010-12-08 05:08:21 +00001710 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001711}
1712
1713addr_t
1714ProcessGDBRemote::GetImageInfoAddress()
1715{
Greg Clayton516f0842012-04-11 00:24:49 +00001716 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001717}
1718
Chris Lattner24943d22010-06-08 16:52:24 +00001719//------------------------------------------------------------------
1720// Process Memory
1721//------------------------------------------------------------------
1722size_t
1723ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1724{
1725 if (size > m_max_memory_size)
1726 {
1727 // Keep memory read sizes down to a sane limit. This function will be
1728 // called multiple times in order to complete the task by
1729 // lldb_private::Process so it is ok to do this.
1730 size = m_max_memory_size;
1731 }
1732
1733 char packet[64];
1734 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1735 assert (packet_len + 1 < sizeof(packet));
1736 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001737 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001738 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001739 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001740 {
1741 error.Clear();
1742 return response.GetHexBytes(buf, size, '\xdd');
1743 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001744 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001745 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001746 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001747 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1748 else
1749 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1750 }
1751 else
1752 {
1753 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1754 }
1755 return 0;
1756}
1757
1758size_t
1759ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1760{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001761 if (size > m_max_memory_size)
1762 {
1763 // Keep memory read sizes down to a sane limit. This function will be
1764 // called multiple times in order to complete the task by
1765 // lldb_private::Process so it is ok to do this.
1766 size = m_max_memory_size;
1767 }
1768
Chris Lattner24943d22010-06-08 16:52:24 +00001769 StreamString packet;
1770 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001771 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001772 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001773 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001774 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001775 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001776 {
1777 error.Clear();
1778 return size;
1779 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001780 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001781 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001782 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001783 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1784 else
1785 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1786 }
1787 else
1788 {
1789 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1790 }
1791 return 0;
1792}
1793
1794lldb::addr_t
1795ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1796{
Greg Clayton989816b2011-05-14 01:50:35 +00001797 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1798
Greg Clayton2f085c62011-05-15 01:25:55 +00001799 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001800 switch (supported)
1801 {
1802 case eLazyBoolCalculate:
1803 case eLazyBoolYes:
1804 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1805 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1806 return allocated_addr;
1807
1808 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001809 // Call mmap() to create memory in the inferior..
1810 unsigned prot = 0;
1811 if (permissions & lldb::ePermissionsReadable)
1812 prot |= eMmapProtRead;
1813 if (permissions & lldb::ePermissionsWritable)
1814 prot |= eMmapProtWrite;
1815 if (permissions & lldb::ePermissionsExecutable)
1816 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001817
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001818 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1819 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1820 m_addr_to_mmap_size[allocated_addr] = size;
1821 else
1822 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001823 break;
1824 }
1825
Chris Lattner24943d22010-06-08 16:52:24 +00001826 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001827 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001828 else
1829 error.Clear();
1830 return allocated_addr;
1831}
1832
1833Error
Greg Claytona9385532011-11-18 07:03:08 +00001834ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1835 MemoryRegionInfo &region_info)
1836{
1837
1838 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1839 return error;
1840}
1841
1842Error
Chris Lattner24943d22010-06-08 16:52:24 +00001843ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1844{
1845 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001846 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1847
1848 switch (supported)
1849 {
1850 case eLazyBoolCalculate:
1851 // We should never be deallocating memory without allocating memory
1852 // first so we should never get eLazyBoolCalculate
1853 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1854 break;
1855
1856 case eLazyBoolYes:
1857 if (!m_gdb_comm.DeallocateMemory (addr))
1858 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1859 break;
1860
1861 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001862 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001863 {
1864 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001865 if (pos != m_addr_to_mmap_size.end() &&
1866 InferiorCallMunmap(this, addr, pos->second))
1867 m_addr_to_mmap_size.erase (pos);
1868 else
1869 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001870 }
1871 break;
1872 }
1873
Chris Lattner24943d22010-06-08 16:52:24 +00001874 return error;
1875}
1876
1877
1878//------------------------------------------------------------------
1879// Process STDIO
1880//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001881size_t
1882ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1883{
1884 if (m_stdio_communication.IsConnected())
1885 {
1886 ConnectionStatus status;
1887 m_stdio_communication.Write(src, src_len, status, NULL);
1888 }
1889 return 0;
1890}
1891
1892Error
1893ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1894{
1895 Error error;
1896 assert (bp_site != NULL);
1897
Greg Claytone005f2c2010-11-06 01:53:30 +00001898 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001899 user_id_t site_id = bp_site->GetID();
1900 const addr_t addr = bp_site->GetLoadAddress();
1901 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001902 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001903
1904 if (bp_site->IsEnabled())
1905 {
1906 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001907 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 +00001908 return error;
1909 }
1910 else
1911 {
1912 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1913
1914 if (bp_site->HardwarePreferred())
1915 {
1916 // Try and set hardware breakpoint, and if that fails, fall through
1917 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001918 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001919 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001920 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001921 {
1922 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001923 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001924 return error;
1925 }
Chris Lattner24943d22010-06-08 16:52:24 +00001926 }
1927 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001928
1929 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001930 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001931 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1932 {
1933 bp_site->SetEnabled(true);
1934 bp_site->SetType (BreakpointSite::eExternal);
1935 return error;
1936 }
Chris Lattner24943d22010-06-08 16:52:24 +00001937 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001938
1939 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001940 }
1941
1942 if (log)
1943 {
1944 const char *err_string = error.AsCString();
1945 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1946 bp_site->GetLoadAddress(),
1947 err_string ? err_string : "NULL");
1948 }
1949 // We shouldn't reach here on a successful breakpoint enable...
1950 if (error.Success())
1951 error.SetErrorToGenericError();
1952 return error;
1953}
1954
1955Error
1956ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1957{
1958 Error error;
1959 assert (bp_site != NULL);
1960 addr_t addr = bp_site->GetLoadAddress();
1961 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001962 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001963 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001964 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001965
1966 if (bp_site->IsEnabled())
1967 {
1968 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1969
Greg Claytonb72d0f02011-04-12 05:54:46 +00001970 BreakpointSite::Type bp_type = bp_site->GetType();
1971 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001972 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001973 case BreakpointSite::eSoftware:
1974 error = DisableSoftwareBreakpoint (bp_site);
1975 break;
1976
1977 case BreakpointSite::eHardware:
1978 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1979 error.SetErrorToGenericError();
1980 break;
1981
1982 case BreakpointSite::eExternal:
1983 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1984 error.SetErrorToGenericError();
1985 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001986 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001987 if (error.Success())
1988 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001989 }
1990 else
1991 {
1992 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001993 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 +00001994 return error;
1995 }
1996
1997 if (error.Success())
1998 error.SetErrorToGenericError();
1999 return error;
2000}
2001
Johnny Chen21900fb2011-09-06 22:38:36 +00002002// Pre-requisite: wp != NULL.
2003static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002004GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002005{
2006 assert(wp);
2007 bool watch_read = wp->WatchpointRead();
2008 bool watch_write = wp->WatchpointWrite();
2009
2010 // watch_read and watch_write cannot both be false.
2011 assert(watch_read || watch_write);
2012 if (watch_read && watch_write)
2013 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002014 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002015 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002016 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002017 return eWatchpointWrite;
2018}
2019
Chris Lattner24943d22010-06-08 16:52:24 +00002020Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002021ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002022{
2023 Error error;
2024 if (wp)
2025 {
2026 user_id_t watchID = wp->GetID();
2027 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002028 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002029 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002030 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002031 if (wp->IsEnabled())
2032 {
2033 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002034 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002035 return error;
2036 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002037
2038 GDBStoppointType type = GetGDBStoppointType(wp);
2039 // Pass down an appropriate z/Z packet...
2040 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002041 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002042 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2043 {
2044 wp->SetEnabled(true);
2045 return error;
2046 }
2047 else
2048 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002049 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002050 else
2051 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002052 }
2053 else
2054 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002055 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002056 }
2057 if (error.Success())
2058 error.SetErrorToGenericError();
2059 return error;
2060}
2061
2062Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002063ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002064{
2065 Error error;
2066 if (wp)
2067 {
2068 user_id_t watchID = wp->GetID();
2069
Greg Claytone005f2c2010-11-06 01:53:30 +00002070 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002071
2072 addr_t addr = wp->GetLoadAddress();
2073 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002074 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002075
Johnny Chen21900fb2011-09-06 22:38:36 +00002076 if (!wp->IsEnabled())
2077 {
2078 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002079 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002080 return error;
2081 }
2082
Chris Lattner24943d22010-06-08 16:52:24 +00002083 if (wp->IsHardware())
2084 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002085 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002086 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002087 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2088 {
2089 wp->SetEnabled(false);
2090 return error;
2091 }
2092 else
2093 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002094 }
2095 // TODO: clear software watchpoints if we implement them
2096 }
2097 else
2098 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002099 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002100 }
2101 if (error.Success())
2102 error.SetErrorToGenericError();
2103 return error;
2104}
2105
2106void
2107ProcessGDBRemote::Clear()
2108{
2109 m_flags = 0;
2110 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002111}
2112
2113Error
2114ProcessGDBRemote::DoSignal (int signo)
2115{
2116 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002117 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002118 if (log)
2119 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2120
2121 if (!m_gdb_comm.SendAsyncSignal (signo))
2122 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2123 return error;
2124}
2125
Chris Lattner24943d22010-06-08 16:52:24 +00002126Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002127ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2128{
2129 ProcessLaunchInfo launch_info;
2130 return StartDebugserverProcess(debugserver_url, launch_info);
2131}
2132
2133Error
2134ProcessGDBRemote::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 +00002135{
2136 Error error;
2137 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2138 {
2139 // If we locate debugserver, keep that located version around
2140 static FileSpec g_debugserver_file_spec;
2141
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002142 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002143 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002144 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002145
2146 // Always check to see if we have an environment override for the path
2147 // to the debugserver to use and use it if we do.
2148 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2149 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002150 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002151 else
2152 debugserver_file_spec = g_debugserver_file_spec;
2153 bool debugserver_exists = debugserver_file_spec.Exists();
2154 if (!debugserver_exists)
2155 {
2156 // The debugserver binary is in the LLDB.framework/Resources
2157 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002158 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002159 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002160 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002161 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002162 if (debugserver_exists)
2163 {
2164 g_debugserver_file_spec = debugserver_file_spec;
2165 }
2166 else
2167 {
2168 g_debugserver_file_spec.Clear();
2169 debugserver_file_spec.Clear();
2170 }
Chris Lattner24943d22010-06-08 16:52:24 +00002171 }
2172 }
2173
2174 if (debugserver_exists)
2175 {
2176 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2177
2178 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002179
Greg Claytone005f2c2010-11-06 01:53:30 +00002180 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002181
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002182 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002183 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002184
Chris Lattner24943d22010-06-08 16:52:24 +00002185 // Start args with "debugserver /file/path -r --"
2186 debugserver_args.AppendArgument(debugserver_path);
2187 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002188 // use native registers, not the GDB registers
2189 debugserver_args.AppendArgument("--native-regs");
2190 // make debugserver run in its own session so signals generated by
2191 // special terminal key sequences (^C) don't affect debugserver
2192 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002193
Chris Lattner24943d22010-06-08 16:52:24 +00002194 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2195 if (env_debugserver_log_file)
2196 {
2197 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2198 debugserver_args.AppendArgument(arg_cstr);
2199 }
2200
2201 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2202 if (env_debugserver_log_flags)
2203 {
2204 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2205 debugserver_args.AppendArgument(arg_cstr);
2206 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002207// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002208// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002209
Greg Claytonb72d0f02011-04-12 05:54:46 +00002210 // We currently send down all arguments, attach pids, or attach
2211 // process names in dedicated GDB server packets, so we don't need
2212 // to pass them as arguments. This is currently because of all the
2213 // things we need to setup prior to launching: the environment,
2214 // current working dir, file actions, etc.
2215#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002216 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002217 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002218 {
Greg Claytona2f74232011-02-24 22:24:29 +00002219 // Terminate the debugserver args so we can now append the inferior args
2220 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002221
Greg Claytona2f74232011-02-24 22:24:29 +00002222 for (int i = 0; inferior_argv[i] != NULL; ++i)
2223 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002224 }
2225 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2226 {
2227 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2228 debugserver_args.AppendArgument (arg_cstr);
2229 }
2230 else if (attach_name && attach_name[0])
2231 {
2232 if (wait_for_launch)
2233 debugserver_args.AppendArgument ("--waitfor");
2234 else
2235 debugserver_args.AppendArgument ("--attach");
2236 debugserver_args.AppendArgument (attach_name);
2237 }
Chris Lattner24943d22010-06-08 16:52:24 +00002238#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002239
2240 ProcessLaunchInfo::FileAction file_action;
2241
2242 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2243 // to "/dev/null" if we run into any problems.
2244 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002245 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002246 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002247 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002248 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002249 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002250
2251 if (log)
2252 {
2253 StreamString strm;
2254 debugserver_args.Dump (&strm);
2255 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2256 }
2257
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002258 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2259 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002260
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002261 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002262
Greg Claytonb72d0f02011-04-12 05:54:46 +00002263 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002264 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002265 else
Chris Lattner24943d22010-06-08 16:52:24 +00002266 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2267
2268 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002269 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002270 }
2271 else
2272 {
Greg Clayton9c236732011-10-26 00:56:27 +00002273 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002274 }
2275
2276 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2277 StartAsyncThread ();
2278 }
2279 return error;
2280}
2281
2282bool
2283ProcessGDBRemote::MonitorDebugserverProcess
2284(
2285 void *callback_baton,
2286 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002287 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002288 int signo, // Zero for no signal
2289 int exit_status // Exit value of process if signal is zero
2290)
2291{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002292 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2293 // and might not exist anymore, so we need to carefully try to get the
2294 // target for this process first since we have a race condition when
2295 // we are done running between getting the notice that the inferior
2296 // process has died and the debugserver that was debugging this process.
2297 // In our test suite, we are also continually running process after
2298 // process, so we must be very careful to make sure:
2299 // 1 - process object hasn't been deleted already
2300 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002301
2302 // "debugserver_pid" argument passed in is the process ID for
2303 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002304 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002305
Greg Clayton75ccf502010-08-21 02:22:51 +00002306 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002307
Greg Clayton1c4642c2011-11-16 05:37:56 +00002308 // Get a shared pointer to the target that has a matching process pointer.
2309 // This target could be gone, or the target could already have a new process
2310 // object inside of it
2311 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2312
Greg Clayton72e1c782011-01-22 23:43:18 +00002313 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002314 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 +00002315
Greg Clayton1c4642c2011-11-16 05:37:56 +00002316 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002317 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002318 // We found a process in a target that matches, but another thread
2319 // might be in the process of launching a new process that will
2320 // soon replace it, so get a shared pointer to the process so we
2321 // can keep it alive.
2322 ProcessSP process_sp (target_sp->GetProcessSP());
2323 // Now we have a shared pointer to the process that can't go away on us
2324 // so we now make sure it was the same as the one passed in, and also make
2325 // sure that our previous "process *" didn't get deleted and have a new
2326 // "process *" created in its place with the same pointer. To verify this
2327 // we make sure the process has our debugserver process ID. If we pass all
2328 // of these tests, then we are sure that this process is the one we were
2329 // looking for.
2330 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002331 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002332 // Sleep for a half a second to make sure our inferior process has
2333 // time to set its exit status before we set it incorrectly when
2334 // both the debugserver and the inferior process shut down.
2335 usleep (500000);
2336 // If our process hasn't yet exited, debugserver might have died.
2337 // If the process did exit, the we are reaping it.
2338 const StateType state = process->GetState();
2339
2340 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2341 state != eStateInvalid &&
2342 state != eStateUnloaded &&
2343 state != eStateExited &&
2344 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002345 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002346 char error_str[1024];
2347 if (signo)
2348 {
2349 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2350 if (signal_cstr)
2351 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2352 else
2353 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2354 }
Chris Lattner24943d22010-06-08 16:52:24 +00002355 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002356 {
2357 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2358 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002359
Greg Clayton1c4642c2011-11-16 05:37:56 +00002360 process->SetExitStatus (-1, error_str);
2361 }
2362 // Debugserver has exited we need to let our ProcessGDBRemote
2363 // know that it no longer has a debugserver instance
2364 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002365 }
Chris Lattner24943d22010-06-08 16:52:24 +00002366 }
2367 return true;
2368}
2369
2370void
2371ProcessGDBRemote::KillDebugserverProcess ()
2372{
2373 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2374 {
2375 ::kill (m_debugserver_pid, SIGINT);
2376 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2377 }
2378}
2379
2380void
2381ProcessGDBRemote::Initialize()
2382{
2383 static bool g_initialized = false;
2384
2385 if (g_initialized == false)
2386 {
2387 g_initialized = true;
2388 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2389 GetPluginDescriptionStatic(),
2390 CreateInstance);
2391
2392 Log::Callbacks log_callbacks = {
2393 ProcessGDBRemoteLog::DisableLog,
2394 ProcessGDBRemoteLog::EnableLog,
2395 ProcessGDBRemoteLog::ListLogCategories
2396 };
2397
2398 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2399 }
2400}
2401
2402bool
Chris Lattner24943d22010-06-08 16:52:24 +00002403ProcessGDBRemote::StartAsyncThread ()
2404{
Greg Claytone005f2c2010-11-06 01:53:30 +00002405 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002406
2407 if (log)
2408 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2409
2410 // Create a thread that watches our internal state and controls which
2411 // events make it to clients (into the DCProcess event queue).
2412 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002413 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002414}
2415
2416void
2417ProcessGDBRemote::StopAsyncThread ()
2418{
Greg Claytone005f2c2010-11-06 01:53:30 +00002419 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002420
2421 if (log)
2422 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2423
2424 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002425
2426 // This will shut down the async thread.
2427 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002428
2429 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002430 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002431 {
2432 Host::ThreadJoin (m_async_thread, NULL, NULL);
2433 }
2434}
2435
2436
2437void *
2438ProcessGDBRemote::AsyncThread (void *arg)
2439{
2440 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2441
Greg Claytone005f2c2010-11-06 01:53:30 +00002442 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002443 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002444 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002445
2446 Listener listener ("ProcessGDBRemote::AsyncThread");
2447 EventSP event_sp;
2448 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2449 eBroadcastBitAsyncThreadShouldExit;
2450
2451 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2452 {
Greg Claytona2f74232011-02-24 22:24:29 +00002453 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2454
Chris Lattner24943d22010-06-08 16:52:24 +00002455 bool done = false;
2456 while (!done)
2457 {
2458 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002459 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002460 if (listener.WaitForEvent (NULL, event_sp))
2461 {
2462 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002463 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002464 {
Greg Claytona2f74232011-02-24 22:24:29 +00002465 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002466 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 +00002467
Greg Claytona2f74232011-02-24 22:24:29 +00002468 switch (event_type)
2469 {
2470 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002471 {
Greg Claytona2f74232011-02-24 22:24:29 +00002472 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002473
Greg Claytona2f74232011-02-24 22:24:29 +00002474 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002475 {
Greg Claytona2f74232011-02-24 22:24:29 +00002476 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2477 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2478 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002479 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002480
Greg Claytona2f74232011-02-24 22:24:29 +00002481 if (::strstr (continue_cstr, "vAttach") == NULL)
2482 process->SetPrivateState(eStateRunning);
2483 StringExtractorGDBRemote response;
2484 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002485
Greg Claytona2f74232011-02-24 22:24:29 +00002486 switch (stop_state)
2487 {
2488 case eStateStopped:
2489 case eStateCrashed:
2490 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002491 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002492 process->SetPrivateState (stop_state);
2493 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002494
Greg Claytona2f74232011-02-24 22:24:29 +00002495 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002496 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002497 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002498 response.SetFilePos(1);
2499 process->SetExitStatus(response.GetHexU8(), NULL);
2500 done = true;
2501 break;
2502
2503 case eStateInvalid:
2504 process->SetExitStatus(-1, "lost connection");
2505 break;
2506
2507 default:
2508 process->SetPrivateState (stop_state);
2509 break;
2510 }
Chris Lattner24943d22010-06-08 16:52:24 +00002511 }
2512 }
Greg Claytona2f74232011-02-24 22:24:29 +00002513 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002514
Greg Claytona2f74232011-02-24 22:24:29 +00002515 case eBroadcastBitAsyncThreadShouldExit:
2516 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002517 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002518 done = true;
2519 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002520
Greg Claytona2f74232011-02-24 22:24:29 +00002521 default:
2522 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002523 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 +00002524 done = true;
2525 break;
2526 }
2527 }
2528 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2529 {
2530 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2531 {
2532 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002533 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002534 }
Chris Lattner24943d22010-06-08 16:52:24 +00002535 }
2536 }
2537 else
2538 {
2539 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002540 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 +00002541 done = true;
2542 }
2543 }
2544 }
2545
2546 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002547 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002548
2549 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2550 return NULL;
2551}
2552
Chris Lattner24943d22010-06-08 16:52:24 +00002553const char *
2554ProcessGDBRemote::GetDispatchQueueNameForThread
2555(
2556 addr_t thread_dispatch_qaddr,
2557 std::string &dispatch_queue_name
2558)
2559{
2560 dispatch_queue_name.clear();
2561 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2562 {
2563 // Cache the dispatch_queue_offsets_addr value so we don't always have
2564 // to look it up
2565 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2566 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002567 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2568 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002569 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2570 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002571 if (module_sp)
2572 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2573
2574 if (dispatch_queue_offsets_symbol == NULL)
2575 {
Greg Clayton444fe992012-02-26 05:51:37 +00002576 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2577 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002578 if (module_sp)
2579 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2580 }
Chris Lattner24943d22010-06-08 16:52:24 +00002581 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002582 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002583
2584 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2585 return NULL;
2586 }
2587
2588 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002589 DataExtractor data (memory_buffer,
2590 sizeof(memory_buffer),
2591 m_target.GetArchitecture().GetByteOrder(),
2592 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002593
2594 // Excerpt from src/queue_private.h
2595 struct dispatch_queue_offsets_s
2596 {
2597 uint16_t dqo_version;
2598 uint16_t dqo_label;
2599 uint16_t dqo_label_size;
2600 } dispatch_queue_offsets;
2601
2602
2603 Error error;
2604 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2605 {
2606 uint32_t data_offset = 0;
2607 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2608 {
2609 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2610 {
2611 data_offset = 0;
2612 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2613 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2614 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2615 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2616 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2617 dispatch_queue_name.erase (bytes_read);
2618 }
2619 }
2620 }
2621 }
2622 if (dispatch_queue_name.empty())
2623 return NULL;
2624 return dispatch_queue_name.c_str();
2625}
2626
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002627//uint32_t
2628//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2629//{
2630// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2631// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2632// if (m_local_debugserver)
2633// {
2634// return Host::ListProcessesMatchingName (name, matches, pids);
2635// }
2636// else
2637// {
2638// // FIXME: Implement talking to the remote debugserver.
2639// return 0;
2640// }
2641//
2642//}
2643//
Jim Ingham55e01d82011-01-22 01:33:44 +00002644bool
2645ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2646 lldb_private::StoppointCallbackContext *context,
2647 lldb::user_id_t break_id,
2648 lldb::user_id_t break_loc_id)
2649{
2650 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2651 // run so I can stop it if that's what I want to do.
2652 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2653 if (log)
2654 log->Printf("Hit New Thread Notification breakpoint.");
2655 return false;
2656}
2657
2658
2659bool
2660ProcessGDBRemote::StartNoticingNewThreads()
2661{
2662 static const char *bp_names[] =
2663 {
2664 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002665 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002666 "_pthread_start",
2667 NULL
2668 };
2669
2670 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2671 size_t num_bps = m_thread_observation_bps.size();
2672 if (num_bps != 0)
2673 {
2674 for (int i = 0; i < num_bps; i++)
2675 {
2676 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2677 if (break_sp)
2678 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002679 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002680 log->Printf("Enabled noticing new thread breakpoint.");
2681 break_sp->SetEnabled(true);
2682 }
2683 }
2684 }
2685 else
2686 {
2687 for (int i = 0; bp_names[i] != NULL; i++)
2688 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002689 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002690 if (breakpoint)
2691 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002692 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002693 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2694 m_thread_observation_bps.push_back(breakpoint->GetID());
2695 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2696 }
2697 else
2698 {
2699 if (log)
2700 log->Printf("Failed to create new thread notification breakpoint.");
2701 return false;
2702 }
2703 }
2704 }
2705
2706 return true;
2707}
2708
2709bool
2710ProcessGDBRemote::StopNoticingNewThreads()
2711{
Jim Inghamff276fe2011-02-08 05:19:01 +00002712 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002713 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002714 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002715 size_t num_bps = m_thread_observation_bps.size();
2716 if (num_bps != 0)
2717 {
2718 for (int i = 0; i < num_bps; i++)
2719 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002720
2721 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2722 if (break_sp)
2723 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002724 break_sp->SetEnabled(false);
2725 }
2726 }
2727 }
2728 return true;
2729}
2730
2731