blob: 77981efc446153d07d733c1f82dc85f705fa2461 [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 (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000166 m_continue_c_tids (),
167 m_continue_C_tids (),
168 m_continue_s_tids (),
169 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000170 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000171 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000172 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000173 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000174{
Greg Claytonff39f742011-04-01 00:29:43 +0000175 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
176 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000177 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000178}
179
180//----------------------------------------------------------------------
181// Destructor
182//----------------------------------------------------------------------
183ProcessGDBRemote::~ProcessGDBRemote()
184{
185 // m_mach_process.UnregisterNotificationCallbacks (this);
186 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000187 // We need to call finalize on the process before destroying ourselves
188 // to make sure all of the broadcaster cleanup goes as planned. If we
189 // destruct this class, then Process::~Process() might have problems
190 // trying to fully destroy the broadcaster.
191 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000192}
193
194//----------------------------------------------------------------------
195// PluginInterface
196//----------------------------------------------------------------------
197const char *
198ProcessGDBRemote::GetPluginName()
199{
200 return "Process debugging plug-in that uses the GDB remote protocol";
201}
202
203const char *
204ProcessGDBRemote::GetShortPluginName()
205{
206 return GetPluginNameStatic();
207}
208
209uint32_t
210ProcessGDBRemote::GetPluginVersion()
211{
212 return 1;
213}
214
215void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000216ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000217{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000218 if (!force && m_register_info.GetNumRegisters() > 0)
219 return;
220
221 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000222 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000223 uint32_t reg_offset = 0;
224 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000225 StringExtractorGDBRemote::ResponseType response_type;
226 for (response_type = StringExtractorGDBRemote::eResponse;
227 response_type == StringExtractorGDBRemote::eResponse;
228 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000229 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000230 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
231 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000232 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000233 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000234 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000235 response_type = response.GetResponseType();
236 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000237 {
238 std::string name;
239 std::string value;
240 ConstString reg_name;
241 ConstString alt_name;
242 ConstString set_name;
243 RegisterInfo reg_info = { NULL, // Name
244 NULL, // Alt name
245 0, // byte size
246 reg_offset, // offset
247 eEncodingUint, // encoding
248 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000249 {
250 LLDB_INVALID_REGNUM, // GCC reg num
251 LLDB_INVALID_REGNUM, // DWARF reg num
252 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000253 reg_num, // GDB reg num
254 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000255 },
256 NULL,
257 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000258 };
259
260 while (response.GetNameColonValue(name, value))
261 {
262 if (name.compare("name") == 0)
263 {
264 reg_name.SetCString(value.c_str());
265 }
266 else if (name.compare("alt-name") == 0)
267 {
268 alt_name.SetCString(value.c_str());
269 }
270 else if (name.compare("bitsize") == 0)
271 {
272 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
273 }
274 else if (name.compare("offset") == 0)
275 {
276 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000277 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000278 {
279 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000280 }
281 }
282 else if (name.compare("encoding") == 0)
283 {
284 if (value.compare("uint") == 0)
285 reg_info.encoding = eEncodingUint;
286 else if (value.compare("sint") == 0)
287 reg_info.encoding = eEncodingSint;
288 else if (value.compare("ieee754") == 0)
289 reg_info.encoding = eEncodingIEEE754;
290 else if (value.compare("vector") == 0)
291 reg_info.encoding = eEncodingVector;
292 }
293 else if (name.compare("format") == 0)
294 {
295 if (value.compare("binary") == 0)
296 reg_info.format = eFormatBinary;
297 else if (value.compare("decimal") == 0)
298 reg_info.format = eFormatDecimal;
299 else if (value.compare("hex") == 0)
300 reg_info.format = eFormatHex;
301 else if (value.compare("float") == 0)
302 reg_info.format = eFormatFloat;
303 else if (value.compare("vector-sint8") == 0)
304 reg_info.format = eFormatVectorOfSInt8;
305 else if (value.compare("vector-uint8") == 0)
306 reg_info.format = eFormatVectorOfUInt8;
307 else if (value.compare("vector-sint16") == 0)
308 reg_info.format = eFormatVectorOfSInt16;
309 else if (value.compare("vector-uint16") == 0)
310 reg_info.format = eFormatVectorOfUInt16;
311 else if (value.compare("vector-sint32") == 0)
312 reg_info.format = eFormatVectorOfSInt32;
313 else if (value.compare("vector-uint32") == 0)
314 reg_info.format = eFormatVectorOfUInt32;
315 else if (value.compare("vector-float32") == 0)
316 reg_info.format = eFormatVectorOfFloat32;
317 else if (value.compare("vector-uint128") == 0)
318 reg_info.format = eFormatVectorOfUInt128;
319 }
320 else if (name.compare("set") == 0)
321 {
322 set_name.SetCString(value.c_str());
323 }
324 else if (name.compare("gcc") == 0)
325 {
326 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
327 }
328 else if (name.compare("dwarf") == 0)
329 {
330 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
331 }
332 else if (name.compare("generic") == 0)
333 {
334 if (value.compare("pc") == 0)
335 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
336 else if (value.compare("sp") == 0)
337 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
338 else if (value.compare("fp") == 0)
339 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
340 else if (value.compare("ra") == 0)
341 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
342 else if (value.compare("flags") == 0)
343 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000344 else if (value.find("arg") == 0)
345 {
346 if (value.size() == 4)
347 {
348 switch (value[3])
349 {
350 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
351 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
352 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
353 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
354 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
355 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
356 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
357 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
358 }
359 }
360 }
Chris Lattner24943d22010-06-08 16:52:24 +0000361 }
362 }
363
Jason Molenda53d96862010-06-11 23:44:18 +0000364 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000365 assert (reg_info.byte_size != 0);
366 reg_offset += reg_info.byte_size;
367 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
368 }
369 }
370 else
371 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000372 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000373 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000374 }
375 }
376
377 if (reg_num == 0)
378 {
379 // We didn't get anything. See if we are debugging ARM and fill with
380 // a hard coded register set until we can get an updated debugserver
381 // down on the devices.
Jason Molenda428b5502011-10-06 01:45:46 +0000382
383 if (!GetTarget().GetArchitecture().IsValid()
384 && m_gdb_comm.GetHostArchitecture().IsValid()
385 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm
386 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
387 {
Chris Lattner24943d22010-06-08 16:52:24 +0000388 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000389 }
390 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
391 {
392 m_register_info.HardcodeARMRegisters();
393 }
Chris Lattner24943d22010-06-08 16:52:24 +0000394 }
395 m_register_info.Finalize ();
396}
397
398Error
399ProcessGDBRemote::WillLaunch (Module* module)
400{
401 return WillLaunchOrAttach ();
402}
403
404Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000405ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000406{
407 return WillLaunchOrAttach ();
408}
409
410Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000411ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000412{
413 return WillLaunchOrAttach ();
414}
415
416Error
Greg Claytone71e2582011-02-04 01:58:07 +0000417ProcessGDBRemote::DoConnectRemote (const char *remote_url)
418{
419 Error error (WillLaunchOrAttach ());
420
421 if (error.Fail())
422 return error;
423
Greg Clayton180546b2011-04-30 01:09:13 +0000424 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000425
426 if (error.Fail())
427 return error;
428 StartAsyncThread ();
429
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000430 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000431 if (pid == LLDB_INVALID_PROCESS_ID)
432 {
433 // We don't have a valid process ID, so note that we are connected
434 // and could now request to launch or attach, or get remote process
435 // listings...
436 SetPrivateState (eStateConnected);
437 }
438 else
439 {
440 // We have a valid process
441 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000442 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000443 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000444 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000445 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000446 if (state == eStateStopped)
447 {
448 SetPrivateState (state);
449 }
450 else
Greg Claytond9919d32011-12-01 23:28:38 +0000451 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 +0000452 }
453 else
Greg Claytond9919d32011-12-01 23:28:38 +0000454 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 +0000455 }
456 return error;
457}
458
459Error
Chris Lattner24943d22010-06-08 16:52:24 +0000460ProcessGDBRemote::WillLaunchOrAttach ()
461{
462 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000463 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000464 return error;
465}
466
467//----------------------------------------------------------------------
468// Process Control
469//----------------------------------------------------------------------
470Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000471ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000472{
Greg Clayton4b407112010-09-30 21:49:03 +0000473 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000474
475 uint32_t launch_flags = launch_info.GetFlags().Get();
476 const char *stdin_path = NULL;
477 const char *stdout_path = NULL;
478 const char *stderr_path = NULL;
479 const char *working_dir = launch_info.GetWorkingDirectory();
480
481 const ProcessLaunchInfo::FileAction *file_action;
482 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
483 if (file_action)
484 {
485 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
486 stdin_path = file_action->GetPath();
487 }
488 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
489 if (file_action)
490 {
491 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
492 stdout_path = file_action->GetPath();
493 }
494 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
495 if (file_action)
496 {
497 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
498 stderr_path = file_action->GetPath();
499 }
500
Chris Lattner24943d22010-06-08 16:52:24 +0000501 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
502 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
503 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000504 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000505
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000506 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000507 if (object_file)
508 {
Chris Lattner24943d22010-06-08 16:52:24 +0000509 char host_port[128];
510 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000511 char connect_url[128];
512 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000513
Greg Claytona2f74232011-02-24 22:24:29 +0000514 // Make sure we aren't already connected?
515 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000516 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000517 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000518 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000519 {
Johnny Chenc143d622011-08-09 18:56:45 +0000520 if (log)
521 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000522 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000523 }
Chris Lattner24943d22010-06-08 16:52:24 +0000524
Greg Claytone71e2582011-02-04 01:58:07 +0000525 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000526 }
527
528 if (error.Success())
529 {
530 lldb_utility::PseudoTerminal pty;
531 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000532
533 // If the debugserver is local and we aren't disabling STDIO, lets use
534 // a pseudo terminal to instead of relying on the 'O' packets for stdio
535 // since 'O' packets can really slow down debugging if the inferior
536 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000537 PlatformSP platform_sp (m_target.GetPlatform());
538 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000539 {
540 const char *slave_name = NULL;
541 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000542 {
Greg Claytona2f74232011-02-24 22:24:29 +0000543 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
544 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000545 }
Greg Claytona2f74232011-02-24 22:24:29 +0000546 if (stdin_path == NULL)
547 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000548
Greg Claytona2f74232011-02-24 22:24:29 +0000549 if (stdout_path == NULL)
550 stdout_path = slave_name;
551
552 if (stderr_path == NULL)
553 stderr_path = slave_name;
554 }
555
Greg Claytonafb81862011-03-02 21:34:46 +0000556 // Set STDIN to /dev/null if we want STDIO disabled or if either
557 // STDOUT or STDERR have been set to something and STDIN hasn't
558 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000559 stdin_path = "/dev/null";
560
Greg Claytonafb81862011-03-02 21:34:46 +0000561 // Set STDOUT to /dev/null if we want STDIO disabled or if either
562 // STDIN or STDERR have been set to something and STDOUT hasn't
563 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000564 stdout_path = "/dev/null";
565
Greg Claytonafb81862011-03-02 21:34:46 +0000566 // Set STDERR to /dev/null if we want STDIO disabled or if either
567 // STDIN or STDOUT have been set to something and STDERR hasn't
568 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000569 stderr_path = "/dev/null";
570
571 if (stdin_path)
572 m_gdb_comm.SetSTDIN (stdin_path);
573 if (stdout_path)
574 m_gdb_comm.SetSTDOUT (stdout_path);
575 if (stderr_path)
576 m_gdb_comm.SetSTDERR (stderr_path);
577
578 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
579
Greg Claytona4582402011-05-08 04:53:50 +0000580 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000581
582 if (working_dir && working_dir[0])
583 {
584 m_gdb_comm.SetWorkingDir (working_dir);
585 }
586
587 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000588 const Args &environment = launch_info.GetEnvironmentEntries();
589 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000590 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000591 size_t num_environment_entries = environment.GetArgumentCount();
592 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000593 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000594 const char *env_entry = environment.GetArgumentAtIndex(i);
595 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000596 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000597 }
Greg Claytona2f74232011-02-24 22:24:29 +0000598 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000599
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000600 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000601 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000602 if (arg_packet_err == 0)
603 {
604 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000605 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000606 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000607 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000608 }
609 else
610 {
Greg Claytona2f74232011-02-24 22:24:29 +0000611 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000612 }
Greg Claytona2f74232011-02-24 22:24:29 +0000613 }
614 else
615 {
Greg Clayton9c236732011-10-26 00:56:27 +0000616 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000617 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000618
619 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000620
Greg Claytona2f74232011-02-24 22:24:29 +0000621 if (GetID() == LLDB_INVALID_PROCESS_ID)
622 {
Johnny Chenc143d622011-08-09 18:56:45 +0000623 if (log)
624 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000625 KillDebugserverProcess ();
626 return error;
627 }
628
Greg Clayton261a18b2011-06-02 22:22:38 +0000629 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000630 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000631 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000632
633 if (!disable_stdio)
634 {
635 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000636 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000637 }
Chris Lattner24943d22010-06-08 16:52:24 +0000638 }
639 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000640 else
641 {
Johnny Chenc143d622011-08-09 18:56:45 +0000642 if (log)
643 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000644 }
Chris Lattner24943d22010-06-08 16:52:24 +0000645 }
646 else
647 {
648 // Set our user ID to an invalid process ID.
649 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000650 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
651 exe_module->GetFileSpec().GetFilename().AsCString(),
652 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000653 }
Chris Lattner24943d22010-06-08 16:52:24 +0000654 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000655
Chris Lattner24943d22010-06-08 16:52:24 +0000656}
657
658
659Error
Greg Claytone71e2582011-02-04 01:58:07 +0000660ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000661{
662 Error error;
663 // Sleep and wait a bit for debugserver to start to listen...
664 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
665 if (conn_ap.get())
666 {
Chris Lattner24943d22010-06-08 16:52:24 +0000667 const uint32_t max_retry_count = 50;
668 uint32_t retry_count = 0;
669 while (!m_gdb_comm.IsConnected())
670 {
Greg Claytone71e2582011-02-04 01:58:07 +0000671 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000672 {
673 m_gdb_comm.SetConnection (conn_ap.release());
674 break;
675 }
676 retry_count++;
677
678 if (retry_count >= max_retry_count)
679 break;
680
681 usleep (100000);
682 }
683 }
684
685 if (!m_gdb_comm.IsConnected())
686 {
687 if (error.Success())
688 error.SetErrorString("not connected to remote gdb server");
689 return error;
690 }
691
Greg Clayton24bc5d92011-03-30 18:16:51 +0000692 // We always seem to be able to open a connection to a local port
693 // so we need to make sure we can then send data to it. If we can't
694 // then we aren't actually connected to anything, so try and do the
695 // handshake with the remote GDB server and make sure that goes
696 // alright.
697 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000698 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000699 m_gdb_comm.Disconnect();
700 if (error.Success())
701 error.SetErrorString("not connected to remote gdb server");
702 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000703 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000704 m_gdb_comm.ResetDiscoverableSettings();
705 m_gdb_comm.QueryNoAckModeSupported ();
706 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000707 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000708 m_gdb_comm.GetHostInfo ();
709 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000710 return error;
711}
712
713void
714ProcessGDBRemote::DidLaunchOrAttach ()
715{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000716 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
717 if (log)
718 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000719 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000720 {
721 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
722
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000723 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000724
Chris Lattner24943d22010-06-08 16:52:24 +0000725 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000726
Greg Claytoncb8977d2011-03-23 00:09:55 +0000727 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
728 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000729 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000730 ArchSpec &target_arch = GetTarget().GetArchitecture();
731
732 if (target_arch.IsValid())
733 {
734 // If the remote host is ARM and we have apple as the vendor, then
735 // ARM executables and shared libraries can have mixed ARM architectures.
736 // You can have an armv6 executable, and if the host is armv7, then the
737 // system will load the best possible architecture for all shared libraries
738 // it has, so we really need to take the remote host architecture as our
739 // defacto architecture in this case.
740
741 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
742 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
743 {
744 target_arch = gdb_remote_arch;
745 }
746 else
747 {
748 // Fill in what is missing in the triple
749 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
750 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000751 if (target_triple.getVendorName().size() == 0)
752 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000753 target_triple.setVendor (remote_triple.getVendor());
754
Greg Clayton2f085c62011-05-15 01:25:55 +0000755 if (target_triple.getOSName().size() == 0)
756 {
757 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000758
Greg Clayton2f085c62011-05-15 01:25:55 +0000759 if (target_triple.getEnvironmentName().size() == 0)
760 target_triple.setEnvironment (remote_triple.getEnvironment());
761 }
762 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000763 }
764 }
765 else
766 {
767 // The target doesn't have a valid architecture yet, set it from
768 // the architecture we got from the remote GDB server
769 target_arch = gdb_remote_arch;
770 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000771 }
Chris Lattner24943d22010-06-08 16:52:24 +0000772 }
773}
774
775void
776ProcessGDBRemote::DidLaunch ()
777{
778 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000779}
780
781Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000782ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000783{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000784 ProcessAttachInfo attach_info;
785 return DoAttachToProcessWithID(attach_pid, attach_info);
786}
787
788Error
789ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
790{
Chris Lattner24943d22010-06-08 16:52:24 +0000791 Error error;
792 // Clear out and clean up from any current state
793 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000794 if (attach_pid != LLDB_INVALID_PROCESS_ID)
795 {
Greg Claytona2f74232011-02-24 22:24:29 +0000796 // Make sure we aren't already connected?
797 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000798 {
Greg Claytona2f74232011-02-24 22:24:29 +0000799 char host_port[128];
800 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
801 char connect_url[128];
802 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000803
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000804 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000805
806 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000807 {
Greg Claytona2f74232011-02-24 22:24:29 +0000808 const char *error_string = error.AsCString();
809 if (error_string == NULL)
810 error_string = "unable to launch " DEBUGSERVER_BASENAME;
811
812 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000813 }
Greg Claytona2f74232011-02-24 22:24:29 +0000814 else
815 {
816 error = ConnectToDebugserver (connect_url);
817 }
818 }
819
820 if (error.Success())
821 {
822 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000823 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000824 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000825 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000826 }
827 }
Chris Lattner24943d22010-06-08 16:52:24 +0000828 return error;
829}
830
831size_t
832ProcessGDBRemote::AttachInputReaderCallback
833(
834 void *baton,
835 InputReader *reader,
836 lldb::InputReaderAction notification,
837 const char *bytes,
838 size_t bytes_len
839)
840{
841 if (notification == eInputReaderGotToken)
842 {
843 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
844 if (gdb_process->m_waiting_for_attach)
845 gdb_process->m_waiting_for_attach = false;
846 reader->SetIsDone(true);
847 return 1;
848 }
849 return 0;
850}
851
852Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000853ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000854{
855 Error error;
856 // Clear out and clean up from any current state
857 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000858
Chris Lattner24943d22010-06-08 16:52:24 +0000859 if (process_name && process_name[0])
860 {
Greg Claytona2f74232011-02-24 22:24:29 +0000861 // Make sure we aren't already connected?
862 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000863 {
Greg Claytona2f74232011-02-24 22:24:29 +0000864 char host_port[128];
865 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
866 char connect_url[128];
867 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
868
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000869 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000870 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000871 {
Greg Claytona2f74232011-02-24 22:24:29 +0000872 const char *error_string = error.AsCString();
873 if (error_string == NULL)
874 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000875
Greg Claytona2f74232011-02-24 22:24:29 +0000876 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000877 }
Greg Claytona2f74232011-02-24 22:24:29 +0000878 else
879 {
880 error = ConnectToDebugserver (connect_url);
881 }
882 }
883
884 if (error.Success())
885 {
886 StreamString packet;
887
888 if (wait_for_launch)
889 packet.PutCString("vAttachWait");
890 else
891 packet.PutCString("vAttachName");
892 packet.PutChar(';');
893 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
894
895 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
896
Chris Lattner24943d22010-06-08 16:52:24 +0000897 }
898 }
Chris Lattner24943d22010-06-08 16:52:24 +0000899 return error;
900}
901
Chris Lattner24943d22010-06-08 16:52:24 +0000902
903void
904ProcessGDBRemote::DidAttach ()
905{
Greg Claytone71e2582011-02-04 01:58:07 +0000906 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000907}
908
909Error
910ProcessGDBRemote::WillResume ()
911{
Greg Claytonc1f45872011-02-12 06:28:37 +0000912 m_continue_c_tids.clear();
913 m_continue_C_tids.clear();
914 m_continue_s_tids.clear();
915 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000916 return Error();
917}
918
919Error
920ProcessGDBRemote::DoResume ()
921{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000922 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000923 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
924 if (log)
925 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000926
927 Listener listener ("gdb-remote.resume-packet-sent");
928 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
929 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000930 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
931
Greg Claytonc1f45872011-02-12 06:28:37 +0000932 StreamString continue_packet;
933 bool continue_packet_error = false;
934 if (m_gdb_comm.HasAnyVContSupport ())
935 {
936 continue_packet.PutCString ("vCont");
937
938 if (!m_continue_c_tids.empty())
939 {
940 if (m_gdb_comm.GetVContSupported ('c'))
941 {
942 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 +0000943 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000944 }
945 else
946 continue_packet_error = true;
947 }
948
949 if (!continue_packet_error && !m_continue_C_tids.empty())
950 {
951 if (m_gdb_comm.GetVContSupported ('C'))
952 {
953 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 +0000954 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000955 }
956 else
957 continue_packet_error = true;
958 }
Greg Claytonb749a262010-12-03 06:02:24 +0000959
Greg Claytonc1f45872011-02-12 06:28:37 +0000960 if (!continue_packet_error && !m_continue_s_tids.empty())
961 {
962 if (m_gdb_comm.GetVContSupported ('s'))
963 {
964 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 +0000965 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000966 }
967 else
968 continue_packet_error = true;
969 }
970
971 if (!continue_packet_error && !m_continue_S_tids.empty())
972 {
973 if (m_gdb_comm.GetVContSupported ('S'))
974 {
975 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 +0000976 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000977 }
978 else
979 continue_packet_error = true;
980 }
981
982 if (continue_packet_error)
983 continue_packet.GetString().clear();
984 }
985 else
986 continue_packet_error = true;
987
988 if (continue_packet_error)
989 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000990 // Either no vCont support, or we tried to use part of the vCont
991 // packet that wasn't supported by the remote GDB server.
992 // We need to try and make a simple packet that can do our continue
993 const size_t num_threads = GetThreadList().GetSize();
994 const size_t num_continue_c_tids = m_continue_c_tids.size();
995 const size_t num_continue_C_tids = m_continue_C_tids.size();
996 const size_t num_continue_s_tids = m_continue_s_tids.size();
997 const size_t num_continue_S_tids = m_continue_S_tids.size();
998 if (num_continue_c_tids > 0)
999 {
1000 if (num_continue_c_tids == num_threads)
1001 {
1002 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001003 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001004 continue_packet.PutChar ('c');
1005 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001006 }
1007 else if (num_continue_c_tids == 1 &&
1008 num_continue_C_tids == 0 &&
1009 num_continue_s_tids == 0 &&
1010 num_continue_S_tids == 0 )
1011 {
1012 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001013 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001014 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001015 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001016 }
1017 }
1018
Greg Claytonde1dd812011-06-24 03:21:43 +00001019 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001020 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001021 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1022 num_continue_C_tids > 0 &&
1023 num_continue_s_tids == 0 &&
1024 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001025 {
1026 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001027 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001028 if (num_continue_C_tids > 1)
1029 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001030 // More that one thread with a signal, yet we don't have
1031 // vCont support and we are being asked to resume each
1032 // thread with a signal, we need to make sure they are
1033 // all the same signal, or we can't issue the continue
1034 // accurately with the current support...
1035 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001036 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001037 continue_packet_error = false;
1038 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1039 {
1040 if (m_continue_C_tids[i].second != continue_signo)
1041 continue_packet_error = true;
1042 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001043 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001044 if (!continue_packet_error)
1045 m_gdb_comm.SetCurrentThreadForRun (-1);
1046 }
1047 else
1048 {
1049 // Set the continue thread ID
1050 continue_packet_error = false;
1051 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001052 }
1053 if (!continue_packet_error)
1054 {
1055 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001056 continue_packet.Printf("C%2.2x", continue_signo);
1057 }
1058 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001059 }
1060
Greg Claytonde1dd812011-06-24 03:21:43 +00001061 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001062 {
1063 if (num_continue_s_tids == num_threads)
1064 {
1065 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001066 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001067 continue_packet.PutChar ('s');
1068 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001069 }
1070 else if (num_continue_c_tids == 0 &&
1071 num_continue_C_tids == 0 &&
1072 num_continue_s_tids == 1 &&
1073 num_continue_S_tids == 0 )
1074 {
1075 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001076 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001077 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001078 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001079 }
1080 }
1081
1082 if (!continue_packet_error && num_continue_S_tids > 0)
1083 {
1084 if (num_continue_S_tids == num_threads)
1085 {
1086 const int step_signo = m_continue_S_tids.front().second;
1087 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001088 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001089 if (num_continue_S_tids > 1)
1090 {
1091 for (size_t i=1; i<num_threads; ++i)
1092 {
1093 if (m_continue_S_tids[i].second != step_signo)
1094 continue_packet_error = true;
1095 }
1096 }
1097 if (!continue_packet_error)
1098 {
1099 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001100 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001101 continue_packet.Printf("S%2.2x", step_signo);
1102 }
1103 }
1104 else if (num_continue_c_tids == 0 &&
1105 num_continue_C_tids == 0 &&
1106 num_continue_s_tids == 0 &&
1107 num_continue_S_tids == 1 )
1108 {
1109 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001110 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001111 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001112 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001113 }
1114 }
1115 }
1116
1117 if (continue_packet_error)
1118 {
1119 error.SetErrorString ("can't make continue packet for this resume");
1120 }
1121 else
1122 {
1123 EventSP event_sp;
1124 TimeValue timeout;
1125 timeout = TimeValue::Now();
1126 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001127 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1128 {
1129 error.SetErrorString ("Trying to resume but the async thread is dead.");
1130 if (log)
1131 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1132 return error;
1133 }
1134
Greg Claytonc1f45872011-02-12 06:28:37 +00001135 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1136
1137 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001138 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001139 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001140 if (log)
1141 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1142 }
1143 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1144 {
1145 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1146 if (log)
1147 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1148 return error;
1149 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001150 }
Greg Claytonb749a262010-12-03 06:02:24 +00001151 }
1152
Jim Ingham3ae449a2010-11-17 02:32:00 +00001153 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001154}
1155
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001156void
1157ProcessGDBRemote::ClearThreadIDList ()
1158{
Greg Claytonff3448e2012-04-13 02:11:32 +00001159 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001160 m_thread_ids.clear();
1161}
1162
1163bool
1164ProcessGDBRemote::UpdateThreadIDList ()
1165{
Greg Claytonff3448e2012-04-13 02:11:32 +00001166 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001167 bool sequence_mutex_unavailable = false;
1168 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1169 if (sequence_mutex_unavailable)
1170 {
1171#if defined (LLDB_CONFIGURATION_DEBUG)
1172 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1173#endif
1174 return false; // We just didn't get the list
1175 }
1176 return true;
1177}
1178
Greg Claytonae932352012-04-10 00:18:59 +00001179bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001180ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001181{
1182 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001183 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001184 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001185 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001186
1187 size_t num_thread_ids = m_thread_ids.size();
1188 // The "m_thread_ids" thread ID list should always be updated after each stop
1189 // reply packet, but in case it isn't, update it here.
1190 if (num_thread_ids == 0)
1191 {
1192 if (!UpdateThreadIDList ())
1193 return false;
1194 num_thread_ids = m_thread_ids.size();
1195 }
Chris Lattner24943d22010-06-08 16:52:24 +00001196
Greg Clayton37f962e2011-08-22 02:49:39 +00001197 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001198 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001199 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001200 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001201 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001202 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1203 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001204 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001205 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001206 }
Chris Lattner24943d22010-06-08 16:52:24 +00001207 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001208
Greg Claytonae932352012-04-10 00:18:59 +00001209 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001210}
1211
1212
1213StateType
1214ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1215{
Greg Clayton261a18b2011-06-02 22:22:38 +00001216 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001217 const char stop_type = stop_packet.GetChar();
1218 switch (stop_type)
1219 {
1220 case 'T':
1221 case 'S':
1222 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001223 if (GetStopID() == 0)
1224 {
1225 // Our first stop, make sure we have a process ID, and also make
1226 // sure we know about our registers
1227 if (GetID() == LLDB_INVALID_PROCESS_ID)
1228 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001229 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001230 if (pid != LLDB_INVALID_PROCESS_ID)
1231 SetID (pid);
1232 }
1233 BuildDynamicRegisterInfo (true);
1234 }
Chris Lattner24943d22010-06-08 16:52:24 +00001235 // Stop with signal and thread info
1236 const uint8_t signo = stop_packet.GetHexU8();
1237 std::string name;
1238 std::string value;
1239 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001240 std::string reason;
1241 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001242 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001243 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001244 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1245 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001246 ThreadSP thread_sp;
1247
Chris Lattner24943d22010-06-08 16:52:24 +00001248 while (stop_packet.GetNameColonValue(name, value))
1249 {
1250 if (name.compare("metype") == 0)
1251 {
1252 // exception type in big endian hex
1253 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1254 }
1255 else if (name.compare("mecount") == 0)
1256 {
1257 // exception count in big endian hex
1258 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1259 }
1260 else if (name.compare("medata") == 0)
1261 {
1262 // exception data in big endian hex
1263 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1264 }
1265 else if (name.compare("thread") == 0)
1266 {
1267 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001268 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001269 // m_thread_list does have its own mutex, but we need to
1270 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1271 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001272 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001273 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001274 if (!thread_sp)
1275 {
1276 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001277 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001278 m_thread_list.AddThread(thread_sp);
1279 }
Chris Lattner24943d22010-06-08 16:52:24 +00001280 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001281 else if (name.compare("threads") == 0)
1282 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001283 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001284 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001285 // A comma separated list of all threads in the current
1286 // process that includes the thread for this stop reply
1287 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001288 size_t comma_pos;
1289 lldb::tid_t tid;
1290 while ((comma_pos = value.find(',')) != std::string::npos)
1291 {
1292 value[comma_pos] = '\0';
1293 // thread in big endian hex
1294 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1295 if (tid != LLDB_INVALID_THREAD_ID)
1296 m_thread_ids.push_back (tid);
1297 value.erase(0, comma_pos + 1);
1298
1299 }
1300 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1301 if (tid != LLDB_INVALID_THREAD_ID)
1302 m_thread_ids.push_back (tid);
1303 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001304 else if (name.compare("hexname") == 0)
1305 {
1306 StringExtractor name_extractor;
1307 // Swap "value" over into "name_extractor"
1308 name_extractor.GetStringRef().swap(value);
1309 // Now convert the HEX bytes into a string value
1310 name_extractor.GetHexByteString (value);
1311 thread_name.swap (value);
1312 }
Chris Lattner24943d22010-06-08 16:52:24 +00001313 else if (name.compare("name") == 0)
1314 {
1315 thread_name.swap (value);
1316 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001317 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001318 {
1319 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1320 }
Greg Clayton65611552011-06-04 01:26:29 +00001321 else if (name.compare("reason") == 0)
1322 {
1323 reason.swap(value);
1324 }
1325 else if (name.compare("description") == 0)
1326 {
1327 StringExtractor desc_extractor;
1328 // Swap "value" over into "name_extractor"
1329 desc_extractor.GetStringRef().swap(value);
1330 // Now convert the HEX bytes into a string value
1331 desc_extractor.GetHexByteString (thread_name);
1332 }
Greg Claytona875b642011-01-09 21:07:35 +00001333 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1334 {
1335 // We have a register number that contains an expedited
1336 // register value. Lets supply this register to our thread
1337 // so it won't have to go and read it.
1338 if (thread_sp)
1339 {
1340 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1341
1342 if (reg != UINT32_MAX)
1343 {
1344 StringExtractor reg_value_extractor;
1345 // Swap "value" over into "reg_value_extractor"
1346 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001347 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1348 {
1349 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1350 name.c_str(),
1351 reg,
1352 reg,
1353 reg_value_extractor.GetStringRef().c_str(),
1354 stop_packet.GetStringRef().c_str());
1355 }
Greg Claytona875b642011-01-09 21:07:35 +00001356 }
1357 }
1358 }
Chris Lattner24943d22010-06-08 16:52:24 +00001359 }
Chris Lattner24943d22010-06-08 16:52:24 +00001360
1361 if (thread_sp)
1362 {
1363 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1364
1365 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001366 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001367 if (exc_type != 0)
1368 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001369 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001370
1371 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1372 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001373 exc_data_size,
1374 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001375 exc_data_size >= 2 ? exc_data[1] : 0,
1376 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001377 }
Greg Clayton65611552011-06-04 01:26:29 +00001378 else
Chris Lattner24943d22010-06-08 16:52:24 +00001379 {
Greg Clayton65611552011-06-04 01:26:29 +00001380 bool handled = false;
1381 if (!reason.empty())
1382 {
1383 if (reason.compare("trace") == 0)
1384 {
1385 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1386 handled = true;
1387 }
1388 else if (reason.compare("breakpoint") == 0)
1389 {
1390 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001391 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001392 if (bp_site_sp)
1393 {
1394 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1395 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1396 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1397 if (bp_site_sp->ValidForThisThread (gdb_thread))
1398 {
1399 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1400 handled = true;
1401 }
1402 }
1403
1404 if (!handled)
1405 {
1406 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1407 }
1408 }
1409 else if (reason.compare("trap") == 0)
1410 {
1411 // Let the trap just use the standard signal stop reason below...
1412 }
1413 else if (reason.compare("watchpoint") == 0)
1414 {
1415 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1416 // TODO: locate the watchpoint somehow...
1417 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1418 handled = true;
1419 }
1420 else if (reason.compare("exception") == 0)
1421 {
1422 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1423 handled = true;
1424 }
1425 }
1426
1427 if (signo)
1428 {
1429 if (signo == SIGTRAP)
1430 {
1431 // Currently we are going to assume SIGTRAP means we are either
1432 // hitting a breakpoint or hardware single stepping.
1433 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001434 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001435 if (bp_site_sp)
1436 {
1437 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1438 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1439 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1440 if (bp_site_sp->ValidForThisThread (gdb_thread))
1441 {
1442 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1443 handled = true;
1444 }
1445 }
1446 if (!handled)
1447 {
1448 // TODO: check for breakpoint or trap opcode in case there is a hard
1449 // coded software trap
1450 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1451 handled = true;
1452 }
1453 }
1454 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001455 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001456 }
1457 else
1458 {
Greg Clayton643ee732010-08-04 01:40:35 +00001459 StopInfoSP invalid_stop_info_sp;
1460 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001461 }
Greg Clayton65611552011-06-04 01:26:29 +00001462
1463 if (!description.empty())
1464 {
1465 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1466 if (stop_info_sp)
1467 {
1468 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001469 }
Greg Clayton65611552011-06-04 01:26:29 +00001470 else
1471 {
1472 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1473 }
1474 }
1475 }
Chris Lattner24943d22010-06-08 16:52:24 +00001476 }
1477 return eStateStopped;
1478 }
1479 break;
1480
1481 case 'W':
1482 // process exited
1483 return eStateExited;
1484
1485 default:
1486 break;
1487 }
1488 return eStateInvalid;
1489}
1490
1491void
1492ProcessGDBRemote::RefreshStateAfterStop ()
1493{
Greg Claytonff3448e2012-04-13 02:11:32 +00001494 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001495 m_thread_ids.clear();
1496 // Set the thread stop info. It might have a "threads" key whose value is
1497 // a list of all thread IDs in the current process, so m_thread_ids might
1498 // get set.
1499 SetThreadStopInfo (m_last_stop_packet);
1500 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1501 if (m_thread_ids.empty())
1502 {
1503 // No, we need to fetch the thread list manually
1504 UpdateThreadIDList();
1505 }
1506
Chris Lattner24943d22010-06-08 16:52:24 +00001507 // Let all threads recover from stopping and do any clean up based
1508 // on the previous thread state (if any).
1509 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001510
Chris Lattner24943d22010-06-08 16:52:24 +00001511}
1512
1513Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001514ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001515{
1516 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001517
Greg Claytona4881d02011-01-22 07:12:45 +00001518 bool timed_out = false;
1519 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001520
1521 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001522 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001523 // We are being asked to halt during an attach. We need to just close
1524 // our file handle and debugserver will go away, and we can be done...
1525 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001526 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001527 else
1528 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001529 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001530 {
1531 if (timed_out)
1532 error.SetErrorString("timed out sending interrupt packet");
1533 else
1534 error.SetErrorString("unknown error sending interrupt packet");
1535 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001536
1537 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001538 }
Chris Lattner24943d22010-06-08 16:52:24 +00001539 return error;
1540}
1541
1542Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001543ProcessGDBRemote::InterruptIfRunning
1544(
1545 bool discard_thread_plans,
1546 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001547 EventSP &stop_event_sp
1548)
Chris Lattner24943d22010-06-08 16:52:24 +00001549{
1550 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001551
Greg Clayton2860ba92011-01-23 19:58:49 +00001552 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1553
Greg Clayton68ca8232011-01-25 02:58:48 +00001554 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001555 const bool is_running = m_gdb_comm.IsRunning();
1556 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001557 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001558 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001559 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001560 is_running);
1561
Greg Clayton2860ba92011-01-23 19:58:49 +00001562 if (discard_thread_plans)
1563 {
1564 if (log)
1565 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1566 m_thread_list.DiscardThreadPlans();
1567 }
1568 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001569 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001570 if (catch_stop_event)
1571 {
1572 if (log)
1573 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1574 PausePrivateStateThread();
1575 paused_private_state_thread = true;
1576 }
1577
Greg Clayton4fb400f2010-09-27 21:07:38 +00001578 bool timed_out = false;
1579 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001580
Greg Clayton05e4d972012-03-29 01:55:41 +00001581 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001582 {
1583 if (timed_out)
1584 error.SetErrorString("timed out sending interrupt packet");
1585 else
1586 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001587 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001588 ResumePrivateStateThread();
1589 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001590 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001591
Greg Clayton72e1c782011-01-22 23:43:18 +00001592 if (catch_stop_event)
1593 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001594 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001595 TimeValue timeout_time;
1596 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001597 timeout_time.OffsetWithSeconds(5);
1598 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001599
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001600 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001601 if (log)
1602 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001603
Greg Clayton2860ba92011-01-23 19:58:49 +00001604 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001605 error.SetErrorString("unable to verify target stopped");
1606 }
1607
Greg Clayton68ca8232011-01-25 02:58:48 +00001608 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001609 {
1610 if (log)
1611 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001612 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001613 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001614 }
Chris Lattner24943d22010-06-08 16:52:24 +00001615 return error;
1616}
1617
Greg Clayton4fb400f2010-09-27 21:07:38 +00001618Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001619ProcessGDBRemote::WillDetach ()
1620{
Greg Clayton2860ba92011-01-23 19:58:49 +00001621 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1622 if (log)
1623 log->Printf ("ProcessGDBRemote::WillDetach()");
1624
Greg Clayton72e1c782011-01-22 23:43:18 +00001625 bool discard_thread_plans = true;
1626 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001627 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001628 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001629}
1630
1631Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001632ProcessGDBRemote::DoDetach()
1633{
1634 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001635 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001636 if (log)
1637 log->Printf ("ProcessGDBRemote::DoDetach()");
1638
1639 DisableAllBreakpointSites ();
1640
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001641 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001642
Greg Clayton516f0842012-04-11 00:24:49 +00001643 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001644 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001645 {
Greg Clayton516f0842012-04-11 00:24:49 +00001646 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001647 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1648 else
1649 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001650 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001651 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001652 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001653
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001654 SetPrivateState (eStateDetached);
1655 ResumePrivateStateThread();
1656
1657 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001658 return error;
1659}
Chris Lattner24943d22010-06-08 16:52:24 +00001660
1661Error
1662ProcessGDBRemote::DoDestroy ()
1663{
1664 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001665 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001666 if (log)
1667 log->Printf ("ProcessGDBRemote::DoDestroy()");
1668
1669 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001670 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001671 {
Jim Ingham8226e942011-10-28 01:11:35 +00001672 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001673 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001674
1675 StringExtractorGDBRemote response;
1676 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001677 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001678 {
1679 char packet_cmd = response.GetChar(0);
1680
1681 if (packet_cmd == 'W' || packet_cmd == 'X')
1682 {
Greg Clayton06709002011-12-06 04:51:14 +00001683 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001684 ClearThreadIDList ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001685 SetExitStatus(response.GetHexU8(), NULL);
1686 }
1687 }
1688 else
1689 {
1690 SetExitStatus(SIGABRT, NULL);
1691 //error.SetErrorString("kill packet failed");
1692 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001693 }
1694 }
Chris Lattner24943d22010-06-08 16:52:24 +00001695 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001696 KillDebugserverProcess ();
1697 return error;
1698}
1699
Chris Lattner24943d22010-06-08 16:52:24 +00001700//------------------------------------------------------------------
1701// Process Queries
1702//------------------------------------------------------------------
1703
1704bool
1705ProcessGDBRemote::IsAlive ()
1706{
Greg Clayton58e844b2010-12-08 05:08:21 +00001707 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001708}
1709
1710addr_t
1711ProcessGDBRemote::GetImageInfoAddress()
1712{
Greg Clayton516f0842012-04-11 00:24:49 +00001713 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001714}
1715
Chris Lattner24943d22010-06-08 16:52:24 +00001716//------------------------------------------------------------------
1717// Process Memory
1718//------------------------------------------------------------------
1719size_t
1720ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1721{
1722 if (size > m_max_memory_size)
1723 {
1724 // Keep memory read sizes down to a sane limit. This function will be
1725 // called multiple times in order to complete the task by
1726 // lldb_private::Process so it is ok to do this.
1727 size = m_max_memory_size;
1728 }
1729
1730 char packet[64];
1731 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1732 assert (packet_len + 1 < sizeof(packet));
1733 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001734 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001735 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001736 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001737 {
1738 error.Clear();
1739 return response.GetHexBytes(buf, size, '\xdd');
1740 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001741 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001742 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001743 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001744 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1745 else
1746 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1747 }
1748 else
1749 {
1750 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1751 }
1752 return 0;
1753}
1754
1755size_t
1756ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1757{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001758 if (size > m_max_memory_size)
1759 {
1760 // Keep memory read sizes down to a sane limit. This function will be
1761 // called multiple times in order to complete the task by
1762 // lldb_private::Process so it is ok to do this.
1763 size = m_max_memory_size;
1764 }
1765
Chris Lattner24943d22010-06-08 16:52:24 +00001766 StreamString packet;
1767 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001768 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001769 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001770 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001771 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001772 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001773 {
1774 error.Clear();
1775 return size;
1776 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001777 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001778 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001779 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001780 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1781 else
1782 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1783 }
1784 else
1785 {
1786 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1787 }
1788 return 0;
1789}
1790
1791lldb::addr_t
1792ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1793{
Greg Clayton989816b2011-05-14 01:50:35 +00001794 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1795
Greg Clayton2f085c62011-05-15 01:25:55 +00001796 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001797 switch (supported)
1798 {
1799 case eLazyBoolCalculate:
1800 case eLazyBoolYes:
1801 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1802 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1803 return allocated_addr;
1804
1805 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001806 // Call mmap() to create memory in the inferior..
1807 unsigned prot = 0;
1808 if (permissions & lldb::ePermissionsReadable)
1809 prot |= eMmapProtRead;
1810 if (permissions & lldb::ePermissionsWritable)
1811 prot |= eMmapProtWrite;
1812 if (permissions & lldb::ePermissionsExecutable)
1813 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001814
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001815 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1816 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1817 m_addr_to_mmap_size[allocated_addr] = size;
1818 else
1819 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001820 break;
1821 }
1822
Chris Lattner24943d22010-06-08 16:52:24 +00001823 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001824 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001825 else
1826 error.Clear();
1827 return allocated_addr;
1828}
1829
1830Error
Greg Claytona9385532011-11-18 07:03:08 +00001831ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1832 MemoryRegionInfo &region_info)
1833{
1834
1835 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1836 return error;
1837}
1838
1839Error
Chris Lattner24943d22010-06-08 16:52:24 +00001840ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1841{
1842 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001843 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1844
1845 switch (supported)
1846 {
1847 case eLazyBoolCalculate:
1848 // We should never be deallocating memory without allocating memory
1849 // first so we should never get eLazyBoolCalculate
1850 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1851 break;
1852
1853 case eLazyBoolYes:
1854 if (!m_gdb_comm.DeallocateMemory (addr))
1855 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1856 break;
1857
1858 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001859 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001860 {
1861 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001862 if (pos != m_addr_to_mmap_size.end() &&
1863 InferiorCallMunmap(this, addr, pos->second))
1864 m_addr_to_mmap_size.erase (pos);
1865 else
1866 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001867 }
1868 break;
1869 }
1870
Chris Lattner24943d22010-06-08 16:52:24 +00001871 return error;
1872}
1873
1874
1875//------------------------------------------------------------------
1876// Process STDIO
1877//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001878size_t
1879ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1880{
1881 if (m_stdio_communication.IsConnected())
1882 {
1883 ConnectionStatus status;
1884 m_stdio_communication.Write(src, src_len, status, NULL);
1885 }
1886 return 0;
1887}
1888
1889Error
1890ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1891{
1892 Error error;
1893 assert (bp_site != NULL);
1894
Greg Claytone005f2c2010-11-06 01:53:30 +00001895 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001896 user_id_t site_id = bp_site->GetID();
1897 const addr_t addr = bp_site->GetLoadAddress();
1898 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001899 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001900
1901 if (bp_site->IsEnabled())
1902 {
1903 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001904 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 +00001905 return error;
1906 }
1907 else
1908 {
1909 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1910
1911 if (bp_site->HardwarePreferred())
1912 {
1913 // Try and set hardware breakpoint, and if that fails, fall through
1914 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001915 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001916 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001917 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001918 {
1919 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001920 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001921 return error;
1922 }
Chris Lattner24943d22010-06-08 16:52:24 +00001923 }
1924 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001925
1926 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001927 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001928 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1929 {
1930 bp_site->SetEnabled(true);
1931 bp_site->SetType (BreakpointSite::eExternal);
1932 return error;
1933 }
Chris Lattner24943d22010-06-08 16:52:24 +00001934 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001935
1936 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001937 }
1938
1939 if (log)
1940 {
1941 const char *err_string = error.AsCString();
1942 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1943 bp_site->GetLoadAddress(),
1944 err_string ? err_string : "NULL");
1945 }
1946 // We shouldn't reach here on a successful breakpoint enable...
1947 if (error.Success())
1948 error.SetErrorToGenericError();
1949 return error;
1950}
1951
1952Error
1953ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1954{
1955 Error error;
1956 assert (bp_site != NULL);
1957 addr_t addr = bp_site->GetLoadAddress();
1958 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001959 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001960 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001961 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001962
1963 if (bp_site->IsEnabled())
1964 {
1965 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1966
Greg Claytonb72d0f02011-04-12 05:54:46 +00001967 BreakpointSite::Type bp_type = bp_site->GetType();
1968 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001969 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001970 case BreakpointSite::eSoftware:
1971 error = DisableSoftwareBreakpoint (bp_site);
1972 break;
1973
1974 case BreakpointSite::eHardware:
1975 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1976 error.SetErrorToGenericError();
1977 break;
1978
1979 case BreakpointSite::eExternal:
1980 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1981 error.SetErrorToGenericError();
1982 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001983 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001984 if (error.Success())
1985 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001986 }
1987 else
1988 {
1989 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001990 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 +00001991 return error;
1992 }
1993
1994 if (error.Success())
1995 error.SetErrorToGenericError();
1996 return error;
1997}
1998
Johnny Chen21900fb2011-09-06 22:38:36 +00001999// Pre-requisite: wp != NULL.
2000static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002001GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002002{
2003 assert(wp);
2004 bool watch_read = wp->WatchpointRead();
2005 bool watch_write = wp->WatchpointWrite();
2006
2007 // watch_read and watch_write cannot both be false.
2008 assert(watch_read || watch_write);
2009 if (watch_read && watch_write)
2010 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002011 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002012 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002013 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002014 return eWatchpointWrite;
2015}
2016
Chris Lattner24943d22010-06-08 16:52:24 +00002017Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002018ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002019{
2020 Error error;
2021 if (wp)
2022 {
2023 user_id_t watchID = wp->GetID();
2024 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002025 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002026 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002027 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002028 if (wp->IsEnabled())
2029 {
2030 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002031 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002032 return error;
2033 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002034
2035 GDBStoppointType type = GetGDBStoppointType(wp);
2036 // Pass down an appropriate z/Z packet...
2037 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002038 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002039 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2040 {
2041 wp->SetEnabled(true);
2042 return error;
2043 }
2044 else
2045 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002046 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002047 else
2048 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002049 }
2050 else
2051 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002052 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002053 }
2054 if (error.Success())
2055 error.SetErrorToGenericError();
2056 return error;
2057}
2058
2059Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002060ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002061{
2062 Error error;
2063 if (wp)
2064 {
2065 user_id_t watchID = wp->GetID();
2066
Greg Claytone005f2c2010-11-06 01:53:30 +00002067 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002068
2069 addr_t addr = wp->GetLoadAddress();
2070 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002071 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002072
Johnny Chen21900fb2011-09-06 22:38:36 +00002073 if (!wp->IsEnabled())
2074 {
2075 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002076 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002077 return error;
2078 }
2079
Chris Lattner24943d22010-06-08 16:52:24 +00002080 if (wp->IsHardware())
2081 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002082 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002083 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002084 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2085 {
2086 wp->SetEnabled(false);
2087 return error;
2088 }
2089 else
2090 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002091 }
2092 // TODO: clear software watchpoints if we implement them
2093 }
2094 else
2095 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002096 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002097 }
2098 if (error.Success())
2099 error.SetErrorToGenericError();
2100 return error;
2101}
2102
2103void
2104ProcessGDBRemote::Clear()
2105{
2106 m_flags = 0;
2107 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002108}
2109
2110Error
2111ProcessGDBRemote::DoSignal (int signo)
2112{
2113 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002114 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002115 if (log)
2116 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2117
2118 if (!m_gdb_comm.SendAsyncSignal (signo))
2119 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2120 return error;
2121}
2122
Chris Lattner24943d22010-06-08 16:52:24 +00002123Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002124ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2125{
2126 ProcessLaunchInfo launch_info;
2127 return StartDebugserverProcess(debugserver_url, launch_info);
2128}
2129
2130Error
2131ProcessGDBRemote::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 +00002132{
2133 Error error;
2134 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2135 {
2136 // If we locate debugserver, keep that located version around
2137 static FileSpec g_debugserver_file_spec;
2138
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002139 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002140 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002141 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002142
2143 // Always check to see if we have an environment override for the path
2144 // to the debugserver to use and use it if we do.
2145 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2146 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002147 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002148 else
2149 debugserver_file_spec = g_debugserver_file_spec;
2150 bool debugserver_exists = debugserver_file_spec.Exists();
2151 if (!debugserver_exists)
2152 {
2153 // The debugserver binary is in the LLDB.framework/Resources
2154 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002155 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002156 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002157 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002158 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002159 if (debugserver_exists)
2160 {
2161 g_debugserver_file_spec = debugserver_file_spec;
2162 }
2163 else
2164 {
2165 g_debugserver_file_spec.Clear();
2166 debugserver_file_spec.Clear();
2167 }
Chris Lattner24943d22010-06-08 16:52:24 +00002168 }
2169 }
2170
2171 if (debugserver_exists)
2172 {
2173 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2174
2175 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002176
Greg Claytone005f2c2010-11-06 01:53:30 +00002177 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002178
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002179 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002180 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002181
Chris Lattner24943d22010-06-08 16:52:24 +00002182 // Start args with "debugserver /file/path -r --"
2183 debugserver_args.AppendArgument(debugserver_path);
2184 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002185 // use native registers, not the GDB registers
2186 debugserver_args.AppendArgument("--native-regs");
2187 // make debugserver run in its own session so signals generated by
2188 // special terminal key sequences (^C) don't affect debugserver
2189 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002190
Chris Lattner24943d22010-06-08 16:52:24 +00002191 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2192 if (env_debugserver_log_file)
2193 {
2194 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2195 debugserver_args.AppendArgument(arg_cstr);
2196 }
2197
2198 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2199 if (env_debugserver_log_flags)
2200 {
2201 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2202 debugserver_args.AppendArgument(arg_cstr);
2203 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002204// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002205// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002206
Greg Claytonb72d0f02011-04-12 05:54:46 +00002207 // We currently send down all arguments, attach pids, or attach
2208 // process names in dedicated GDB server packets, so we don't need
2209 // to pass them as arguments. This is currently because of all the
2210 // things we need to setup prior to launching: the environment,
2211 // current working dir, file actions, etc.
2212#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002213 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002214 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002215 {
Greg Claytona2f74232011-02-24 22:24:29 +00002216 // Terminate the debugserver args so we can now append the inferior args
2217 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002218
Greg Claytona2f74232011-02-24 22:24:29 +00002219 for (int i = 0; inferior_argv[i] != NULL; ++i)
2220 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002221 }
2222 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2223 {
2224 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2225 debugserver_args.AppendArgument (arg_cstr);
2226 }
2227 else if (attach_name && attach_name[0])
2228 {
2229 if (wait_for_launch)
2230 debugserver_args.AppendArgument ("--waitfor");
2231 else
2232 debugserver_args.AppendArgument ("--attach");
2233 debugserver_args.AppendArgument (attach_name);
2234 }
Chris Lattner24943d22010-06-08 16:52:24 +00002235#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002236
2237 ProcessLaunchInfo::FileAction file_action;
2238
2239 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2240 // to "/dev/null" if we run into any problems.
2241 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002242 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002243 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002244 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002245 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002246 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002247
2248 if (log)
2249 {
2250 StreamString strm;
2251 debugserver_args.Dump (&strm);
2252 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2253 }
2254
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002255 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2256 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002257
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002258 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002259
Greg Claytonb72d0f02011-04-12 05:54:46 +00002260 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002261 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002262 else
Chris Lattner24943d22010-06-08 16:52:24 +00002263 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2264
2265 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002266 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002267 }
2268 else
2269 {
Greg Clayton9c236732011-10-26 00:56:27 +00002270 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002271 }
2272
2273 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2274 StartAsyncThread ();
2275 }
2276 return error;
2277}
2278
2279bool
2280ProcessGDBRemote::MonitorDebugserverProcess
2281(
2282 void *callback_baton,
2283 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002284 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002285 int signo, // Zero for no signal
2286 int exit_status // Exit value of process if signal is zero
2287)
2288{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002289 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2290 // and might not exist anymore, so we need to carefully try to get the
2291 // target for this process first since we have a race condition when
2292 // we are done running between getting the notice that the inferior
2293 // process has died and the debugserver that was debugging this process.
2294 // In our test suite, we are also continually running process after
2295 // process, so we must be very careful to make sure:
2296 // 1 - process object hasn't been deleted already
2297 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002298
2299 // "debugserver_pid" argument passed in is the process ID for
2300 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002301 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002302
Greg Clayton75ccf502010-08-21 02:22:51 +00002303 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002304
Greg Clayton1c4642c2011-11-16 05:37:56 +00002305 // Get a shared pointer to the target that has a matching process pointer.
2306 // This target could be gone, or the target could already have a new process
2307 // object inside of it
2308 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2309
Greg Clayton72e1c782011-01-22 23:43:18 +00002310 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002311 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 +00002312
Greg Clayton1c4642c2011-11-16 05:37:56 +00002313 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002314 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002315 // We found a process in a target that matches, but another thread
2316 // might be in the process of launching a new process that will
2317 // soon replace it, so get a shared pointer to the process so we
2318 // can keep it alive.
2319 ProcessSP process_sp (target_sp->GetProcessSP());
2320 // Now we have a shared pointer to the process that can't go away on us
2321 // so we now make sure it was the same as the one passed in, and also make
2322 // sure that our previous "process *" didn't get deleted and have a new
2323 // "process *" created in its place with the same pointer. To verify this
2324 // we make sure the process has our debugserver process ID. If we pass all
2325 // of these tests, then we are sure that this process is the one we were
2326 // looking for.
2327 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002328 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002329 // Sleep for a half a second to make sure our inferior process has
2330 // time to set its exit status before we set it incorrectly when
2331 // both the debugserver and the inferior process shut down.
2332 usleep (500000);
2333 // If our process hasn't yet exited, debugserver might have died.
2334 // If the process did exit, the we are reaping it.
2335 const StateType state = process->GetState();
2336
2337 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2338 state != eStateInvalid &&
2339 state != eStateUnloaded &&
2340 state != eStateExited &&
2341 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002342 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002343 char error_str[1024];
2344 if (signo)
2345 {
2346 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2347 if (signal_cstr)
2348 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2349 else
2350 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2351 }
Chris Lattner24943d22010-06-08 16:52:24 +00002352 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002353 {
2354 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2355 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002356
Greg Clayton1c4642c2011-11-16 05:37:56 +00002357 process->SetExitStatus (-1, error_str);
2358 }
2359 // Debugserver has exited we need to let our ProcessGDBRemote
2360 // know that it no longer has a debugserver instance
2361 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002362 }
Chris Lattner24943d22010-06-08 16:52:24 +00002363 }
2364 return true;
2365}
2366
2367void
2368ProcessGDBRemote::KillDebugserverProcess ()
2369{
2370 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2371 {
2372 ::kill (m_debugserver_pid, SIGINT);
2373 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2374 }
2375}
2376
2377void
2378ProcessGDBRemote::Initialize()
2379{
2380 static bool g_initialized = false;
2381
2382 if (g_initialized == false)
2383 {
2384 g_initialized = true;
2385 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2386 GetPluginDescriptionStatic(),
2387 CreateInstance);
2388
2389 Log::Callbacks log_callbacks = {
2390 ProcessGDBRemoteLog::DisableLog,
2391 ProcessGDBRemoteLog::EnableLog,
2392 ProcessGDBRemoteLog::ListLogCategories
2393 };
2394
2395 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2396 }
2397}
2398
2399bool
Chris Lattner24943d22010-06-08 16:52:24 +00002400ProcessGDBRemote::StartAsyncThread ()
2401{
Greg Claytone005f2c2010-11-06 01:53:30 +00002402 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002403
2404 if (log)
2405 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2406
2407 // Create a thread that watches our internal state and controls which
2408 // events make it to clients (into the DCProcess event queue).
2409 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002410 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002411}
2412
2413void
2414ProcessGDBRemote::StopAsyncThread ()
2415{
Greg Claytone005f2c2010-11-06 01:53:30 +00002416 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002417
2418 if (log)
2419 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2420
2421 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002422
2423 // This will shut down the async thread.
2424 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002425
2426 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002427 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002428 {
2429 Host::ThreadJoin (m_async_thread, NULL, NULL);
2430 }
2431}
2432
2433
2434void *
2435ProcessGDBRemote::AsyncThread (void *arg)
2436{
2437 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2438
Greg Claytone005f2c2010-11-06 01:53:30 +00002439 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002440 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002441 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002442
2443 Listener listener ("ProcessGDBRemote::AsyncThread");
2444 EventSP event_sp;
2445 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2446 eBroadcastBitAsyncThreadShouldExit;
2447
2448 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2449 {
Greg Claytona2f74232011-02-24 22:24:29 +00002450 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2451
Chris Lattner24943d22010-06-08 16:52:24 +00002452 bool done = false;
2453 while (!done)
2454 {
2455 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002456 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002457 if (listener.WaitForEvent (NULL, event_sp))
2458 {
2459 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002460 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002461 {
Greg Claytona2f74232011-02-24 22:24:29 +00002462 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002463 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 +00002464
Greg Claytona2f74232011-02-24 22:24:29 +00002465 switch (event_type)
2466 {
2467 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002468 {
Greg Claytona2f74232011-02-24 22:24:29 +00002469 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002470
Greg Claytona2f74232011-02-24 22:24:29 +00002471 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002472 {
Greg Claytona2f74232011-02-24 22:24:29 +00002473 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2474 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2475 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002476 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002477
Greg Claytona2f74232011-02-24 22:24:29 +00002478 if (::strstr (continue_cstr, "vAttach") == NULL)
2479 process->SetPrivateState(eStateRunning);
2480 StringExtractorGDBRemote response;
2481 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002482
Greg Claytona2f74232011-02-24 22:24:29 +00002483 switch (stop_state)
2484 {
2485 case eStateStopped:
2486 case eStateCrashed:
2487 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002488 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002489 process->SetPrivateState (stop_state);
2490 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002491
Greg Claytona2f74232011-02-24 22:24:29 +00002492 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002493 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002494 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002495 response.SetFilePos(1);
2496 process->SetExitStatus(response.GetHexU8(), NULL);
2497 done = true;
2498 break;
2499
2500 case eStateInvalid:
2501 process->SetExitStatus(-1, "lost connection");
2502 break;
2503
2504 default:
2505 process->SetPrivateState (stop_state);
2506 break;
2507 }
Chris Lattner24943d22010-06-08 16:52:24 +00002508 }
2509 }
Greg Claytona2f74232011-02-24 22:24:29 +00002510 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002511
Greg Claytona2f74232011-02-24 22:24:29 +00002512 case eBroadcastBitAsyncThreadShouldExit:
2513 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002514 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002515 done = true;
2516 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002517
Greg Claytona2f74232011-02-24 22:24:29 +00002518 default:
2519 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002520 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 +00002521 done = true;
2522 break;
2523 }
2524 }
2525 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2526 {
2527 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2528 {
2529 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002530 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002531 }
Chris Lattner24943d22010-06-08 16:52:24 +00002532 }
2533 }
2534 else
2535 {
2536 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002537 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 +00002538 done = true;
2539 }
2540 }
2541 }
2542
2543 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002544 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002545
2546 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2547 return NULL;
2548}
2549
Chris Lattner24943d22010-06-08 16:52:24 +00002550const char *
2551ProcessGDBRemote::GetDispatchQueueNameForThread
2552(
2553 addr_t thread_dispatch_qaddr,
2554 std::string &dispatch_queue_name
2555)
2556{
2557 dispatch_queue_name.clear();
2558 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2559 {
2560 // Cache the dispatch_queue_offsets_addr value so we don't always have
2561 // to look it up
2562 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2563 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002564 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2565 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002566 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2567 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002568 if (module_sp)
2569 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2570
2571 if (dispatch_queue_offsets_symbol == NULL)
2572 {
Greg Clayton444fe992012-02-26 05:51:37 +00002573 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2574 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002575 if (module_sp)
2576 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2577 }
Chris Lattner24943d22010-06-08 16:52:24 +00002578 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002579 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002580
2581 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2582 return NULL;
2583 }
2584
2585 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002586 DataExtractor data (memory_buffer,
2587 sizeof(memory_buffer),
2588 m_target.GetArchitecture().GetByteOrder(),
2589 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002590
2591 // Excerpt from src/queue_private.h
2592 struct dispatch_queue_offsets_s
2593 {
2594 uint16_t dqo_version;
2595 uint16_t dqo_label;
2596 uint16_t dqo_label_size;
2597 } dispatch_queue_offsets;
2598
2599
2600 Error error;
2601 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2602 {
2603 uint32_t data_offset = 0;
2604 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2605 {
2606 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2607 {
2608 data_offset = 0;
2609 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2610 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2611 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2612 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2613 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2614 dispatch_queue_name.erase (bytes_read);
2615 }
2616 }
2617 }
2618 }
2619 if (dispatch_queue_name.empty())
2620 return NULL;
2621 return dispatch_queue_name.c_str();
2622}
2623
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002624//uint32_t
2625//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2626//{
2627// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2628// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2629// if (m_local_debugserver)
2630// {
2631// return Host::ListProcessesMatchingName (name, matches, pids);
2632// }
2633// else
2634// {
2635// // FIXME: Implement talking to the remote debugserver.
2636// return 0;
2637// }
2638//
2639//}
2640//
Jim Ingham55e01d82011-01-22 01:33:44 +00002641bool
2642ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2643 lldb_private::StoppointCallbackContext *context,
2644 lldb::user_id_t break_id,
2645 lldb::user_id_t break_loc_id)
2646{
2647 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2648 // run so I can stop it if that's what I want to do.
2649 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2650 if (log)
2651 log->Printf("Hit New Thread Notification breakpoint.");
2652 return false;
2653}
2654
2655
2656bool
2657ProcessGDBRemote::StartNoticingNewThreads()
2658{
2659 static const char *bp_names[] =
2660 {
2661 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002662 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002663 "_pthread_start",
2664 NULL
2665 };
2666
2667 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2668 size_t num_bps = m_thread_observation_bps.size();
2669 if (num_bps != 0)
2670 {
2671 for (int i = 0; i < num_bps; i++)
2672 {
2673 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2674 if (break_sp)
2675 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002676 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002677 log->Printf("Enabled noticing new thread breakpoint.");
2678 break_sp->SetEnabled(true);
2679 }
2680 }
2681 }
2682 else
2683 {
2684 for (int i = 0; bp_names[i] != NULL; i++)
2685 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002686 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002687 if (breakpoint)
2688 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002689 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002690 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2691 m_thread_observation_bps.push_back(breakpoint->GetID());
2692 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2693 }
2694 else
2695 {
2696 if (log)
2697 log->Printf("Failed to create new thread notification breakpoint.");
2698 return false;
2699 }
2700 }
2701 }
2702
2703 return true;
2704}
2705
2706bool
2707ProcessGDBRemote::StopNoticingNewThreads()
2708{
Jim Inghamff276fe2011-02-08 05:19:01 +00002709 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002710 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002711 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002712 size_t num_bps = m_thread_observation_bps.size();
2713 if (num_bps != 0)
2714 {
2715 for (int i = 0; i < num_bps; i++)
2716 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002717
2718 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2719 if (break_sp)
2720 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002721 break_sp->SetEnabled(false);
2722 }
2723 }
2724 }
2725 return true;
2726}
2727
2728