blob: 9b875012a6ab07541c79d2f33a63fb6ef87ea97b [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 ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000707 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000708 m_gdb_comm.GetHostInfo ();
709 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000710 return error;
711}
712
713void
714ProcessGDBRemote::DidLaunchOrAttach ()
715{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000716 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
717 if (log)
718 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000719 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000720 {
721 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
722
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000723 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000724
Chris Lattner24943d22010-06-08 16:52:24 +0000725 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000726
Greg Claytoncb8977d2011-03-23 00:09:55 +0000727 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
728 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000729 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000730 ArchSpec &target_arch = GetTarget().GetArchitecture();
731
732 if (target_arch.IsValid())
733 {
734 // If the remote host is ARM and we have apple as the vendor, then
735 // ARM executables and shared libraries can have mixed ARM architectures.
736 // You can have an armv6 executable, and if the host is armv7, then the
737 // system will load the best possible architecture for all shared libraries
738 // it has, so we really need to take the remote host architecture as our
739 // defacto architecture in this case.
740
741 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
742 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
743 {
744 target_arch = gdb_remote_arch;
745 }
746 else
747 {
748 // Fill in what is missing in the triple
749 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
750 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000751 if (target_triple.getVendorName().size() == 0)
752 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000753 target_triple.setVendor (remote_triple.getVendor());
754
Greg Clayton2f085c62011-05-15 01:25:55 +0000755 if (target_triple.getOSName().size() == 0)
756 {
757 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000758
Greg Clayton2f085c62011-05-15 01:25:55 +0000759 if (target_triple.getEnvironmentName().size() == 0)
760 target_triple.setEnvironment (remote_triple.getEnvironment());
761 }
762 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000763 }
764 }
765 else
766 {
767 // The target doesn't have a valid architecture yet, set it from
768 // the architecture we got from the remote GDB server
769 target_arch = gdb_remote_arch;
770 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000771 }
Chris Lattner24943d22010-06-08 16:52:24 +0000772 }
773}
774
775void
776ProcessGDBRemote::DidLaunch ()
777{
778 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000779}
780
781Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000782ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000783{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000784 ProcessAttachInfo attach_info;
785 return DoAttachToProcessWithID(attach_pid, attach_info);
786}
787
788Error
789ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
790{
Chris Lattner24943d22010-06-08 16:52:24 +0000791 Error error;
792 // Clear out and clean up from any current state
793 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000794 if (attach_pid != LLDB_INVALID_PROCESS_ID)
795 {
Greg Claytona2f74232011-02-24 22:24:29 +0000796 // Make sure we aren't already connected?
797 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000798 {
Greg Claytona2f74232011-02-24 22:24:29 +0000799 char host_port[128];
800 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
801 char connect_url[128];
802 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000803
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000804 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000805
806 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000807 {
Greg Claytona2f74232011-02-24 22:24:29 +0000808 const char *error_string = error.AsCString();
809 if (error_string == NULL)
810 error_string = "unable to launch " DEBUGSERVER_BASENAME;
811
812 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000813 }
Greg Claytona2f74232011-02-24 22:24:29 +0000814 else
815 {
816 error = ConnectToDebugserver (connect_url);
817 }
818 }
819
820 if (error.Success())
821 {
822 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000823 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000824 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000825 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000826 }
827 }
Chris Lattner24943d22010-06-08 16:52:24 +0000828 return error;
829}
830
831size_t
832ProcessGDBRemote::AttachInputReaderCallback
833(
834 void *baton,
835 InputReader *reader,
836 lldb::InputReaderAction notification,
837 const char *bytes,
838 size_t bytes_len
839)
840{
841 if (notification == eInputReaderGotToken)
842 {
843 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
844 if (gdb_process->m_waiting_for_attach)
845 gdb_process->m_waiting_for_attach = false;
846 reader->SetIsDone(true);
847 return 1;
848 }
849 return 0;
850}
851
852Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000853ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000854{
855 Error error;
856 // Clear out and clean up from any current state
857 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000858
Chris Lattner24943d22010-06-08 16:52:24 +0000859 if (process_name && process_name[0])
860 {
Greg Claytona2f74232011-02-24 22:24:29 +0000861 // Make sure we aren't already connected?
862 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000863 {
Greg Claytona2f74232011-02-24 22:24:29 +0000864 char host_port[128];
865 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
866 char connect_url[128];
867 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
868
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000869 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000870 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000871 {
Greg Claytona2f74232011-02-24 22:24:29 +0000872 const char *error_string = error.AsCString();
873 if (error_string == NULL)
874 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000875
Greg Claytona2f74232011-02-24 22:24:29 +0000876 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000877 }
Greg Claytona2f74232011-02-24 22:24:29 +0000878 else
879 {
880 error = ConnectToDebugserver (connect_url);
881 }
882 }
883
884 if (error.Success())
885 {
886 StreamString packet;
887
888 if (wait_for_launch)
889 packet.PutCString("vAttachWait");
890 else
891 packet.PutCString("vAttachName");
892 packet.PutChar(';');
893 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
894
895 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
896
Chris Lattner24943d22010-06-08 16:52:24 +0000897 }
898 }
Chris Lattner24943d22010-06-08 16:52:24 +0000899 return error;
900}
901
Chris Lattner24943d22010-06-08 16:52:24 +0000902
903void
904ProcessGDBRemote::DidAttach ()
905{
Greg Claytone71e2582011-02-04 01:58:07 +0000906 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000907}
908
909Error
910ProcessGDBRemote::WillResume ()
911{
Greg Claytonc1f45872011-02-12 06:28:37 +0000912 m_continue_c_tids.clear();
913 m_continue_C_tids.clear();
914 m_continue_s_tids.clear();
915 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000916 return Error();
917}
918
919Error
920ProcessGDBRemote::DoResume ()
921{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000922 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000923 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
924 if (log)
925 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000926
927 Listener listener ("gdb-remote.resume-packet-sent");
928 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
929 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000930 StreamString continue_packet;
931 bool continue_packet_error = false;
932 if (m_gdb_comm.HasAnyVContSupport ())
933 {
934 continue_packet.PutCString ("vCont");
935
936 if (!m_continue_c_tids.empty())
937 {
938 if (m_gdb_comm.GetVContSupported ('c'))
939 {
940 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 +0000941 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000942 }
943 else
944 continue_packet_error = true;
945 }
946
947 if (!continue_packet_error && !m_continue_C_tids.empty())
948 {
949 if (m_gdb_comm.GetVContSupported ('C'))
950 {
951 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 +0000952 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000953 }
954 else
955 continue_packet_error = true;
956 }
Greg Claytonb749a262010-12-03 06:02:24 +0000957
Greg Claytonc1f45872011-02-12 06:28:37 +0000958 if (!continue_packet_error && !m_continue_s_tids.empty())
959 {
960 if (m_gdb_comm.GetVContSupported ('s'))
961 {
962 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 +0000963 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000964 }
965 else
966 continue_packet_error = true;
967 }
968
969 if (!continue_packet_error && !m_continue_S_tids.empty())
970 {
971 if (m_gdb_comm.GetVContSupported ('S'))
972 {
973 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 +0000974 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000975 }
976 else
977 continue_packet_error = true;
978 }
979
980 if (continue_packet_error)
981 continue_packet.GetString().clear();
982 }
983 else
984 continue_packet_error = true;
985
986 if (continue_packet_error)
987 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000988 // Either no vCont support, or we tried to use part of the vCont
989 // packet that wasn't supported by the remote GDB server.
990 // We need to try and make a simple packet that can do our continue
991 const size_t num_threads = GetThreadList().GetSize();
992 const size_t num_continue_c_tids = m_continue_c_tids.size();
993 const size_t num_continue_C_tids = m_continue_C_tids.size();
994 const size_t num_continue_s_tids = m_continue_s_tids.size();
995 const size_t num_continue_S_tids = m_continue_S_tids.size();
996 if (num_continue_c_tids > 0)
997 {
998 if (num_continue_c_tids == num_threads)
999 {
1000 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001001 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001002 continue_packet.PutChar ('c');
1003 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001004 }
1005 else if (num_continue_c_tids == 1 &&
1006 num_continue_C_tids == 0 &&
1007 num_continue_s_tids == 0 &&
1008 num_continue_S_tids == 0 )
1009 {
1010 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001011 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001012 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001013 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001014 }
1015 }
1016
Greg Claytonde1dd812011-06-24 03:21:43 +00001017 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001018 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001019 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1020 num_continue_C_tids > 0 &&
1021 num_continue_s_tids == 0 &&
1022 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001023 {
1024 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001025 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001026 if (num_continue_C_tids > 1)
1027 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001028 // More that one thread with a signal, yet we don't have
1029 // vCont support and we are being asked to resume each
1030 // thread with a signal, we need to make sure they are
1031 // all the same signal, or we can't issue the continue
1032 // accurately with the current support...
1033 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001034 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001035 continue_packet_error = false;
1036 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1037 {
1038 if (m_continue_C_tids[i].second != continue_signo)
1039 continue_packet_error = true;
1040 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001041 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001042 if (!continue_packet_error)
1043 m_gdb_comm.SetCurrentThreadForRun (-1);
1044 }
1045 else
1046 {
1047 // Set the continue thread ID
1048 continue_packet_error = false;
1049 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001050 }
1051 if (!continue_packet_error)
1052 {
1053 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001054 continue_packet.Printf("C%2.2x", continue_signo);
1055 }
1056 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001057 }
1058
Greg Claytonde1dd812011-06-24 03:21:43 +00001059 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001060 {
1061 if (num_continue_s_tids == num_threads)
1062 {
1063 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001064 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001065 continue_packet.PutChar ('s');
1066 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001067 }
1068 else if (num_continue_c_tids == 0 &&
1069 num_continue_C_tids == 0 &&
1070 num_continue_s_tids == 1 &&
1071 num_continue_S_tids == 0 )
1072 {
1073 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001074 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001075 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001076 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001077 }
1078 }
1079
1080 if (!continue_packet_error && num_continue_S_tids > 0)
1081 {
1082 if (num_continue_S_tids == num_threads)
1083 {
1084 const int step_signo = m_continue_S_tids.front().second;
1085 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001086 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001087 if (num_continue_S_tids > 1)
1088 {
1089 for (size_t i=1; i<num_threads; ++i)
1090 {
1091 if (m_continue_S_tids[i].second != step_signo)
1092 continue_packet_error = true;
1093 }
1094 }
1095 if (!continue_packet_error)
1096 {
1097 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001098 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001099 continue_packet.Printf("S%2.2x", step_signo);
1100 }
1101 }
1102 else if (num_continue_c_tids == 0 &&
1103 num_continue_C_tids == 0 &&
1104 num_continue_s_tids == 0 &&
1105 num_continue_S_tids == 1 )
1106 {
1107 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001108 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001109 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001110 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001111 }
1112 }
1113 }
1114
1115 if (continue_packet_error)
1116 {
1117 error.SetErrorString ("can't make continue packet for this resume");
1118 }
1119 else
1120 {
1121 EventSP event_sp;
1122 TimeValue timeout;
1123 timeout = TimeValue::Now();
1124 timeout.OffsetWithSeconds (5);
1125 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1126
1127 if (listener.WaitForEvent (&timeout, event_sp) == false)
1128 error.SetErrorString("Resume timed out.");
1129 }
Greg Claytonb749a262010-12-03 06:02:24 +00001130 }
1131
Jim Ingham3ae449a2010-11-17 02:32:00 +00001132 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001133}
1134
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001135void
1136ProcessGDBRemote::ClearThreadIDList ()
1137{
1138 Mutex::Locker locker(m_thread_ids_mutex);
1139 m_thread_ids.clear();
1140}
1141
1142bool
1143ProcessGDBRemote::UpdateThreadIDList ()
1144{
1145 Mutex::Locker locker(m_thread_ids_mutex);
1146 bool sequence_mutex_unavailable = false;
1147 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1148 if (sequence_mutex_unavailable)
1149 {
1150#if defined (LLDB_CONFIGURATION_DEBUG)
1151 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1152#endif
1153 return false; // We just didn't get the list
1154 }
1155 return true;
1156}
1157
Greg Claytonae932352012-04-10 00:18:59 +00001158bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001159ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001160{
1161 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001162 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001163 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001164 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001165 // Update the thread list's stop id immediately so we don't recurse into this function.
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001166 Mutex::Locker locker(m_thread_ids_mutex);
1167
1168 size_t num_thread_ids = m_thread_ids.size();
1169 // The "m_thread_ids" thread ID list should always be updated after each stop
1170 // reply packet, but in case it isn't, update it here.
1171 if (num_thread_ids == 0)
1172 {
1173 if (!UpdateThreadIDList ())
1174 return false;
1175 num_thread_ids = m_thread_ids.size();
1176 }
Chris Lattner24943d22010-06-08 16:52:24 +00001177
Greg Clayton37f962e2011-08-22 02:49:39 +00001178 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001179 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001180 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001181 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001182 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001183 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1184 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001185 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001186 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001187 }
Chris Lattner24943d22010-06-08 16:52:24 +00001188 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001189
Greg Claytonae932352012-04-10 00:18:59 +00001190 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001191}
1192
1193
1194StateType
1195ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1196{
Greg Clayton261a18b2011-06-02 22:22:38 +00001197 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001198 const char stop_type = stop_packet.GetChar();
1199 switch (stop_type)
1200 {
1201 case 'T':
1202 case 'S':
1203 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001204 if (GetStopID() == 0)
1205 {
1206 // Our first stop, make sure we have a process ID, and also make
1207 // sure we know about our registers
1208 if (GetID() == LLDB_INVALID_PROCESS_ID)
1209 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001210 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001211 if (pid != LLDB_INVALID_PROCESS_ID)
1212 SetID (pid);
1213 }
1214 BuildDynamicRegisterInfo (true);
1215 }
Chris Lattner24943d22010-06-08 16:52:24 +00001216 // Stop with signal and thread info
1217 const uint8_t signo = stop_packet.GetHexU8();
1218 std::string name;
1219 std::string value;
1220 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001221 std::string reason;
1222 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001223 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001224 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001225 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1226 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001227 ThreadSP thread_sp;
1228
Chris Lattner24943d22010-06-08 16:52:24 +00001229 while (stop_packet.GetNameColonValue(name, value))
1230 {
1231 if (name.compare("metype") == 0)
1232 {
1233 // exception type in big endian hex
1234 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1235 }
1236 else if (name.compare("mecount") == 0)
1237 {
1238 // exception count in big endian hex
1239 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1240 }
1241 else if (name.compare("medata") == 0)
1242 {
1243 // exception data in big endian hex
1244 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1245 }
1246 else if (name.compare("thread") == 0)
1247 {
1248 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001249 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001250 // m_thread_list does have its own mutex, but we need to
1251 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1252 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001253 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001254 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001255 if (!thread_sp)
1256 {
1257 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001258 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001259 m_thread_list.AddThread(thread_sp);
1260 }
Chris Lattner24943d22010-06-08 16:52:24 +00001261 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001262 else if (name.compare("threads") == 0)
1263 {
1264 Mutex::Locker locker(m_thread_ids_mutex);
1265 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001266 // A comma separated list of all threads in the current
1267 // process that includes the thread for this stop reply
1268 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001269 size_t comma_pos;
1270 lldb::tid_t tid;
1271 while ((comma_pos = value.find(',')) != std::string::npos)
1272 {
1273 value[comma_pos] = '\0';
1274 // thread in big endian hex
1275 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1276 if (tid != LLDB_INVALID_THREAD_ID)
1277 m_thread_ids.push_back (tid);
1278 value.erase(0, comma_pos + 1);
1279
1280 }
1281 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1282 if (tid != LLDB_INVALID_THREAD_ID)
1283 m_thread_ids.push_back (tid);
1284 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001285 else if (name.compare("hexname") == 0)
1286 {
1287 StringExtractor name_extractor;
1288 // Swap "value" over into "name_extractor"
1289 name_extractor.GetStringRef().swap(value);
1290 // Now convert the HEX bytes into a string value
1291 name_extractor.GetHexByteString (value);
1292 thread_name.swap (value);
1293 }
Chris Lattner24943d22010-06-08 16:52:24 +00001294 else if (name.compare("name") == 0)
1295 {
1296 thread_name.swap (value);
1297 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001298 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001299 {
1300 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1301 }
Greg Clayton65611552011-06-04 01:26:29 +00001302 else if (name.compare("reason") == 0)
1303 {
1304 reason.swap(value);
1305 }
1306 else if (name.compare("description") == 0)
1307 {
1308 StringExtractor desc_extractor;
1309 // Swap "value" over into "name_extractor"
1310 desc_extractor.GetStringRef().swap(value);
1311 // Now convert the HEX bytes into a string value
1312 desc_extractor.GetHexByteString (thread_name);
1313 }
Greg Claytona875b642011-01-09 21:07:35 +00001314 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1315 {
1316 // We have a register number that contains an expedited
1317 // register value. Lets supply this register to our thread
1318 // so it won't have to go and read it.
1319 if (thread_sp)
1320 {
1321 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1322
1323 if (reg != UINT32_MAX)
1324 {
1325 StringExtractor reg_value_extractor;
1326 // Swap "value" over into "reg_value_extractor"
1327 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001328 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1329 {
1330 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1331 name.c_str(),
1332 reg,
1333 reg,
1334 reg_value_extractor.GetStringRef().c_str(),
1335 stop_packet.GetStringRef().c_str());
1336 }
Greg Claytona875b642011-01-09 21:07:35 +00001337 }
1338 }
1339 }
Chris Lattner24943d22010-06-08 16:52:24 +00001340 }
Chris Lattner24943d22010-06-08 16:52:24 +00001341
1342 if (thread_sp)
1343 {
1344 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1345
1346 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001347 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001348 if (exc_type != 0)
1349 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001350 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001351
1352 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1353 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001354 exc_data_size,
1355 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001356 exc_data_size >= 2 ? exc_data[1] : 0,
1357 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001358 }
Greg Clayton65611552011-06-04 01:26:29 +00001359 else
Chris Lattner24943d22010-06-08 16:52:24 +00001360 {
Greg Clayton65611552011-06-04 01:26:29 +00001361 bool handled = false;
1362 if (!reason.empty())
1363 {
1364 if (reason.compare("trace") == 0)
1365 {
1366 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1367 handled = true;
1368 }
1369 else if (reason.compare("breakpoint") == 0)
1370 {
1371 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001372 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001373 if (bp_site_sp)
1374 {
1375 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1376 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1377 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1378 if (bp_site_sp->ValidForThisThread (gdb_thread))
1379 {
1380 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1381 handled = true;
1382 }
1383 }
1384
1385 if (!handled)
1386 {
1387 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1388 }
1389 }
1390 else if (reason.compare("trap") == 0)
1391 {
1392 // Let the trap just use the standard signal stop reason below...
1393 }
1394 else if (reason.compare("watchpoint") == 0)
1395 {
1396 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1397 // TODO: locate the watchpoint somehow...
1398 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1399 handled = true;
1400 }
1401 else if (reason.compare("exception") == 0)
1402 {
1403 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1404 handled = true;
1405 }
1406 }
1407
1408 if (signo)
1409 {
1410 if (signo == SIGTRAP)
1411 {
1412 // Currently we are going to assume SIGTRAP means we are either
1413 // hitting a breakpoint or hardware single stepping.
1414 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001415 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001416 if (bp_site_sp)
1417 {
1418 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1419 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1420 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1421 if (bp_site_sp->ValidForThisThread (gdb_thread))
1422 {
1423 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1424 handled = true;
1425 }
1426 }
1427 if (!handled)
1428 {
1429 // TODO: check for breakpoint or trap opcode in case there is a hard
1430 // coded software trap
1431 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1432 handled = true;
1433 }
1434 }
1435 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001436 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001437 }
1438 else
1439 {
Greg Clayton643ee732010-08-04 01:40:35 +00001440 StopInfoSP invalid_stop_info_sp;
1441 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001442 }
Greg Clayton65611552011-06-04 01:26:29 +00001443
1444 if (!description.empty())
1445 {
1446 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1447 if (stop_info_sp)
1448 {
1449 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001450 }
Greg Clayton65611552011-06-04 01:26:29 +00001451 else
1452 {
1453 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1454 }
1455 }
1456 }
Chris Lattner24943d22010-06-08 16:52:24 +00001457 }
1458 return eStateStopped;
1459 }
1460 break;
1461
1462 case 'W':
1463 // process exited
1464 return eStateExited;
1465
1466 default:
1467 break;
1468 }
1469 return eStateInvalid;
1470}
1471
1472void
1473ProcessGDBRemote::RefreshStateAfterStop ()
1474{
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001475 Mutex::Locker locker(m_thread_ids_mutex);
1476 m_thread_ids.clear();
1477 // Set the thread stop info. It might have a "threads" key whose value is
1478 // a list of all thread IDs in the current process, so m_thread_ids might
1479 // get set.
1480 SetThreadStopInfo (m_last_stop_packet);
1481 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1482 if (m_thread_ids.empty())
1483 {
1484 // No, we need to fetch the thread list manually
1485 UpdateThreadIDList();
1486 }
1487
Chris Lattner24943d22010-06-08 16:52:24 +00001488 // Let all threads recover from stopping and do any clean up based
1489 // on the previous thread state (if any).
1490 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001491
Chris Lattner24943d22010-06-08 16:52:24 +00001492}
1493
1494Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001495ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001496{
1497 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001498
Greg Claytona4881d02011-01-22 07:12:45 +00001499 bool timed_out = false;
1500 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001501
1502 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001503 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001504 // We are being asked to halt during an attach. We need to just close
1505 // our file handle and debugserver will go away, and we can be done...
1506 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001507 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001508 else
1509 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001510 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001511 {
1512 if (timed_out)
1513 error.SetErrorString("timed out sending interrupt packet");
1514 else
1515 error.SetErrorString("unknown error sending interrupt packet");
1516 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001517
1518 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001519 }
Chris Lattner24943d22010-06-08 16:52:24 +00001520 return error;
1521}
1522
1523Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001524ProcessGDBRemote::InterruptIfRunning
1525(
1526 bool discard_thread_plans,
1527 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001528 EventSP &stop_event_sp
1529)
Chris Lattner24943d22010-06-08 16:52:24 +00001530{
1531 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001532
Greg Clayton2860ba92011-01-23 19:58:49 +00001533 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1534
Greg Clayton68ca8232011-01-25 02:58:48 +00001535 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001536 const bool is_running = m_gdb_comm.IsRunning();
1537 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001538 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001539 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001540 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001541 is_running);
1542
Greg Clayton2860ba92011-01-23 19:58:49 +00001543 if (discard_thread_plans)
1544 {
1545 if (log)
1546 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1547 m_thread_list.DiscardThreadPlans();
1548 }
1549 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001550 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001551 if (catch_stop_event)
1552 {
1553 if (log)
1554 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1555 PausePrivateStateThread();
1556 paused_private_state_thread = true;
1557 }
1558
Greg Clayton4fb400f2010-09-27 21:07:38 +00001559 bool timed_out = false;
1560 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001561
Greg Clayton05e4d972012-03-29 01:55:41 +00001562 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001563 {
1564 if (timed_out)
1565 error.SetErrorString("timed out sending interrupt packet");
1566 else
1567 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001568 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001569 ResumePrivateStateThread();
1570 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001571 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001572
Greg Clayton72e1c782011-01-22 23:43:18 +00001573 if (catch_stop_event)
1574 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001575 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001576 TimeValue timeout_time;
1577 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001578 timeout_time.OffsetWithSeconds(5);
1579 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001580
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001581 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001582 if (log)
1583 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001584
Greg Clayton2860ba92011-01-23 19:58:49 +00001585 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001586 error.SetErrorString("unable to verify target stopped");
1587 }
1588
Greg Clayton68ca8232011-01-25 02:58:48 +00001589 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001590 {
1591 if (log)
1592 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001593 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001594 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001595 }
Chris Lattner24943d22010-06-08 16:52:24 +00001596 return error;
1597}
1598
Greg Clayton4fb400f2010-09-27 21:07:38 +00001599Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001600ProcessGDBRemote::WillDetach ()
1601{
Greg Clayton2860ba92011-01-23 19:58:49 +00001602 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1603 if (log)
1604 log->Printf ("ProcessGDBRemote::WillDetach()");
1605
Greg Clayton72e1c782011-01-22 23:43:18 +00001606 bool discard_thread_plans = true;
1607 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001608 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001609 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001610}
1611
1612Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001613ProcessGDBRemote::DoDetach()
1614{
1615 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001616 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001617 if (log)
1618 log->Printf ("ProcessGDBRemote::DoDetach()");
1619
1620 DisableAllBreakpointSites ();
1621
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001622 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001623
Greg Clayton516f0842012-04-11 00:24:49 +00001624 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001625 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001626 {
Greg Clayton516f0842012-04-11 00:24:49 +00001627 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001628 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1629 else
1630 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001631 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001632 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001633 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001634
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001635 SetPrivateState (eStateDetached);
1636 ResumePrivateStateThread();
1637
1638 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001639 return error;
1640}
Chris Lattner24943d22010-06-08 16:52:24 +00001641
1642Error
1643ProcessGDBRemote::DoDestroy ()
1644{
1645 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001646 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001647 if (log)
1648 log->Printf ("ProcessGDBRemote::DoDestroy()");
1649
1650 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001651 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001652 {
Jim Ingham8226e942011-10-28 01:11:35 +00001653 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001654 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001655
1656 StringExtractorGDBRemote response;
1657 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001658 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001659 {
1660 char packet_cmd = response.GetChar(0);
1661
1662 if (packet_cmd == 'W' || packet_cmd == 'X')
1663 {
Greg Clayton06709002011-12-06 04:51:14 +00001664 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001665 ClearThreadIDList ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001666 SetExitStatus(response.GetHexU8(), NULL);
1667 }
1668 }
1669 else
1670 {
1671 SetExitStatus(SIGABRT, NULL);
1672 //error.SetErrorString("kill packet failed");
1673 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001674 }
1675 }
Chris Lattner24943d22010-06-08 16:52:24 +00001676 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001677 KillDebugserverProcess ();
1678 return error;
1679}
1680
Chris Lattner24943d22010-06-08 16:52:24 +00001681//------------------------------------------------------------------
1682// Process Queries
1683//------------------------------------------------------------------
1684
1685bool
1686ProcessGDBRemote::IsAlive ()
1687{
Greg Clayton58e844b2010-12-08 05:08:21 +00001688 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001689}
1690
1691addr_t
1692ProcessGDBRemote::GetImageInfoAddress()
1693{
Greg Clayton516f0842012-04-11 00:24:49 +00001694 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001695}
1696
Chris Lattner24943d22010-06-08 16:52:24 +00001697//------------------------------------------------------------------
1698// Process Memory
1699//------------------------------------------------------------------
1700size_t
1701ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1702{
1703 if (size > m_max_memory_size)
1704 {
1705 // Keep memory read sizes down to a sane limit. This function will be
1706 // called multiple times in order to complete the task by
1707 // lldb_private::Process so it is ok to do this.
1708 size = m_max_memory_size;
1709 }
1710
1711 char packet[64];
1712 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1713 assert (packet_len + 1 < sizeof(packet));
1714 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001715 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001716 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001717 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001718 {
1719 error.Clear();
1720 return response.GetHexBytes(buf, size, '\xdd');
1721 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001722 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001723 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001724 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001725 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1726 else
1727 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1728 }
1729 else
1730 {
1731 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1732 }
1733 return 0;
1734}
1735
1736size_t
1737ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1738{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001739 if (size > m_max_memory_size)
1740 {
1741 // Keep memory read sizes down to a sane limit. This function will be
1742 // called multiple times in order to complete the task by
1743 // lldb_private::Process so it is ok to do this.
1744 size = m_max_memory_size;
1745 }
1746
Chris Lattner24943d22010-06-08 16:52:24 +00001747 StreamString packet;
1748 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001749 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001750 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001751 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001752 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001753 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001754 {
1755 error.Clear();
1756 return size;
1757 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001758 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001759 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001760 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001761 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1762 else
1763 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1764 }
1765 else
1766 {
1767 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1768 }
1769 return 0;
1770}
1771
1772lldb::addr_t
1773ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1774{
Greg Clayton989816b2011-05-14 01:50:35 +00001775 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1776
Greg Clayton2f085c62011-05-15 01:25:55 +00001777 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001778 switch (supported)
1779 {
1780 case eLazyBoolCalculate:
1781 case eLazyBoolYes:
1782 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1783 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1784 return allocated_addr;
1785
1786 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001787 // Call mmap() to create memory in the inferior..
1788 unsigned prot = 0;
1789 if (permissions & lldb::ePermissionsReadable)
1790 prot |= eMmapProtRead;
1791 if (permissions & lldb::ePermissionsWritable)
1792 prot |= eMmapProtWrite;
1793 if (permissions & lldb::ePermissionsExecutable)
1794 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001795
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001796 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1797 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1798 m_addr_to_mmap_size[allocated_addr] = size;
1799 else
1800 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001801 break;
1802 }
1803
Chris Lattner24943d22010-06-08 16:52:24 +00001804 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001805 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001806 else
1807 error.Clear();
1808 return allocated_addr;
1809}
1810
1811Error
Greg Claytona9385532011-11-18 07:03:08 +00001812ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1813 MemoryRegionInfo &region_info)
1814{
1815
1816 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1817 return error;
1818}
1819
1820Error
Chris Lattner24943d22010-06-08 16:52:24 +00001821ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1822{
1823 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001824 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1825
1826 switch (supported)
1827 {
1828 case eLazyBoolCalculate:
1829 // We should never be deallocating memory without allocating memory
1830 // first so we should never get eLazyBoolCalculate
1831 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1832 break;
1833
1834 case eLazyBoolYes:
1835 if (!m_gdb_comm.DeallocateMemory (addr))
1836 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1837 break;
1838
1839 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001840 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001841 {
1842 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001843 if (pos != m_addr_to_mmap_size.end() &&
1844 InferiorCallMunmap(this, addr, pos->second))
1845 m_addr_to_mmap_size.erase (pos);
1846 else
1847 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001848 }
1849 break;
1850 }
1851
Chris Lattner24943d22010-06-08 16:52:24 +00001852 return error;
1853}
1854
1855
1856//------------------------------------------------------------------
1857// Process STDIO
1858//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001859size_t
1860ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1861{
1862 if (m_stdio_communication.IsConnected())
1863 {
1864 ConnectionStatus status;
1865 m_stdio_communication.Write(src, src_len, status, NULL);
1866 }
1867 return 0;
1868}
1869
1870Error
1871ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1872{
1873 Error error;
1874 assert (bp_site != NULL);
1875
Greg Claytone005f2c2010-11-06 01:53:30 +00001876 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001877 user_id_t site_id = bp_site->GetID();
1878 const addr_t addr = bp_site->GetLoadAddress();
1879 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001880 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001881
1882 if (bp_site->IsEnabled())
1883 {
1884 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001885 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 +00001886 return error;
1887 }
1888 else
1889 {
1890 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1891
1892 if (bp_site->HardwarePreferred())
1893 {
1894 // Try and set hardware breakpoint, and if that fails, fall through
1895 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001896 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001897 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001898 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001899 {
1900 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001901 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001902 return error;
1903 }
Chris Lattner24943d22010-06-08 16:52:24 +00001904 }
1905 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001906
1907 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001908 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001909 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1910 {
1911 bp_site->SetEnabled(true);
1912 bp_site->SetType (BreakpointSite::eExternal);
1913 return error;
1914 }
Chris Lattner24943d22010-06-08 16:52:24 +00001915 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001916
1917 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001918 }
1919
1920 if (log)
1921 {
1922 const char *err_string = error.AsCString();
1923 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1924 bp_site->GetLoadAddress(),
1925 err_string ? err_string : "NULL");
1926 }
1927 // We shouldn't reach here on a successful breakpoint enable...
1928 if (error.Success())
1929 error.SetErrorToGenericError();
1930 return error;
1931}
1932
1933Error
1934ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1935{
1936 Error error;
1937 assert (bp_site != NULL);
1938 addr_t addr = bp_site->GetLoadAddress();
1939 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001940 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001941 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001942 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001943
1944 if (bp_site->IsEnabled())
1945 {
1946 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1947
Greg Claytonb72d0f02011-04-12 05:54:46 +00001948 BreakpointSite::Type bp_type = bp_site->GetType();
1949 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001950 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001951 case BreakpointSite::eSoftware:
1952 error = DisableSoftwareBreakpoint (bp_site);
1953 break;
1954
1955 case BreakpointSite::eHardware:
1956 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1957 error.SetErrorToGenericError();
1958 break;
1959
1960 case BreakpointSite::eExternal:
1961 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1962 error.SetErrorToGenericError();
1963 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001964 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001965 if (error.Success())
1966 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001967 }
1968 else
1969 {
1970 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001971 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 +00001972 return error;
1973 }
1974
1975 if (error.Success())
1976 error.SetErrorToGenericError();
1977 return error;
1978}
1979
Johnny Chen21900fb2011-09-06 22:38:36 +00001980// Pre-requisite: wp != NULL.
1981static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00001982GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00001983{
1984 assert(wp);
1985 bool watch_read = wp->WatchpointRead();
1986 bool watch_write = wp->WatchpointWrite();
1987
1988 // watch_read and watch_write cannot both be false.
1989 assert(watch_read || watch_write);
1990 if (watch_read && watch_write)
1991 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001992 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00001993 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00001994 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00001995 return eWatchpointWrite;
1996}
1997
Chris Lattner24943d22010-06-08 16:52:24 +00001998Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001999ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002000{
2001 Error error;
2002 if (wp)
2003 {
2004 user_id_t watchID = wp->GetID();
2005 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002006 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002007 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002008 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002009 if (wp->IsEnabled())
2010 {
2011 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002012 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002013 return error;
2014 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002015
2016 GDBStoppointType type = GetGDBStoppointType(wp);
2017 // Pass down an appropriate z/Z packet...
2018 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002019 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002020 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2021 {
2022 wp->SetEnabled(true);
2023 return error;
2024 }
2025 else
2026 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002027 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002028 else
2029 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002030 }
2031 else
2032 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002033 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002034 }
2035 if (error.Success())
2036 error.SetErrorToGenericError();
2037 return error;
2038}
2039
2040Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002041ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002042{
2043 Error error;
2044 if (wp)
2045 {
2046 user_id_t watchID = wp->GetID();
2047
Greg Claytone005f2c2010-11-06 01:53:30 +00002048 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002049
2050 addr_t addr = wp->GetLoadAddress();
2051 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002052 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002053
Johnny Chen21900fb2011-09-06 22:38:36 +00002054 if (!wp->IsEnabled())
2055 {
2056 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002057 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002058 return error;
2059 }
2060
Chris Lattner24943d22010-06-08 16:52:24 +00002061 if (wp->IsHardware())
2062 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002063 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002064 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002065 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2066 {
2067 wp->SetEnabled(false);
2068 return error;
2069 }
2070 else
2071 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002072 }
2073 // TODO: clear software watchpoints if we implement them
2074 }
2075 else
2076 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002077 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002078 }
2079 if (error.Success())
2080 error.SetErrorToGenericError();
2081 return error;
2082}
2083
2084void
2085ProcessGDBRemote::Clear()
2086{
2087 m_flags = 0;
2088 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002089}
2090
2091Error
2092ProcessGDBRemote::DoSignal (int signo)
2093{
2094 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002095 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002096 if (log)
2097 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2098
2099 if (!m_gdb_comm.SendAsyncSignal (signo))
2100 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2101 return error;
2102}
2103
Chris Lattner24943d22010-06-08 16:52:24 +00002104Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002105ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2106{
2107 ProcessLaunchInfo launch_info;
2108 return StartDebugserverProcess(debugserver_url, launch_info);
2109}
2110
2111Error
2112ProcessGDBRemote::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 +00002113{
2114 Error error;
2115 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2116 {
2117 // If we locate debugserver, keep that located version around
2118 static FileSpec g_debugserver_file_spec;
2119
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002120 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002121 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002122 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002123
2124 // Always check to see if we have an environment override for the path
2125 // to the debugserver to use and use it if we do.
2126 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2127 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002128 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002129 else
2130 debugserver_file_spec = g_debugserver_file_spec;
2131 bool debugserver_exists = debugserver_file_spec.Exists();
2132 if (!debugserver_exists)
2133 {
2134 // The debugserver binary is in the LLDB.framework/Resources
2135 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002136 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002137 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002138 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002139 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002140 if (debugserver_exists)
2141 {
2142 g_debugserver_file_spec = debugserver_file_spec;
2143 }
2144 else
2145 {
2146 g_debugserver_file_spec.Clear();
2147 debugserver_file_spec.Clear();
2148 }
Chris Lattner24943d22010-06-08 16:52:24 +00002149 }
2150 }
2151
2152 if (debugserver_exists)
2153 {
2154 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2155
2156 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002157
Greg Claytone005f2c2010-11-06 01:53:30 +00002158 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002159
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002160 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002161 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002162
Chris Lattner24943d22010-06-08 16:52:24 +00002163 // Start args with "debugserver /file/path -r --"
2164 debugserver_args.AppendArgument(debugserver_path);
2165 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002166 // use native registers, not the GDB registers
2167 debugserver_args.AppendArgument("--native-regs");
2168 // make debugserver run in its own session so signals generated by
2169 // special terminal key sequences (^C) don't affect debugserver
2170 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002171
Chris Lattner24943d22010-06-08 16:52:24 +00002172 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2173 if (env_debugserver_log_file)
2174 {
2175 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2176 debugserver_args.AppendArgument(arg_cstr);
2177 }
2178
2179 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2180 if (env_debugserver_log_flags)
2181 {
2182 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2183 debugserver_args.AppendArgument(arg_cstr);
2184 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002185// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002186// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002187
Greg Claytonb72d0f02011-04-12 05:54:46 +00002188 // We currently send down all arguments, attach pids, or attach
2189 // process names in dedicated GDB server packets, so we don't need
2190 // to pass them as arguments. This is currently because of all the
2191 // things we need to setup prior to launching: the environment,
2192 // current working dir, file actions, etc.
2193#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002194 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002195 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002196 {
Greg Claytona2f74232011-02-24 22:24:29 +00002197 // Terminate the debugserver args so we can now append the inferior args
2198 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002199
Greg Claytona2f74232011-02-24 22:24:29 +00002200 for (int i = 0; inferior_argv[i] != NULL; ++i)
2201 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002202 }
2203 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2204 {
2205 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2206 debugserver_args.AppendArgument (arg_cstr);
2207 }
2208 else if (attach_name && attach_name[0])
2209 {
2210 if (wait_for_launch)
2211 debugserver_args.AppendArgument ("--waitfor");
2212 else
2213 debugserver_args.AppendArgument ("--attach");
2214 debugserver_args.AppendArgument (attach_name);
2215 }
Chris Lattner24943d22010-06-08 16:52:24 +00002216#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002217
2218 ProcessLaunchInfo::FileAction file_action;
2219
2220 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2221 // to "/dev/null" if we run into any problems.
2222 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002223 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002224 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002225 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002226 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002227 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002228
2229 if (log)
2230 {
2231 StreamString strm;
2232 debugserver_args.Dump (&strm);
2233 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2234 }
2235
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002236 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2237 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002238
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002239 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002240
Greg Claytonb72d0f02011-04-12 05:54:46 +00002241 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002242 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002243 else
Chris Lattner24943d22010-06-08 16:52:24 +00002244 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2245
2246 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002247 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002248 }
2249 else
2250 {
Greg Clayton9c236732011-10-26 00:56:27 +00002251 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002252 }
2253
2254 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2255 StartAsyncThread ();
2256 }
2257 return error;
2258}
2259
2260bool
2261ProcessGDBRemote::MonitorDebugserverProcess
2262(
2263 void *callback_baton,
2264 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002265 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002266 int signo, // Zero for no signal
2267 int exit_status // Exit value of process if signal is zero
2268)
2269{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002270 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2271 // and might not exist anymore, so we need to carefully try to get the
2272 // target for this process first since we have a race condition when
2273 // we are done running between getting the notice that the inferior
2274 // process has died and the debugserver that was debugging this process.
2275 // In our test suite, we are also continually running process after
2276 // process, so we must be very careful to make sure:
2277 // 1 - process object hasn't been deleted already
2278 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002279
2280 // "debugserver_pid" argument passed in is the process ID for
2281 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002282 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002283
Greg Clayton75ccf502010-08-21 02:22:51 +00002284 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002285
Greg Clayton1c4642c2011-11-16 05:37:56 +00002286 // Get a shared pointer to the target that has a matching process pointer.
2287 // This target could be gone, or the target could already have a new process
2288 // object inside of it
2289 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2290
Greg Clayton72e1c782011-01-22 23:43:18 +00002291 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002292 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 +00002293
Greg Clayton1c4642c2011-11-16 05:37:56 +00002294 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002295 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002296 // We found a process in a target that matches, but another thread
2297 // might be in the process of launching a new process that will
2298 // soon replace it, so get a shared pointer to the process so we
2299 // can keep it alive.
2300 ProcessSP process_sp (target_sp->GetProcessSP());
2301 // Now we have a shared pointer to the process that can't go away on us
2302 // so we now make sure it was the same as the one passed in, and also make
2303 // sure that our previous "process *" didn't get deleted and have a new
2304 // "process *" created in its place with the same pointer. To verify this
2305 // we make sure the process has our debugserver process ID. If we pass all
2306 // of these tests, then we are sure that this process is the one we were
2307 // looking for.
2308 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002309 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002310 // Sleep for a half a second to make sure our inferior process has
2311 // time to set its exit status before we set it incorrectly when
2312 // both the debugserver and the inferior process shut down.
2313 usleep (500000);
2314 // If our process hasn't yet exited, debugserver might have died.
2315 // If the process did exit, the we are reaping it.
2316 const StateType state = process->GetState();
2317
2318 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2319 state != eStateInvalid &&
2320 state != eStateUnloaded &&
2321 state != eStateExited &&
2322 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002323 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002324 char error_str[1024];
2325 if (signo)
2326 {
2327 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2328 if (signal_cstr)
2329 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2330 else
2331 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2332 }
Chris Lattner24943d22010-06-08 16:52:24 +00002333 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002334 {
2335 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2336 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002337
Greg Clayton1c4642c2011-11-16 05:37:56 +00002338 process->SetExitStatus (-1, error_str);
2339 }
2340 // Debugserver has exited we need to let our ProcessGDBRemote
2341 // know that it no longer has a debugserver instance
2342 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002343 }
Chris Lattner24943d22010-06-08 16:52:24 +00002344 }
2345 return true;
2346}
2347
2348void
2349ProcessGDBRemote::KillDebugserverProcess ()
2350{
2351 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2352 {
2353 ::kill (m_debugserver_pid, SIGINT);
2354 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2355 }
2356}
2357
2358void
2359ProcessGDBRemote::Initialize()
2360{
2361 static bool g_initialized = false;
2362
2363 if (g_initialized == false)
2364 {
2365 g_initialized = true;
2366 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2367 GetPluginDescriptionStatic(),
2368 CreateInstance);
2369
2370 Log::Callbacks log_callbacks = {
2371 ProcessGDBRemoteLog::DisableLog,
2372 ProcessGDBRemoteLog::EnableLog,
2373 ProcessGDBRemoteLog::ListLogCategories
2374 };
2375
2376 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2377 }
2378}
2379
2380bool
Chris Lattner24943d22010-06-08 16:52:24 +00002381ProcessGDBRemote::StartAsyncThread ()
2382{
Greg Claytone005f2c2010-11-06 01:53:30 +00002383 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002384
2385 if (log)
2386 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2387
2388 // Create a thread that watches our internal state and controls which
2389 // events make it to clients (into the DCProcess event queue).
2390 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002391 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002392}
2393
2394void
2395ProcessGDBRemote::StopAsyncThread ()
2396{
Greg Claytone005f2c2010-11-06 01:53:30 +00002397 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002398
2399 if (log)
2400 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2401
2402 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002403
2404 // This will shut down the async thread.
2405 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002406
2407 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002408 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002409 {
2410 Host::ThreadJoin (m_async_thread, NULL, NULL);
2411 }
2412}
2413
2414
2415void *
2416ProcessGDBRemote::AsyncThread (void *arg)
2417{
2418 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2419
Greg Claytone005f2c2010-11-06 01:53:30 +00002420 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002421 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002422 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002423
2424 Listener listener ("ProcessGDBRemote::AsyncThread");
2425 EventSP event_sp;
2426 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2427 eBroadcastBitAsyncThreadShouldExit;
2428
2429 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2430 {
Greg Claytona2f74232011-02-24 22:24:29 +00002431 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2432
Chris Lattner24943d22010-06-08 16:52:24 +00002433 bool done = false;
2434 while (!done)
2435 {
2436 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002437 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002438 if (listener.WaitForEvent (NULL, event_sp))
2439 {
2440 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002441 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002442 {
Greg Claytona2f74232011-02-24 22:24:29 +00002443 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002444 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 +00002445
Greg Claytona2f74232011-02-24 22:24:29 +00002446 switch (event_type)
2447 {
2448 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002449 {
Greg Claytona2f74232011-02-24 22:24:29 +00002450 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002451
Greg Claytona2f74232011-02-24 22:24:29 +00002452 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002453 {
Greg Claytona2f74232011-02-24 22:24:29 +00002454 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2455 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2456 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002457 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002458
Greg Claytona2f74232011-02-24 22:24:29 +00002459 if (::strstr (continue_cstr, "vAttach") == NULL)
2460 process->SetPrivateState(eStateRunning);
2461 StringExtractorGDBRemote response;
2462 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002463
Greg Claytona2f74232011-02-24 22:24:29 +00002464 switch (stop_state)
2465 {
2466 case eStateStopped:
2467 case eStateCrashed:
2468 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002469 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002470 process->SetPrivateState (stop_state);
2471 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002472
Greg Claytona2f74232011-02-24 22:24:29 +00002473 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002474 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002475 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002476 response.SetFilePos(1);
2477 process->SetExitStatus(response.GetHexU8(), NULL);
2478 done = true;
2479 break;
2480
2481 case eStateInvalid:
2482 process->SetExitStatus(-1, "lost connection");
2483 break;
2484
2485 default:
2486 process->SetPrivateState (stop_state);
2487 break;
2488 }
Chris Lattner24943d22010-06-08 16:52:24 +00002489 }
2490 }
Greg Claytona2f74232011-02-24 22:24:29 +00002491 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002492
Greg Claytona2f74232011-02-24 22:24:29 +00002493 case eBroadcastBitAsyncThreadShouldExit:
2494 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002495 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002496 done = true;
2497 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002498
Greg Claytona2f74232011-02-24 22:24:29 +00002499 default:
2500 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002501 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 +00002502 done = true;
2503 break;
2504 }
2505 }
2506 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2507 {
2508 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2509 {
2510 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002511 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002512 }
Chris Lattner24943d22010-06-08 16:52:24 +00002513 }
2514 }
2515 else
2516 {
2517 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002518 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 +00002519 done = true;
2520 }
2521 }
2522 }
2523
2524 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002525 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002526
2527 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2528 return NULL;
2529}
2530
Chris Lattner24943d22010-06-08 16:52:24 +00002531const char *
2532ProcessGDBRemote::GetDispatchQueueNameForThread
2533(
2534 addr_t thread_dispatch_qaddr,
2535 std::string &dispatch_queue_name
2536)
2537{
2538 dispatch_queue_name.clear();
2539 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2540 {
2541 // Cache the dispatch_queue_offsets_addr value so we don't always have
2542 // to look it up
2543 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2544 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002545 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2546 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002547 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2548 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002549 if (module_sp)
2550 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2551
2552 if (dispatch_queue_offsets_symbol == NULL)
2553 {
Greg Clayton444fe992012-02-26 05:51:37 +00002554 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2555 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_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 }
Chris Lattner24943d22010-06-08 16:52:24 +00002559 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002560 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002561
2562 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2563 return NULL;
2564 }
2565
2566 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002567 DataExtractor data (memory_buffer,
2568 sizeof(memory_buffer),
2569 m_target.GetArchitecture().GetByteOrder(),
2570 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002571
2572 // Excerpt from src/queue_private.h
2573 struct dispatch_queue_offsets_s
2574 {
2575 uint16_t dqo_version;
2576 uint16_t dqo_label;
2577 uint16_t dqo_label_size;
2578 } dispatch_queue_offsets;
2579
2580
2581 Error error;
2582 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2583 {
2584 uint32_t data_offset = 0;
2585 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2586 {
2587 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2588 {
2589 data_offset = 0;
2590 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2591 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2592 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2593 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2594 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2595 dispatch_queue_name.erase (bytes_read);
2596 }
2597 }
2598 }
2599 }
2600 if (dispatch_queue_name.empty())
2601 return NULL;
2602 return dispatch_queue_name.c_str();
2603}
2604
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002605//uint32_t
2606//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2607//{
2608// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2609// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2610// if (m_local_debugserver)
2611// {
2612// return Host::ListProcessesMatchingName (name, matches, pids);
2613// }
2614// else
2615// {
2616// // FIXME: Implement talking to the remote debugserver.
2617// return 0;
2618// }
2619//
2620//}
2621//
Jim Ingham55e01d82011-01-22 01:33:44 +00002622bool
2623ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2624 lldb_private::StoppointCallbackContext *context,
2625 lldb::user_id_t break_id,
2626 lldb::user_id_t break_loc_id)
2627{
2628 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2629 // run so I can stop it if that's what I want to do.
2630 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2631 if (log)
2632 log->Printf("Hit New Thread Notification breakpoint.");
2633 return false;
2634}
2635
2636
2637bool
2638ProcessGDBRemote::StartNoticingNewThreads()
2639{
2640 static const char *bp_names[] =
2641 {
2642 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002643 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002644 "_pthread_start",
2645 NULL
2646 };
2647
2648 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2649 size_t num_bps = m_thread_observation_bps.size();
2650 if (num_bps != 0)
2651 {
2652 for (int i = 0; i < num_bps; i++)
2653 {
2654 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2655 if (break_sp)
2656 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002657 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002658 log->Printf("Enabled noticing new thread breakpoint.");
2659 break_sp->SetEnabled(true);
2660 }
2661 }
2662 }
2663 else
2664 {
2665 for (int i = 0; bp_names[i] != NULL; i++)
2666 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002667 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002668 if (breakpoint)
2669 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002670 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002671 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2672 m_thread_observation_bps.push_back(breakpoint->GetID());
2673 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2674 }
2675 else
2676 {
2677 if (log)
2678 log->Printf("Failed to create new thread notification breakpoint.");
2679 return false;
2680 }
2681 }
2682 }
2683
2684 return true;
2685}
2686
2687bool
2688ProcessGDBRemote::StopNoticingNewThreads()
2689{
Jim Inghamff276fe2011-02-08 05:19:01 +00002690 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002691 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002692 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002693 size_t num_bps = m_thread_observation_bps.size();
2694 if (num_bps != 0)
2695 {
2696 for (int i = 0; i < num_bps; i++)
2697 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002698
2699 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2700 if (break_sp)
2701 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002702 break_sp->SetEnabled(false);
2703 }
2704 }
2705 }
2706 return true;
2707}
2708
2709