blob: e207ebd9153add578005519eba8fc49c15100d55 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Greg Clayton989816b2011-05-14 01:50:35 +000014#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000016#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000017#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000018
19// C++ Includes
20#include <algorithm>
21#include <map>
22
23// Other libraries and framework includes
24
Johnny Chenecd4feb2011-10-14 00:42:25 +000025#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000026#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Core/ArchSpec.h"
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000030#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Core/InputReader.h"
32#include "lldb/Core/Module.h"
33#include "lldb/Core/PluginManager.h"
34#include "lldb/Core/State.h"
35#include "lldb/Core/StreamString.h"
36#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000037#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Host/TimeValue.h"
39#include "lldb/Symbol/ObjectFile.h"
40#include "lldb/Target/DynamicLoader.h"
41#include "lldb/Target/Target.h"
42#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000043#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000044#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045
46// Project includes
47#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000048#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000049#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000050#include "GDBRemoteRegisterContext.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000054#include "StopInfoMachException.h"
55
Greg Clayton451fa822012-04-09 22:46:21 +000056namespace lldb
57{
58 // Provide a function that can easily dump the packet history if we know a
59 // ProcessGDBRemote * value (which we can get from logs or from debugging).
60 // We need the function in the lldb namespace so it makes it into the final
61 // executable since the LLDB shared library only exports stuff in the lldb
62 // namespace. This allows you to attach with a debugger and call this
63 // function and get the packet history dumped to a file.
64 void
65 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
66 {
67 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (path);
68 }
69};
Chris Lattner24943d22010-06-08 16:52:24 +000070
Chris Lattner24943d22010-06-08 16:52:24 +000071
72#define DEBUGSERVER_BASENAME "debugserver"
73using namespace lldb;
74using namespace lldb_private;
75
Jim Inghamf9600482011-03-29 21:45:47 +000076static bool rand_initialized = false;
77
Chris Lattner24943d22010-06-08 16:52:24 +000078static inline uint16_t
79get_random_port ()
80{
Jim Inghamf9600482011-03-29 21:45:47 +000081 if (!rand_initialized)
82 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000083 time_t seed = time(NULL);
84
Jim Inghamf9600482011-03-29 21:45:47 +000085 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000086 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000087 }
Stephen Wilson50daf772011-03-25 18:16:28 +000088 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000089}
90
91
92const char *
93ProcessGDBRemote::GetPluginNameStatic()
94{
Greg Claytonb1888f22011-03-19 01:12:21 +000095 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000096}
97
98const char *
99ProcessGDBRemote::GetPluginDescriptionStatic()
100{
101 return "GDB Remote protocol based debugging plug-in.";
102}
103
104void
105ProcessGDBRemote::Terminate()
106{
107 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
108}
109
110
Greg Clayton46c9a352012-02-09 06:16:32 +0000111lldb::ProcessSP
112ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000113{
Greg Clayton46c9a352012-02-09 06:16:32 +0000114 lldb::ProcessSP process_sp;
115 if (crash_file_path == NULL)
116 process_sp.reset (new ProcessGDBRemote (target, listener));
117 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000118}
119
120bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000121ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000122{
Greg Clayton61ddf562011-10-21 21:41:45 +0000123 if (plugin_specified_by_name)
124 return true;
125
Chris Lattner24943d22010-06-08 16:52:24 +0000126 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000127 Module *exe_module = target.GetExecutableModulePointer();
128 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000129 {
130 ObjectFile *exe_objfile = exe_module->GetObjectFile();
131 // We can't debug core files...
132 switch (exe_objfile->GetType())
133 {
134 case ObjectFile::eTypeInvalid:
135 case ObjectFile::eTypeCoreFile:
136 case ObjectFile::eTypeDebugInfo:
137 case ObjectFile::eTypeObjectFile:
138 case ObjectFile::eTypeSharedLibrary:
139 case ObjectFile::eTypeStubLibrary:
140 return false;
141 case ObjectFile::eTypeExecutable:
142 case ObjectFile::eTypeDynamicLinker:
143 case ObjectFile::eTypeUnknown:
144 break;
145 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000146 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000147 }
Jim Ingham7508e732010-08-09 23:31:02 +0000148 // However, if there is no executable module, we return true since we might be preparing to attach.
149 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000150}
151
152//----------------------------------------------------------------------
153// ProcessGDBRemote constructor
154//----------------------------------------------------------------------
155ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
156 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000157 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000158 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000159 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000160 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000161 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000162 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000163 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000164 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000165 m_thread_ids (),
166 m_thread_ids_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonc1f45872011-02-12 06:28:37 +0000167 m_continue_c_tids (),
168 m_continue_C_tids (),
169 m_continue_s_tids (),
170 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000171 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000172 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000173 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000174 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000175{
Greg Claytonff39f742011-04-01 00:29:43 +0000176 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
177 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
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 ();
707 m_gdb_comm.GetHostInfo ();
708 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000709 return error;
710}
711
712void
713ProcessGDBRemote::DidLaunchOrAttach ()
714{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000715 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
716 if (log)
717 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000718 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000719 {
720 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
721
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000722 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000723
Chris Lattner24943d22010-06-08 16:52:24 +0000724 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000725
Greg Claytoncb8977d2011-03-23 00:09:55 +0000726 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
727 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000728 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000729 ArchSpec &target_arch = GetTarget().GetArchitecture();
730
731 if (target_arch.IsValid())
732 {
733 // If the remote host is ARM and we have apple as the vendor, then
734 // ARM executables and shared libraries can have mixed ARM architectures.
735 // You can have an armv6 executable, and if the host is armv7, then the
736 // system will load the best possible architecture for all shared libraries
737 // it has, so we really need to take the remote host architecture as our
738 // defacto architecture in this case.
739
740 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
741 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
742 {
743 target_arch = gdb_remote_arch;
744 }
745 else
746 {
747 // Fill in what is missing in the triple
748 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
749 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000750 if (target_triple.getVendorName().size() == 0)
751 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000752 target_triple.setVendor (remote_triple.getVendor());
753
Greg Clayton2f085c62011-05-15 01:25:55 +0000754 if (target_triple.getOSName().size() == 0)
755 {
756 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000757
Greg Clayton2f085c62011-05-15 01:25:55 +0000758 if (target_triple.getEnvironmentName().size() == 0)
759 target_triple.setEnvironment (remote_triple.getEnvironment());
760 }
761 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000762 }
763 }
764 else
765 {
766 // The target doesn't have a valid architecture yet, set it from
767 // the architecture we got from the remote GDB server
768 target_arch = gdb_remote_arch;
769 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000770 }
Chris Lattner24943d22010-06-08 16:52:24 +0000771 }
772}
773
774void
775ProcessGDBRemote::DidLaunch ()
776{
777 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000778}
779
780Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000781ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000782{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000783 ProcessAttachInfo attach_info;
784 return DoAttachToProcessWithID(attach_pid, attach_info);
785}
786
787Error
788ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
789{
Chris Lattner24943d22010-06-08 16:52:24 +0000790 Error error;
791 // Clear out and clean up from any current state
792 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000793 if (attach_pid != LLDB_INVALID_PROCESS_ID)
794 {
Greg Claytona2f74232011-02-24 22:24:29 +0000795 // Make sure we aren't already connected?
796 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000797 {
Greg Claytona2f74232011-02-24 22:24:29 +0000798 char host_port[128];
799 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
800 char connect_url[128];
801 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000802
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000803 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000804
805 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000806 {
Greg Claytona2f74232011-02-24 22:24:29 +0000807 const char *error_string = error.AsCString();
808 if (error_string == NULL)
809 error_string = "unable to launch " DEBUGSERVER_BASENAME;
810
811 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000812 }
Greg Claytona2f74232011-02-24 22:24:29 +0000813 else
814 {
815 error = ConnectToDebugserver (connect_url);
816 }
817 }
818
819 if (error.Success())
820 {
821 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000822 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000823 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000824 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000825 }
826 }
Chris Lattner24943d22010-06-08 16:52:24 +0000827 return error;
828}
829
830size_t
831ProcessGDBRemote::AttachInputReaderCallback
832(
833 void *baton,
834 InputReader *reader,
835 lldb::InputReaderAction notification,
836 const char *bytes,
837 size_t bytes_len
838)
839{
840 if (notification == eInputReaderGotToken)
841 {
842 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
843 if (gdb_process->m_waiting_for_attach)
844 gdb_process->m_waiting_for_attach = false;
845 reader->SetIsDone(true);
846 return 1;
847 }
848 return 0;
849}
850
851Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000852ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000853{
854 Error error;
855 // Clear out and clean up from any current state
856 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000857
Chris Lattner24943d22010-06-08 16:52:24 +0000858 if (process_name && process_name[0])
859 {
Greg Claytona2f74232011-02-24 22:24:29 +0000860 // Make sure we aren't already connected?
861 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000862 {
Greg Claytona2f74232011-02-24 22:24:29 +0000863 char host_port[128];
864 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
865 char connect_url[128];
866 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
867
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000868 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000869 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000870 {
Greg Claytona2f74232011-02-24 22:24:29 +0000871 const char *error_string = error.AsCString();
872 if (error_string == NULL)
873 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000874
Greg Claytona2f74232011-02-24 22:24:29 +0000875 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000876 }
Greg Claytona2f74232011-02-24 22:24:29 +0000877 else
878 {
879 error = ConnectToDebugserver (connect_url);
880 }
881 }
882
883 if (error.Success())
884 {
885 StreamString packet;
886
887 if (wait_for_launch)
888 packet.PutCString("vAttachWait");
889 else
890 packet.PutCString("vAttachName");
891 packet.PutChar(';');
892 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
893
894 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
895
Chris Lattner24943d22010-06-08 16:52:24 +0000896 }
897 }
Chris Lattner24943d22010-06-08 16:52:24 +0000898 return error;
899}
900
Chris Lattner24943d22010-06-08 16:52:24 +0000901
902void
903ProcessGDBRemote::DidAttach ()
904{
Greg Claytone71e2582011-02-04 01:58:07 +0000905 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000906}
907
908Error
909ProcessGDBRemote::WillResume ()
910{
Greg Claytonc1f45872011-02-12 06:28:37 +0000911 m_continue_c_tids.clear();
912 m_continue_C_tids.clear();
913 m_continue_s_tids.clear();
914 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000915 return Error();
916}
917
918Error
919ProcessGDBRemote::DoResume ()
920{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000921 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000922 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
923 if (log)
924 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000925
926 Listener listener ("gdb-remote.resume-packet-sent");
927 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
928 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000929 StreamString continue_packet;
930 bool continue_packet_error = false;
931 if (m_gdb_comm.HasAnyVContSupport ())
932 {
933 continue_packet.PutCString ("vCont");
934
935 if (!m_continue_c_tids.empty())
936 {
937 if (m_gdb_comm.GetVContSupported ('c'))
938 {
939 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 +0000940 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000941 }
942 else
943 continue_packet_error = true;
944 }
945
946 if (!continue_packet_error && !m_continue_C_tids.empty())
947 {
948 if (m_gdb_comm.GetVContSupported ('C'))
949 {
950 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 +0000951 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000952 }
953 else
954 continue_packet_error = true;
955 }
Greg Claytonb749a262010-12-03 06:02:24 +0000956
Greg Claytonc1f45872011-02-12 06:28:37 +0000957 if (!continue_packet_error && !m_continue_s_tids.empty())
958 {
959 if (m_gdb_comm.GetVContSupported ('s'))
960 {
961 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 +0000962 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000963 }
964 else
965 continue_packet_error = true;
966 }
967
968 if (!continue_packet_error && !m_continue_S_tids.empty())
969 {
970 if (m_gdb_comm.GetVContSupported ('S'))
971 {
972 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 +0000973 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000974 }
975 else
976 continue_packet_error = true;
977 }
978
979 if (continue_packet_error)
980 continue_packet.GetString().clear();
981 }
982 else
983 continue_packet_error = true;
984
985 if (continue_packet_error)
986 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000987 // Either no vCont support, or we tried to use part of the vCont
988 // packet that wasn't supported by the remote GDB server.
989 // We need to try and make a simple packet that can do our continue
990 const size_t num_threads = GetThreadList().GetSize();
991 const size_t num_continue_c_tids = m_continue_c_tids.size();
992 const size_t num_continue_C_tids = m_continue_C_tids.size();
993 const size_t num_continue_s_tids = m_continue_s_tids.size();
994 const size_t num_continue_S_tids = m_continue_S_tids.size();
995 if (num_continue_c_tids > 0)
996 {
997 if (num_continue_c_tids == num_threads)
998 {
999 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001000 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001001 continue_packet.PutChar ('c');
1002 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001003 }
1004 else if (num_continue_c_tids == 1 &&
1005 num_continue_C_tids == 0 &&
1006 num_continue_s_tids == 0 &&
1007 num_continue_S_tids == 0 )
1008 {
1009 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001010 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001011 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001012 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001013 }
1014 }
1015
Greg Claytonde1dd812011-06-24 03:21:43 +00001016 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001017 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001018 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1019 num_continue_C_tids > 0 &&
1020 num_continue_s_tids == 0 &&
1021 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001022 {
1023 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001024 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001025 if (num_continue_C_tids > 1)
1026 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001027 // More that one thread with a signal, yet we don't have
1028 // vCont support and we are being asked to resume each
1029 // thread with a signal, we need to make sure they are
1030 // all the same signal, or we can't issue the continue
1031 // accurately with the current support...
1032 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001033 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001034 continue_packet_error = false;
1035 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1036 {
1037 if (m_continue_C_tids[i].second != continue_signo)
1038 continue_packet_error = true;
1039 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001040 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001041 if (!continue_packet_error)
1042 m_gdb_comm.SetCurrentThreadForRun (-1);
1043 }
1044 else
1045 {
1046 // Set the continue thread ID
1047 continue_packet_error = false;
1048 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001049 }
1050 if (!continue_packet_error)
1051 {
1052 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001053 continue_packet.Printf("C%2.2x", continue_signo);
1054 }
1055 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001056 }
1057
Greg Claytonde1dd812011-06-24 03:21:43 +00001058 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001059 {
1060 if (num_continue_s_tids == num_threads)
1061 {
1062 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001063 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001064 continue_packet.PutChar ('s');
1065 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001066 }
1067 else if (num_continue_c_tids == 0 &&
1068 num_continue_C_tids == 0 &&
1069 num_continue_s_tids == 1 &&
1070 num_continue_S_tids == 0 )
1071 {
1072 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001073 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001074 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001075 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001076 }
1077 }
1078
1079 if (!continue_packet_error && num_continue_S_tids > 0)
1080 {
1081 if (num_continue_S_tids == num_threads)
1082 {
1083 const int step_signo = m_continue_S_tids.front().second;
1084 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001085 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001086 if (num_continue_S_tids > 1)
1087 {
1088 for (size_t i=1; i<num_threads; ++i)
1089 {
1090 if (m_continue_S_tids[i].second != step_signo)
1091 continue_packet_error = true;
1092 }
1093 }
1094 if (!continue_packet_error)
1095 {
1096 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001097 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001098 continue_packet.Printf("S%2.2x", step_signo);
1099 }
1100 }
1101 else if (num_continue_c_tids == 0 &&
1102 num_continue_C_tids == 0 &&
1103 num_continue_s_tids == 0 &&
1104 num_continue_S_tids == 1 )
1105 {
1106 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001107 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001108 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001109 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001110 }
1111 }
1112 }
1113
1114 if (continue_packet_error)
1115 {
1116 error.SetErrorString ("can't make continue packet for this resume");
1117 }
1118 else
1119 {
1120 EventSP event_sp;
1121 TimeValue timeout;
1122 timeout = TimeValue::Now();
1123 timeout.OffsetWithSeconds (5);
1124 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1125
1126 if (listener.WaitForEvent (&timeout, event_sp) == false)
1127 error.SetErrorString("Resume timed out.");
1128 }
Greg Claytonb749a262010-12-03 06:02:24 +00001129 }
1130
Jim Ingham3ae449a2010-11-17 02:32:00 +00001131 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001132}
1133
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001134void
1135ProcessGDBRemote::ClearThreadIDList ()
1136{
1137 Mutex::Locker locker(m_thread_ids_mutex);
1138 m_thread_ids.clear();
1139}
1140
1141bool
1142ProcessGDBRemote::UpdateThreadIDList ()
1143{
1144 Mutex::Locker locker(m_thread_ids_mutex);
1145 bool sequence_mutex_unavailable = false;
1146 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1147 if (sequence_mutex_unavailable)
1148 {
1149#if defined (LLDB_CONFIGURATION_DEBUG)
1150 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1151#endif
1152 return false; // We just didn't get the list
1153 }
1154 return true;
1155}
1156
Greg Claytonae932352012-04-10 00:18:59 +00001157bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001158ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001159{
1160 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001161 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001162 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001163 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001164 // Update the thread list's stop id immediately so we don't recurse into this function.
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001165 Mutex::Locker locker(m_thread_ids_mutex);
1166
1167 size_t num_thread_ids = m_thread_ids.size();
1168 // The "m_thread_ids" thread ID list should always be updated after each stop
1169 // reply packet, but in case it isn't, update it here.
1170 if (num_thread_ids == 0)
1171 {
1172 if (!UpdateThreadIDList ())
1173 return false;
1174 num_thread_ids = m_thread_ids.size();
1175 }
Chris Lattner24943d22010-06-08 16:52:24 +00001176
Greg Clayton37f962e2011-08-22 02:49:39 +00001177 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001178 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001179 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001180 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001181 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001182 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1183 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001184 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001185 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001186 }
Chris Lattner24943d22010-06-08 16:52:24 +00001187 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001188
Greg Claytonae932352012-04-10 00:18:59 +00001189 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001190}
1191
1192
1193StateType
1194ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1195{
Greg Clayton261a18b2011-06-02 22:22:38 +00001196 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001197 const char stop_type = stop_packet.GetChar();
1198 switch (stop_type)
1199 {
1200 case 'T':
1201 case 'S':
1202 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001203 if (GetStopID() == 0)
1204 {
1205 // Our first stop, make sure we have a process ID, and also make
1206 // sure we know about our registers
1207 if (GetID() == LLDB_INVALID_PROCESS_ID)
1208 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001209 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001210 if (pid != LLDB_INVALID_PROCESS_ID)
1211 SetID (pid);
1212 }
1213 BuildDynamicRegisterInfo (true);
1214 }
Chris Lattner24943d22010-06-08 16:52:24 +00001215 // Stop with signal and thread info
1216 const uint8_t signo = stop_packet.GetHexU8();
1217 std::string name;
1218 std::string value;
1219 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001220 std::string reason;
1221 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001222 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001223 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001224 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1225 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001226 ThreadSP thread_sp;
1227
Chris Lattner24943d22010-06-08 16:52:24 +00001228 while (stop_packet.GetNameColonValue(name, value))
1229 {
1230 if (name.compare("metype") == 0)
1231 {
1232 // exception type in big endian hex
1233 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1234 }
1235 else if (name.compare("mecount") == 0)
1236 {
1237 // exception count in big endian hex
1238 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1239 }
1240 else if (name.compare("medata") == 0)
1241 {
1242 // exception data in big endian hex
1243 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1244 }
1245 else if (name.compare("thread") == 0)
1246 {
1247 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001248 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001249 // m_thread_list does have its own mutex, but we need to
1250 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1251 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001252 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001253 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001254 if (!thread_sp)
1255 {
1256 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001257 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001258 m_thread_list.AddThread(thread_sp);
1259 }
Chris Lattner24943d22010-06-08 16:52:24 +00001260 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001261 else if (name.compare("threads") == 0)
1262 {
1263 Mutex::Locker locker(m_thread_ids_mutex);
1264 m_thread_ids.clear();
1265 // A comma separated list of all threads in the current process including
1266 // the thread for this stop reply packet
1267 size_t comma_pos;
1268 lldb::tid_t tid;
1269 while ((comma_pos = value.find(',')) != std::string::npos)
1270 {
1271 value[comma_pos] = '\0';
1272 // thread in big endian hex
1273 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1274 if (tid != LLDB_INVALID_THREAD_ID)
1275 m_thread_ids.push_back (tid);
1276 value.erase(0, comma_pos + 1);
1277
1278 }
1279 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1280 if (tid != LLDB_INVALID_THREAD_ID)
1281 m_thread_ids.push_back (tid);
1282 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001283 else if (name.compare("hexname") == 0)
1284 {
1285 StringExtractor name_extractor;
1286 // Swap "value" over into "name_extractor"
1287 name_extractor.GetStringRef().swap(value);
1288 // Now convert the HEX bytes into a string value
1289 name_extractor.GetHexByteString (value);
1290 thread_name.swap (value);
1291 }
Chris Lattner24943d22010-06-08 16:52:24 +00001292 else if (name.compare("name") == 0)
1293 {
1294 thread_name.swap (value);
1295 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001296 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001297 {
1298 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1299 }
Greg Clayton65611552011-06-04 01:26:29 +00001300 else if (name.compare("reason") == 0)
1301 {
1302 reason.swap(value);
1303 }
1304 else if (name.compare("description") == 0)
1305 {
1306 StringExtractor desc_extractor;
1307 // Swap "value" over into "name_extractor"
1308 desc_extractor.GetStringRef().swap(value);
1309 // Now convert the HEX bytes into a string value
1310 desc_extractor.GetHexByteString (thread_name);
1311 }
Greg Claytona875b642011-01-09 21:07:35 +00001312 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1313 {
1314 // We have a register number that contains an expedited
1315 // register value. Lets supply this register to our thread
1316 // so it won't have to go and read it.
1317 if (thread_sp)
1318 {
1319 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1320
1321 if (reg != UINT32_MAX)
1322 {
1323 StringExtractor reg_value_extractor;
1324 // Swap "value" over into "reg_value_extractor"
1325 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001326 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1327 {
1328 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1329 name.c_str(),
1330 reg,
1331 reg,
1332 reg_value_extractor.GetStringRef().c_str(),
1333 stop_packet.GetStringRef().c_str());
1334 }
Greg Claytona875b642011-01-09 21:07:35 +00001335 }
1336 }
1337 }
Chris Lattner24943d22010-06-08 16:52:24 +00001338 }
Chris Lattner24943d22010-06-08 16:52:24 +00001339
1340 if (thread_sp)
1341 {
1342 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1343
1344 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001345 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001346 if (exc_type != 0)
1347 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001348 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001349
1350 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1351 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001352 exc_data_size,
1353 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001354 exc_data_size >= 2 ? exc_data[1] : 0,
1355 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001356 }
Greg Clayton65611552011-06-04 01:26:29 +00001357 else
Chris Lattner24943d22010-06-08 16:52:24 +00001358 {
Greg Clayton65611552011-06-04 01:26:29 +00001359 bool handled = false;
1360 if (!reason.empty())
1361 {
1362 if (reason.compare("trace") == 0)
1363 {
1364 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1365 handled = true;
1366 }
1367 else if (reason.compare("breakpoint") == 0)
1368 {
1369 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001370 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001371 if (bp_site_sp)
1372 {
1373 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1374 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1375 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1376 if (bp_site_sp->ValidForThisThread (gdb_thread))
1377 {
1378 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1379 handled = true;
1380 }
1381 }
1382
1383 if (!handled)
1384 {
1385 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1386 }
1387 }
1388 else if (reason.compare("trap") == 0)
1389 {
1390 // Let the trap just use the standard signal stop reason below...
1391 }
1392 else if (reason.compare("watchpoint") == 0)
1393 {
1394 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1395 // TODO: locate the watchpoint somehow...
1396 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1397 handled = true;
1398 }
1399 else if (reason.compare("exception") == 0)
1400 {
1401 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1402 handled = true;
1403 }
1404 }
1405
1406 if (signo)
1407 {
1408 if (signo == SIGTRAP)
1409 {
1410 // Currently we are going to assume SIGTRAP means we are either
1411 // hitting a breakpoint or hardware single stepping.
1412 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001413 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001414 if (bp_site_sp)
1415 {
1416 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1417 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1418 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1419 if (bp_site_sp->ValidForThisThread (gdb_thread))
1420 {
1421 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1422 handled = true;
1423 }
1424 }
1425 if (!handled)
1426 {
1427 // TODO: check for breakpoint or trap opcode in case there is a hard
1428 // coded software trap
1429 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1430 handled = true;
1431 }
1432 }
1433 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001434 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001435 }
1436 else
1437 {
Greg Clayton643ee732010-08-04 01:40:35 +00001438 StopInfoSP invalid_stop_info_sp;
1439 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001440 }
Greg Clayton65611552011-06-04 01:26:29 +00001441
1442 if (!description.empty())
1443 {
1444 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1445 if (stop_info_sp)
1446 {
1447 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001448 }
Greg Clayton65611552011-06-04 01:26:29 +00001449 else
1450 {
1451 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1452 }
1453 }
1454 }
Chris Lattner24943d22010-06-08 16:52:24 +00001455 }
1456 return eStateStopped;
1457 }
1458 break;
1459
1460 case 'W':
1461 // process exited
1462 return eStateExited;
1463
1464 default:
1465 break;
1466 }
1467 return eStateInvalid;
1468}
1469
1470void
1471ProcessGDBRemote::RefreshStateAfterStop ()
1472{
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001473 Mutex::Locker locker(m_thread_ids_mutex);
1474 m_thread_ids.clear();
1475 // Set the thread stop info. It might have a "threads" key whose value is
1476 // a list of all thread IDs in the current process, so m_thread_ids might
1477 // get set.
1478 SetThreadStopInfo (m_last_stop_packet);
1479 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1480 if (m_thread_ids.empty())
1481 {
1482 // No, we need to fetch the thread list manually
1483 UpdateThreadIDList();
1484 }
1485
Chris Lattner24943d22010-06-08 16:52:24 +00001486 // Let all threads recover from stopping and do any clean up based
1487 // on the previous thread state (if any).
1488 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001489
Chris Lattner24943d22010-06-08 16:52:24 +00001490}
1491
1492Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001493ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001494{
1495 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001496
Greg Claytona4881d02011-01-22 07:12:45 +00001497 bool timed_out = false;
1498 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001499
1500 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001501 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001502 // We are being asked to halt during an attach. We need to just close
1503 // our file handle and debugserver will go away, and we can be done...
1504 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001505 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001506 else
1507 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001508 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001509 {
1510 if (timed_out)
1511 error.SetErrorString("timed out sending interrupt packet");
1512 else
1513 error.SetErrorString("unknown error sending interrupt packet");
1514 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001515
1516 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001517 }
Chris Lattner24943d22010-06-08 16:52:24 +00001518 return error;
1519}
1520
1521Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001522ProcessGDBRemote::InterruptIfRunning
1523(
1524 bool discard_thread_plans,
1525 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001526 EventSP &stop_event_sp
1527)
Chris Lattner24943d22010-06-08 16:52:24 +00001528{
1529 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001530
Greg Clayton2860ba92011-01-23 19:58:49 +00001531 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1532
Greg Clayton68ca8232011-01-25 02:58:48 +00001533 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001534 const bool is_running = m_gdb_comm.IsRunning();
1535 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001536 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001537 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001538 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001539 is_running);
1540
Greg Clayton2860ba92011-01-23 19:58:49 +00001541 if (discard_thread_plans)
1542 {
1543 if (log)
1544 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1545 m_thread_list.DiscardThreadPlans();
1546 }
1547 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001548 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001549 if (catch_stop_event)
1550 {
1551 if (log)
1552 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1553 PausePrivateStateThread();
1554 paused_private_state_thread = true;
1555 }
1556
Greg Clayton4fb400f2010-09-27 21:07:38 +00001557 bool timed_out = false;
1558 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001559
Greg Clayton05e4d972012-03-29 01:55:41 +00001560 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001561 {
1562 if (timed_out)
1563 error.SetErrorString("timed out sending interrupt packet");
1564 else
1565 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001566 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001567 ResumePrivateStateThread();
1568 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001569 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001570
Greg Clayton72e1c782011-01-22 23:43:18 +00001571 if (catch_stop_event)
1572 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001573 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001574 TimeValue timeout_time;
1575 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001576 timeout_time.OffsetWithSeconds(5);
1577 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001578
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001579 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001580 if (log)
1581 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001582
Greg Clayton2860ba92011-01-23 19:58:49 +00001583 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001584 error.SetErrorString("unable to verify target stopped");
1585 }
1586
Greg Clayton68ca8232011-01-25 02:58:48 +00001587 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001588 {
1589 if (log)
1590 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001591 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001592 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001593 }
Chris Lattner24943d22010-06-08 16:52:24 +00001594 return error;
1595}
1596
Greg Clayton4fb400f2010-09-27 21:07:38 +00001597Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001598ProcessGDBRemote::WillDetach ()
1599{
Greg Clayton2860ba92011-01-23 19:58:49 +00001600 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1601 if (log)
1602 log->Printf ("ProcessGDBRemote::WillDetach()");
1603
Greg Clayton72e1c782011-01-22 23:43:18 +00001604 bool discard_thread_plans = true;
1605 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001606 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001607 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001608}
1609
1610Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001611ProcessGDBRemote::DoDetach()
1612{
1613 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001614 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001615 if (log)
1616 log->Printf ("ProcessGDBRemote::DoDetach()");
1617
1618 DisableAllBreakpointSites ();
1619
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001620 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001621
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001622 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1623 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001624 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001625 if (response_size)
1626 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1627 else
1628 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001629 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001630 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001631 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001632
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001633 SetPrivateState (eStateDetached);
1634 ResumePrivateStateThread();
1635
1636 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001637 return error;
1638}
Chris Lattner24943d22010-06-08 16:52:24 +00001639
1640Error
1641ProcessGDBRemote::DoDestroy ()
1642{
1643 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001644 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001645 if (log)
1646 log->Printf ("ProcessGDBRemote::DoDestroy()");
1647
1648 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001649 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001650 {
Jim Ingham8226e942011-10-28 01:11:35 +00001651 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001652 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001653
1654 StringExtractorGDBRemote response;
1655 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001656 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001657 {
1658 char packet_cmd = response.GetChar(0);
1659
1660 if (packet_cmd == 'W' || packet_cmd == 'X')
1661 {
Greg Clayton06709002011-12-06 04:51:14 +00001662 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001663 ClearThreadIDList ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001664 SetExitStatus(response.GetHexU8(), NULL);
1665 }
1666 }
1667 else
1668 {
1669 SetExitStatus(SIGABRT, NULL);
1670 //error.SetErrorString("kill packet failed");
1671 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001672 }
1673 }
Chris Lattner24943d22010-06-08 16:52:24 +00001674 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001675 KillDebugserverProcess ();
1676 return error;
1677}
1678
Chris Lattner24943d22010-06-08 16:52:24 +00001679//------------------------------------------------------------------
1680// Process Queries
1681//------------------------------------------------------------------
1682
1683bool
1684ProcessGDBRemote::IsAlive ()
1685{
Greg Clayton58e844b2010-12-08 05:08:21 +00001686 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001687}
1688
1689addr_t
1690ProcessGDBRemote::GetImageInfoAddress()
1691{
1692 if (!m_gdb_comm.IsRunning())
1693 {
1694 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001695 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001696 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001697 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001698 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1699 }
1700 }
1701 return LLDB_INVALID_ADDRESS;
1702}
1703
Chris Lattner24943d22010-06-08 16:52:24 +00001704//------------------------------------------------------------------
1705// Process Memory
1706//------------------------------------------------------------------
1707size_t
1708ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1709{
1710 if (size > m_max_memory_size)
1711 {
1712 // Keep memory read sizes down to a sane limit. This function will be
1713 // called multiple times in order to complete the task by
1714 // lldb_private::Process so it is ok to do this.
1715 size = m_max_memory_size;
1716 }
1717
1718 char packet[64];
1719 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1720 assert (packet_len + 1 < sizeof(packet));
1721 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001722 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001723 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001724 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001725 {
1726 error.Clear();
1727 return response.GetHexBytes(buf, size, '\xdd');
1728 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001729 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001730 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001731 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001732 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1733 else
1734 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1735 }
1736 else
1737 {
1738 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1739 }
1740 return 0;
1741}
1742
1743size_t
1744ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1745{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001746 if (size > m_max_memory_size)
1747 {
1748 // Keep memory read sizes down to a sane limit. This function will be
1749 // called multiple times in order to complete the task by
1750 // lldb_private::Process so it is ok to do this.
1751 size = m_max_memory_size;
1752 }
1753
Chris Lattner24943d22010-06-08 16:52:24 +00001754 StreamString packet;
1755 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001756 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001757 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001758 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001759 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001760 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001761 {
1762 error.Clear();
1763 return size;
1764 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001765 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001766 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001767 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001768 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1769 else
1770 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1771 }
1772 else
1773 {
1774 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1775 }
1776 return 0;
1777}
1778
1779lldb::addr_t
1780ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1781{
Greg Clayton989816b2011-05-14 01:50:35 +00001782 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1783
Greg Clayton2f085c62011-05-15 01:25:55 +00001784 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001785 switch (supported)
1786 {
1787 case eLazyBoolCalculate:
1788 case eLazyBoolYes:
1789 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1790 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1791 return allocated_addr;
1792
1793 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001794 // Call mmap() to create memory in the inferior..
1795 unsigned prot = 0;
1796 if (permissions & lldb::ePermissionsReadable)
1797 prot |= eMmapProtRead;
1798 if (permissions & lldb::ePermissionsWritable)
1799 prot |= eMmapProtWrite;
1800 if (permissions & lldb::ePermissionsExecutable)
1801 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001802
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001803 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1804 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1805 m_addr_to_mmap_size[allocated_addr] = size;
1806 else
1807 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001808 break;
1809 }
1810
Chris Lattner24943d22010-06-08 16:52:24 +00001811 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001812 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001813 else
1814 error.Clear();
1815 return allocated_addr;
1816}
1817
1818Error
Greg Claytona9385532011-11-18 07:03:08 +00001819ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1820 MemoryRegionInfo &region_info)
1821{
1822
1823 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1824 return error;
1825}
1826
1827Error
Chris Lattner24943d22010-06-08 16:52:24 +00001828ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1829{
1830 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001831 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1832
1833 switch (supported)
1834 {
1835 case eLazyBoolCalculate:
1836 // We should never be deallocating memory without allocating memory
1837 // first so we should never get eLazyBoolCalculate
1838 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1839 break;
1840
1841 case eLazyBoolYes:
1842 if (!m_gdb_comm.DeallocateMemory (addr))
1843 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1844 break;
1845
1846 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001847 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001848 {
1849 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001850 if (pos != m_addr_to_mmap_size.end() &&
1851 InferiorCallMunmap(this, addr, pos->second))
1852 m_addr_to_mmap_size.erase (pos);
1853 else
1854 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001855 }
1856 break;
1857 }
1858
Chris Lattner24943d22010-06-08 16:52:24 +00001859 return error;
1860}
1861
1862
1863//------------------------------------------------------------------
1864// Process STDIO
1865//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001866size_t
1867ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1868{
1869 if (m_stdio_communication.IsConnected())
1870 {
1871 ConnectionStatus status;
1872 m_stdio_communication.Write(src, src_len, status, NULL);
1873 }
1874 return 0;
1875}
1876
1877Error
1878ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1879{
1880 Error error;
1881 assert (bp_site != NULL);
1882
Greg Claytone005f2c2010-11-06 01:53:30 +00001883 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001884 user_id_t site_id = bp_site->GetID();
1885 const addr_t addr = bp_site->GetLoadAddress();
1886 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001887 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001888
1889 if (bp_site->IsEnabled())
1890 {
1891 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001892 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 +00001893 return error;
1894 }
1895 else
1896 {
1897 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1898
1899 if (bp_site->HardwarePreferred())
1900 {
1901 // Try and set hardware breakpoint, and if that fails, fall through
1902 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001903 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001904 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001905 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001906 {
1907 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001908 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001909 return error;
1910 }
Chris Lattner24943d22010-06-08 16:52:24 +00001911 }
1912 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001913
1914 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001915 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001916 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1917 {
1918 bp_site->SetEnabled(true);
1919 bp_site->SetType (BreakpointSite::eExternal);
1920 return error;
1921 }
Chris Lattner24943d22010-06-08 16:52:24 +00001922 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001923
1924 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001925 }
1926
1927 if (log)
1928 {
1929 const char *err_string = error.AsCString();
1930 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1931 bp_site->GetLoadAddress(),
1932 err_string ? err_string : "NULL");
1933 }
1934 // We shouldn't reach here on a successful breakpoint enable...
1935 if (error.Success())
1936 error.SetErrorToGenericError();
1937 return error;
1938}
1939
1940Error
1941ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1942{
1943 Error error;
1944 assert (bp_site != NULL);
1945 addr_t addr = bp_site->GetLoadAddress();
1946 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001947 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001948 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001949 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001950
1951 if (bp_site->IsEnabled())
1952 {
1953 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1954
Greg Claytonb72d0f02011-04-12 05:54:46 +00001955 BreakpointSite::Type bp_type = bp_site->GetType();
1956 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001957 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001958 case BreakpointSite::eSoftware:
1959 error = DisableSoftwareBreakpoint (bp_site);
1960 break;
1961
1962 case BreakpointSite::eHardware:
1963 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1964 error.SetErrorToGenericError();
1965 break;
1966
1967 case BreakpointSite::eExternal:
1968 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1969 error.SetErrorToGenericError();
1970 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001971 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001972 if (error.Success())
1973 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001974 }
1975 else
1976 {
1977 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001978 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 +00001979 return error;
1980 }
1981
1982 if (error.Success())
1983 error.SetErrorToGenericError();
1984 return error;
1985}
1986
Johnny Chen21900fb2011-09-06 22:38:36 +00001987// Pre-requisite: wp != NULL.
1988static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00001989GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00001990{
1991 assert(wp);
1992 bool watch_read = wp->WatchpointRead();
1993 bool watch_write = wp->WatchpointWrite();
1994
1995 // watch_read and watch_write cannot both be false.
1996 assert(watch_read || watch_write);
1997 if (watch_read && watch_write)
1998 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001999 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002000 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002001 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002002 return eWatchpointWrite;
2003}
2004
Chris Lattner24943d22010-06-08 16:52:24 +00002005Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002006ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002007{
2008 Error error;
2009 if (wp)
2010 {
2011 user_id_t watchID = wp->GetID();
2012 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002013 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002014 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002015 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002016 if (wp->IsEnabled())
2017 {
2018 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002019 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002020 return error;
2021 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002022
2023 GDBStoppointType type = GetGDBStoppointType(wp);
2024 // Pass down an appropriate z/Z packet...
2025 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002026 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002027 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2028 {
2029 wp->SetEnabled(true);
2030 return error;
2031 }
2032 else
2033 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002034 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002035 else
2036 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002037 }
2038 else
2039 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002040 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002041 }
2042 if (error.Success())
2043 error.SetErrorToGenericError();
2044 return error;
2045}
2046
2047Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002048ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002049{
2050 Error error;
2051 if (wp)
2052 {
2053 user_id_t watchID = wp->GetID();
2054
Greg Claytone005f2c2010-11-06 01:53:30 +00002055 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002056
2057 addr_t addr = wp->GetLoadAddress();
2058 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002059 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002060
Johnny Chen21900fb2011-09-06 22:38:36 +00002061 if (!wp->IsEnabled())
2062 {
2063 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002064 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002065 return error;
2066 }
2067
Chris Lattner24943d22010-06-08 16:52:24 +00002068 if (wp->IsHardware())
2069 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002070 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002071 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002072 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2073 {
2074 wp->SetEnabled(false);
2075 return error;
2076 }
2077 else
2078 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002079 }
2080 // TODO: clear software watchpoints if we implement them
2081 }
2082 else
2083 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002084 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002085 }
2086 if (error.Success())
2087 error.SetErrorToGenericError();
2088 return error;
2089}
2090
2091void
2092ProcessGDBRemote::Clear()
2093{
2094 m_flags = 0;
2095 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002096}
2097
2098Error
2099ProcessGDBRemote::DoSignal (int signo)
2100{
2101 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002102 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002103 if (log)
2104 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2105
2106 if (!m_gdb_comm.SendAsyncSignal (signo))
2107 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2108 return error;
2109}
2110
Chris Lattner24943d22010-06-08 16:52:24 +00002111Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002112ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2113{
2114 ProcessLaunchInfo launch_info;
2115 return StartDebugserverProcess(debugserver_url, launch_info);
2116}
2117
2118Error
2119ProcessGDBRemote::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 +00002120{
2121 Error error;
2122 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2123 {
2124 // If we locate debugserver, keep that located version around
2125 static FileSpec g_debugserver_file_spec;
2126
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002127 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002128 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002129 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002130
2131 // Always check to see if we have an environment override for the path
2132 // to the debugserver to use and use it if we do.
2133 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2134 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002135 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002136 else
2137 debugserver_file_spec = g_debugserver_file_spec;
2138 bool debugserver_exists = debugserver_file_spec.Exists();
2139 if (!debugserver_exists)
2140 {
2141 // The debugserver binary is in the LLDB.framework/Resources
2142 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002143 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002144 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002145 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002146 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002147 if (debugserver_exists)
2148 {
2149 g_debugserver_file_spec = debugserver_file_spec;
2150 }
2151 else
2152 {
2153 g_debugserver_file_spec.Clear();
2154 debugserver_file_spec.Clear();
2155 }
Chris Lattner24943d22010-06-08 16:52:24 +00002156 }
2157 }
2158
2159 if (debugserver_exists)
2160 {
2161 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2162
2163 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002164
Greg Claytone005f2c2010-11-06 01:53:30 +00002165 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002166
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002167 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002168 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002169
Chris Lattner24943d22010-06-08 16:52:24 +00002170 // Start args with "debugserver /file/path -r --"
2171 debugserver_args.AppendArgument(debugserver_path);
2172 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002173 // use native registers, not the GDB registers
2174 debugserver_args.AppendArgument("--native-regs");
2175 // make debugserver run in its own session so signals generated by
2176 // special terminal key sequences (^C) don't affect debugserver
2177 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002178
Chris Lattner24943d22010-06-08 16:52:24 +00002179 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2180 if (env_debugserver_log_file)
2181 {
2182 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2183 debugserver_args.AppendArgument(arg_cstr);
2184 }
2185
2186 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2187 if (env_debugserver_log_flags)
2188 {
2189 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2190 debugserver_args.AppendArgument(arg_cstr);
2191 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002192// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002193// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002194
Greg Claytonb72d0f02011-04-12 05:54:46 +00002195 // We currently send down all arguments, attach pids, or attach
2196 // process names in dedicated GDB server packets, so we don't need
2197 // to pass them as arguments. This is currently because of all the
2198 // things we need to setup prior to launching: the environment,
2199 // current working dir, file actions, etc.
2200#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002201 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002202 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002203 {
Greg Claytona2f74232011-02-24 22:24:29 +00002204 // Terminate the debugserver args so we can now append the inferior args
2205 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002206
Greg Claytona2f74232011-02-24 22:24:29 +00002207 for (int i = 0; inferior_argv[i] != NULL; ++i)
2208 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002209 }
2210 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2211 {
2212 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2213 debugserver_args.AppendArgument (arg_cstr);
2214 }
2215 else if (attach_name && attach_name[0])
2216 {
2217 if (wait_for_launch)
2218 debugserver_args.AppendArgument ("--waitfor");
2219 else
2220 debugserver_args.AppendArgument ("--attach");
2221 debugserver_args.AppendArgument (attach_name);
2222 }
Chris Lattner24943d22010-06-08 16:52:24 +00002223#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002224
2225 ProcessLaunchInfo::FileAction file_action;
2226
2227 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2228 // to "/dev/null" if we run into any problems.
2229 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002230 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002231 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002232 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002233 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002234 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002235
2236 if (log)
2237 {
2238 StreamString strm;
2239 debugserver_args.Dump (&strm);
2240 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2241 }
2242
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002243 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2244 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002245
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002246 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002247
Greg Claytonb72d0f02011-04-12 05:54:46 +00002248 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002249 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002250 else
Chris Lattner24943d22010-06-08 16:52:24 +00002251 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2252
2253 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002254 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002255 }
2256 else
2257 {
Greg Clayton9c236732011-10-26 00:56:27 +00002258 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002259 }
2260
2261 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2262 StartAsyncThread ();
2263 }
2264 return error;
2265}
2266
2267bool
2268ProcessGDBRemote::MonitorDebugserverProcess
2269(
2270 void *callback_baton,
2271 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002272 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002273 int signo, // Zero for no signal
2274 int exit_status // Exit value of process if signal is zero
2275)
2276{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002277 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2278 // and might not exist anymore, so we need to carefully try to get the
2279 // target for this process first since we have a race condition when
2280 // we are done running between getting the notice that the inferior
2281 // process has died and the debugserver that was debugging this process.
2282 // In our test suite, we are also continually running process after
2283 // process, so we must be very careful to make sure:
2284 // 1 - process object hasn't been deleted already
2285 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002286
2287 // "debugserver_pid" argument passed in is the process ID for
2288 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002289 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002290
Greg Clayton75ccf502010-08-21 02:22:51 +00002291 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002292
Greg Clayton1c4642c2011-11-16 05:37:56 +00002293 // Get a shared pointer to the target that has a matching process pointer.
2294 // This target could be gone, or the target could already have a new process
2295 // object inside of it
2296 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2297
Greg Clayton72e1c782011-01-22 23:43:18 +00002298 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002299 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 +00002300
Greg Clayton1c4642c2011-11-16 05:37:56 +00002301 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002302 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002303 // We found a process in a target that matches, but another thread
2304 // might be in the process of launching a new process that will
2305 // soon replace it, so get a shared pointer to the process so we
2306 // can keep it alive.
2307 ProcessSP process_sp (target_sp->GetProcessSP());
2308 // Now we have a shared pointer to the process that can't go away on us
2309 // so we now make sure it was the same as the one passed in, and also make
2310 // sure that our previous "process *" didn't get deleted and have a new
2311 // "process *" created in its place with the same pointer. To verify this
2312 // we make sure the process has our debugserver process ID. If we pass all
2313 // of these tests, then we are sure that this process is the one we were
2314 // looking for.
2315 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002316 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002317 // Sleep for a half a second to make sure our inferior process has
2318 // time to set its exit status before we set it incorrectly when
2319 // both the debugserver and the inferior process shut down.
2320 usleep (500000);
2321 // If our process hasn't yet exited, debugserver might have died.
2322 // If the process did exit, the we are reaping it.
2323 const StateType state = process->GetState();
2324
2325 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2326 state != eStateInvalid &&
2327 state != eStateUnloaded &&
2328 state != eStateExited &&
2329 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002330 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002331 char error_str[1024];
2332 if (signo)
2333 {
2334 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2335 if (signal_cstr)
2336 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2337 else
2338 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2339 }
Chris Lattner24943d22010-06-08 16:52:24 +00002340 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002341 {
2342 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2343 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002344
Greg Clayton1c4642c2011-11-16 05:37:56 +00002345 process->SetExitStatus (-1, error_str);
2346 }
2347 // Debugserver has exited we need to let our ProcessGDBRemote
2348 // know that it no longer has a debugserver instance
2349 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002350 }
Chris Lattner24943d22010-06-08 16:52:24 +00002351 }
2352 return true;
2353}
2354
2355void
2356ProcessGDBRemote::KillDebugserverProcess ()
2357{
2358 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2359 {
2360 ::kill (m_debugserver_pid, SIGINT);
2361 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2362 }
2363}
2364
2365void
2366ProcessGDBRemote::Initialize()
2367{
2368 static bool g_initialized = false;
2369
2370 if (g_initialized == false)
2371 {
2372 g_initialized = true;
2373 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2374 GetPluginDescriptionStatic(),
2375 CreateInstance);
2376
2377 Log::Callbacks log_callbacks = {
2378 ProcessGDBRemoteLog::DisableLog,
2379 ProcessGDBRemoteLog::EnableLog,
2380 ProcessGDBRemoteLog::ListLogCategories
2381 };
2382
2383 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2384 }
2385}
2386
2387bool
Chris Lattner24943d22010-06-08 16:52:24 +00002388ProcessGDBRemote::StartAsyncThread ()
2389{
Greg Claytone005f2c2010-11-06 01:53:30 +00002390 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002391
2392 if (log)
2393 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2394
2395 // Create a thread that watches our internal state and controls which
2396 // events make it to clients (into the DCProcess event queue).
2397 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002398 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002399}
2400
2401void
2402ProcessGDBRemote::StopAsyncThread ()
2403{
Greg Claytone005f2c2010-11-06 01:53:30 +00002404 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002405
2406 if (log)
2407 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2408
2409 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002410
2411 // This will shut down the async thread.
2412 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002413
2414 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002415 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002416 {
2417 Host::ThreadJoin (m_async_thread, NULL, NULL);
2418 }
2419}
2420
2421
2422void *
2423ProcessGDBRemote::AsyncThread (void *arg)
2424{
2425 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2426
Greg Claytone005f2c2010-11-06 01:53:30 +00002427 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002428 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002429 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002430
2431 Listener listener ("ProcessGDBRemote::AsyncThread");
2432 EventSP event_sp;
2433 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2434 eBroadcastBitAsyncThreadShouldExit;
2435
2436 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2437 {
Greg Claytona2f74232011-02-24 22:24:29 +00002438 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2439
Chris Lattner24943d22010-06-08 16:52:24 +00002440 bool done = false;
2441 while (!done)
2442 {
2443 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002444 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002445 if (listener.WaitForEvent (NULL, event_sp))
2446 {
2447 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002448 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002449 {
Greg Claytona2f74232011-02-24 22:24:29 +00002450 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002451 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 +00002452
Greg Claytona2f74232011-02-24 22:24:29 +00002453 switch (event_type)
2454 {
2455 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002456 {
Greg Claytona2f74232011-02-24 22:24:29 +00002457 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002458
Greg Claytona2f74232011-02-24 22:24:29 +00002459 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002460 {
Greg Claytona2f74232011-02-24 22:24:29 +00002461 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2462 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2463 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002464 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002465
Greg Claytona2f74232011-02-24 22:24:29 +00002466 if (::strstr (continue_cstr, "vAttach") == NULL)
2467 process->SetPrivateState(eStateRunning);
2468 StringExtractorGDBRemote response;
2469 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002470
Greg Claytona2f74232011-02-24 22:24:29 +00002471 switch (stop_state)
2472 {
2473 case eStateStopped:
2474 case eStateCrashed:
2475 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002476 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002477 process->SetPrivateState (stop_state);
2478 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002479
Greg Claytona2f74232011-02-24 22:24:29 +00002480 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002481 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002482 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002483 response.SetFilePos(1);
2484 process->SetExitStatus(response.GetHexU8(), NULL);
2485 done = true;
2486 break;
2487
2488 case eStateInvalid:
2489 process->SetExitStatus(-1, "lost connection");
2490 break;
2491
2492 default:
2493 process->SetPrivateState (stop_state);
2494 break;
2495 }
Chris Lattner24943d22010-06-08 16:52:24 +00002496 }
2497 }
Greg Claytona2f74232011-02-24 22:24:29 +00002498 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002499
Greg Claytona2f74232011-02-24 22:24:29 +00002500 case eBroadcastBitAsyncThreadShouldExit:
2501 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002502 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002503 done = true;
2504 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002505
Greg Claytona2f74232011-02-24 22:24:29 +00002506 default:
2507 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002508 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 +00002509 done = true;
2510 break;
2511 }
2512 }
2513 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2514 {
2515 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2516 {
2517 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002518 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002519 }
Chris Lattner24943d22010-06-08 16:52:24 +00002520 }
2521 }
2522 else
2523 {
2524 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002525 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 +00002526 done = true;
2527 }
2528 }
2529 }
2530
2531 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002532 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002533
2534 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2535 return NULL;
2536}
2537
Chris Lattner24943d22010-06-08 16:52:24 +00002538const char *
2539ProcessGDBRemote::GetDispatchQueueNameForThread
2540(
2541 addr_t thread_dispatch_qaddr,
2542 std::string &dispatch_queue_name
2543)
2544{
2545 dispatch_queue_name.clear();
2546 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2547 {
2548 // Cache the dispatch_queue_offsets_addr value so we don't always have
2549 // to look it up
2550 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2551 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002552 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2553 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002554 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2555 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002556 if (module_sp)
2557 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2558
2559 if (dispatch_queue_offsets_symbol == NULL)
2560 {
Greg Clayton444fe992012-02-26 05:51:37 +00002561 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2562 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002563 if (module_sp)
2564 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2565 }
Chris Lattner24943d22010-06-08 16:52:24 +00002566 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002567 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002568
2569 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2570 return NULL;
2571 }
2572
2573 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002574 DataExtractor data (memory_buffer,
2575 sizeof(memory_buffer),
2576 m_target.GetArchitecture().GetByteOrder(),
2577 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002578
2579 // Excerpt from src/queue_private.h
2580 struct dispatch_queue_offsets_s
2581 {
2582 uint16_t dqo_version;
2583 uint16_t dqo_label;
2584 uint16_t dqo_label_size;
2585 } dispatch_queue_offsets;
2586
2587
2588 Error error;
2589 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2590 {
2591 uint32_t data_offset = 0;
2592 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2593 {
2594 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2595 {
2596 data_offset = 0;
2597 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2598 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2599 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2600 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2601 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2602 dispatch_queue_name.erase (bytes_read);
2603 }
2604 }
2605 }
2606 }
2607 if (dispatch_queue_name.empty())
2608 return NULL;
2609 return dispatch_queue_name.c_str();
2610}
2611
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002612//uint32_t
2613//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2614//{
2615// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2616// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2617// if (m_local_debugserver)
2618// {
2619// return Host::ListProcessesMatchingName (name, matches, pids);
2620// }
2621// else
2622// {
2623// // FIXME: Implement talking to the remote debugserver.
2624// return 0;
2625// }
2626//
2627//}
2628//
Jim Ingham55e01d82011-01-22 01:33:44 +00002629bool
2630ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2631 lldb_private::StoppointCallbackContext *context,
2632 lldb::user_id_t break_id,
2633 lldb::user_id_t break_loc_id)
2634{
2635 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2636 // run so I can stop it if that's what I want to do.
2637 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2638 if (log)
2639 log->Printf("Hit New Thread Notification breakpoint.");
2640 return false;
2641}
2642
2643
2644bool
2645ProcessGDBRemote::StartNoticingNewThreads()
2646{
2647 static const char *bp_names[] =
2648 {
2649 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002650 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002651 "_pthread_start",
2652 NULL
2653 };
2654
2655 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2656 size_t num_bps = m_thread_observation_bps.size();
2657 if (num_bps != 0)
2658 {
2659 for (int i = 0; i < num_bps; i++)
2660 {
2661 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2662 if (break_sp)
2663 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002664 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002665 log->Printf("Enabled noticing new thread breakpoint.");
2666 break_sp->SetEnabled(true);
2667 }
2668 }
2669 }
2670 else
2671 {
2672 for (int i = 0; bp_names[i] != NULL; i++)
2673 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002674 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002675 if (breakpoint)
2676 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002677 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002678 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2679 m_thread_observation_bps.push_back(breakpoint->GetID());
2680 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2681 }
2682 else
2683 {
2684 if (log)
2685 log->Printf("Failed to create new thread notification breakpoint.");
2686 return false;
2687 }
2688 }
2689 }
2690
2691 return true;
2692}
2693
2694bool
2695ProcessGDBRemote::StopNoticingNewThreads()
2696{
Jim Inghamff276fe2011-02-08 05:19:01 +00002697 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002698 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002699 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002700 size_t num_bps = m_thread_observation_bps.size();
2701 if (num_bps != 0)
2702 {
2703 for (int i = 0; i < num_bps; i++)
2704 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002705
2706 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2707 if (break_sp)
2708 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002709 break_sp->SetEnabled(false);
2710 }
2711 }
2712 }
2713 return true;
2714}
2715
2716