blob: 5b59289bb9a6299fff877dc831a97e6dd3b498e5 [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"
Greg Clayton33559462012-04-13 21:24:18 +000035#include "lldb/Core/StreamFile.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Core/StreamString.h"
37#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000038#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000039#include "lldb/Host/TimeValue.h"
40#include "lldb/Symbol/ObjectFile.h"
41#include "lldb/Target/DynamicLoader.h"
42#include "lldb/Target/Target.h"
43#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000044#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000045#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046
47// Project includes
48#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000049#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000050#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000051#include "GDBRemoteRegisterContext.h"
52#include "ProcessGDBRemote.h"
53#include "ProcessGDBRemoteLog.h"
54#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000055#include "StopInfoMachException.h"
56
Greg Clayton451fa822012-04-09 22:46:21 +000057namespace lldb
58{
59 // Provide a function that can easily dump the packet history if we know a
60 // ProcessGDBRemote * value (which we can get from logs or from debugging).
61 // We need the function in the lldb namespace so it makes it into the final
62 // executable since the LLDB shared library only exports stuff in the lldb
63 // namespace. This allows you to attach with a debugger and call this
64 // function and get the packet history dumped to a file.
65 void
66 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
67 {
Greg Clayton33559462012-04-13 21:24:18 +000068 lldb_private::StreamFile strm;
69 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
70 if (error.Success())
71 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000072 }
73};
Chris Lattner24943d22010-06-08 16:52:24 +000074
Chris Lattner24943d22010-06-08 16:52:24 +000075
76#define DEBUGSERVER_BASENAME "debugserver"
77using namespace lldb;
78using namespace lldb_private;
79
Jim Inghamf9600482011-03-29 21:45:47 +000080static bool rand_initialized = false;
81
Chris Lattner24943d22010-06-08 16:52:24 +000082static inline uint16_t
83get_random_port ()
84{
Jim Inghamf9600482011-03-29 21:45:47 +000085 if (!rand_initialized)
86 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000087 time_t seed = time(NULL);
88
Jim Inghamf9600482011-03-29 21:45:47 +000089 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000090 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000091 }
Stephen Wilson50daf772011-03-25 18:16:28 +000092 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000093}
94
95
96const char *
97ProcessGDBRemote::GetPluginNameStatic()
98{
Greg Claytonb1888f22011-03-19 01:12:21 +000099 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000100}
101
102const char *
103ProcessGDBRemote::GetPluginDescriptionStatic()
104{
105 return "GDB Remote protocol based debugging plug-in.";
106}
107
108void
109ProcessGDBRemote::Terminate()
110{
111 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
112}
113
114
Greg Clayton46c9a352012-02-09 06:16:32 +0000115lldb::ProcessSP
116ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000117{
Greg Clayton46c9a352012-02-09 06:16:32 +0000118 lldb::ProcessSP process_sp;
119 if (crash_file_path == NULL)
120 process_sp.reset (new ProcessGDBRemote (target, listener));
121 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000122}
123
124bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000125ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000126{
Greg Clayton61ddf562011-10-21 21:41:45 +0000127 if (plugin_specified_by_name)
128 return true;
129
Chris Lattner24943d22010-06-08 16:52:24 +0000130 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000131 Module *exe_module = target.GetExecutableModulePointer();
132 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000133 {
134 ObjectFile *exe_objfile = exe_module->GetObjectFile();
135 // We can't debug core files...
136 switch (exe_objfile->GetType())
137 {
138 case ObjectFile::eTypeInvalid:
139 case ObjectFile::eTypeCoreFile:
140 case ObjectFile::eTypeDebugInfo:
141 case ObjectFile::eTypeObjectFile:
142 case ObjectFile::eTypeSharedLibrary:
143 case ObjectFile::eTypeStubLibrary:
144 return false;
145 case ObjectFile::eTypeExecutable:
146 case ObjectFile::eTypeDynamicLinker:
147 case ObjectFile::eTypeUnknown:
148 break;
149 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000150 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000151 }
Jim Ingham7508e732010-08-09 23:31:02 +0000152 // However, if there is no executable module, we return true since we might be preparing to attach.
153 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000154}
155
156//----------------------------------------------------------------------
157// ProcessGDBRemote constructor
158//----------------------------------------------------------------------
159ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
160 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000161 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000162 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000163 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000164 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000165 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000166 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000167 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000168 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000169 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000170 m_continue_c_tids (),
171 m_continue_C_tids (),
172 m_continue_s_tids (),
173 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000174 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000175 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000176 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000177 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000178{
Greg Claytonff39f742011-04-01 00:29:43 +0000179 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
180 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000181 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000182}
183
184//----------------------------------------------------------------------
185// Destructor
186//----------------------------------------------------------------------
187ProcessGDBRemote::~ProcessGDBRemote()
188{
189 // m_mach_process.UnregisterNotificationCallbacks (this);
190 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000191 // We need to call finalize on the process before destroying ourselves
192 // to make sure all of the broadcaster cleanup goes as planned. If we
193 // destruct this class, then Process::~Process() might have problems
194 // trying to fully destroy the broadcaster.
195 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000196}
197
198//----------------------------------------------------------------------
199// PluginInterface
200//----------------------------------------------------------------------
201const char *
202ProcessGDBRemote::GetPluginName()
203{
204 return "Process debugging plug-in that uses the GDB remote protocol";
205}
206
207const char *
208ProcessGDBRemote::GetShortPluginName()
209{
210 return GetPluginNameStatic();
211}
212
213uint32_t
214ProcessGDBRemote::GetPluginVersion()
215{
216 return 1;
217}
218
219void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000220ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000221{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000222 if (!force && m_register_info.GetNumRegisters() > 0)
223 return;
224
225 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000226 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000227 uint32_t reg_offset = 0;
228 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000229 StringExtractorGDBRemote::ResponseType response_type;
230 for (response_type = StringExtractorGDBRemote::eResponse;
231 response_type == StringExtractorGDBRemote::eResponse;
232 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000233 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000234 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
235 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000236 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000237 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000238 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000239 response_type = response.GetResponseType();
240 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000241 {
242 std::string name;
243 std::string value;
244 ConstString reg_name;
245 ConstString alt_name;
246 ConstString set_name;
247 RegisterInfo reg_info = { NULL, // Name
248 NULL, // Alt name
249 0, // byte size
250 reg_offset, // offset
251 eEncodingUint, // encoding
252 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000253 {
254 LLDB_INVALID_REGNUM, // GCC reg num
255 LLDB_INVALID_REGNUM, // DWARF reg num
256 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000257 reg_num, // GDB reg num
258 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000259 },
260 NULL,
261 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000262 };
263
264 while (response.GetNameColonValue(name, value))
265 {
266 if (name.compare("name") == 0)
267 {
268 reg_name.SetCString(value.c_str());
269 }
270 else if (name.compare("alt-name") == 0)
271 {
272 alt_name.SetCString(value.c_str());
273 }
274 else if (name.compare("bitsize") == 0)
275 {
276 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
277 }
278 else if (name.compare("offset") == 0)
279 {
280 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000281 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000282 {
283 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000284 }
285 }
286 else if (name.compare("encoding") == 0)
287 {
288 if (value.compare("uint") == 0)
289 reg_info.encoding = eEncodingUint;
290 else if (value.compare("sint") == 0)
291 reg_info.encoding = eEncodingSint;
292 else if (value.compare("ieee754") == 0)
293 reg_info.encoding = eEncodingIEEE754;
294 else if (value.compare("vector") == 0)
295 reg_info.encoding = eEncodingVector;
296 }
297 else if (name.compare("format") == 0)
298 {
299 if (value.compare("binary") == 0)
300 reg_info.format = eFormatBinary;
301 else if (value.compare("decimal") == 0)
302 reg_info.format = eFormatDecimal;
303 else if (value.compare("hex") == 0)
304 reg_info.format = eFormatHex;
305 else if (value.compare("float") == 0)
306 reg_info.format = eFormatFloat;
307 else if (value.compare("vector-sint8") == 0)
308 reg_info.format = eFormatVectorOfSInt8;
309 else if (value.compare("vector-uint8") == 0)
310 reg_info.format = eFormatVectorOfUInt8;
311 else if (value.compare("vector-sint16") == 0)
312 reg_info.format = eFormatVectorOfSInt16;
313 else if (value.compare("vector-uint16") == 0)
314 reg_info.format = eFormatVectorOfUInt16;
315 else if (value.compare("vector-sint32") == 0)
316 reg_info.format = eFormatVectorOfSInt32;
317 else if (value.compare("vector-uint32") == 0)
318 reg_info.format = eFormatVectorOfUInt32;
319 else if (value.compare("vector-float32") == 0)
320 reg_info.format = eFormatVectorOfFloat32;
321 else if (value.compare("vector-uint128") == 0)
322 reg_info.format = eFormatVectorOfUInt128;
323 }
324 else if (name.compare("set") == 0)
325 {
326 set_name.SetCString(value.c_str());
327 }
328 else if (name.compare("gcc") == 0)
329 {
330 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
331 }
332 else if (name.compare("dwarf") == 0)
333 {
334 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
335 }
336 else if (name.compare("generic") == 0)
337 {
338 if (value.compare("pc") == 0)
339 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
340 else if (value.compare("sp") == 0)
341 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
342 else if (value.compare("fp") == 0)
343 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
344 else if (value.compare("ra") == 0)
345 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
346 else if (value.compare("flags") == 0)
347 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000348 else if (value.find("arg") == 0)
349 {
350 if (value.size() == 4)
351 {
352 switch (value[3])
353 {
354 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
355 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
356 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
357 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
358 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
359 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
360 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
361 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
362 }
363 }
364 }
Chris Lattner24943d22010-06-08 16:52:24 +0000365 }
366 }
367
Jason Molenda53d96862010-06-11 23:44:18 +0000368 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000369 assert (reg_info.byte_size != 0);
370 reg_offset += reg_info.byte_size;
371 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
372 }
373 }
374 else
375 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000376 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000377 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000378 }
379 }
380
381 if (reg_num == 0)
382 {
383 // We didn't get anything. See if we are debugging ARM and fill with
384 // a hard coded register set until we can get an updated debugserver
385 // down on the devices.
Jason Molenda428b5502011-10-06 01:45:46 +0000386
387 if (!GetTarget().GetArchitecture().IsValid()
388 && m_gdb_comm.GetHostArchitecture().IsValid()
389 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm
390 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
391 {
Chris Lattner24943d22010-06-08 16:52:24 +0000392 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000393 }
394 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
395 {
396 m_register_info.HardcodeARMRegisters();
397 }
Chris Lattner24943d22010-06-08 16:52:24 +0000398 }
399 m_register_info.Finalize ();
400}
401
402Error
403ProcessGDBRemote::WillLaunch (Module* module)
404{
405 return WillLaunchOrAttach ();
406}
407
408Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000409ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000410{
411 return WillLaunchOrAttach ();
412}
413
414Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000415ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000416{
417 return WillLaunchOrAttach ();
418}
419
420Error
Greg Claytone71e2582011-02-04 01:58:07 +0000421ProcessGDBRemote::DoConnectRemote (const char *remote_url)
422{
423 Error error (WillLaunchOrAttach ());
424
425 if (error.Fail())
426 return error;
427
Greg Clayton180546b2011-04-30 01:09:13 +0000428 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000429
430 if (error.Fail())
431 return error;
432 StartAsyncThread ();
433
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000434 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000435 if (pid == LLDB_INVALID_PROCESS_ID)
436 {
437 // We don't have a valid process ID, so note that we are connected
438 // and could now request to launch or attach, or get remote process
439 // listings...
440 SetPrivateState (eStateConnected);
441 }
442 else
443 {
444 // We have a valid process
445 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000446 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000447 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000448 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000449 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000450 if (state == eStateStopped)
451 {
452 SetPrivateState (state);
453 }
454 else
Greg Claytond9919d32011-12-01 23:28:38 +0000455 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 +0000456 }
457 else
Greg Claytond9919d32011-12-01 23:28:38 +0000458 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 +0000459 }
Jason Molendacb740b32012-05-03 22:37:30 +0000460
461 if (error.Success()
462 && !GetTarget().GetArchitecture().IsValid()
463 && m_gdb_comm.GetHostArchitecture().IsValid())
464 {
465 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
466 }
467
Greg Claytone71e2582011-02-04 01:58:07 +0000468 return error;
469}
470
471Error
Chris Lattner24943d22010-06-08 16:52:24 +0000472ProcessGDBRemote::WillLaunchOrAttach ()
473{
474 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000475 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000476 return error;
477}
478
479//----------------------------------------------------------------------
480// Process Control
481//----------------------------------------------------------------------
482Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000483ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000484{
Greg Clayton4b407112010-09-30 21:49:03 +0000485 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000486
487 uint32_t launch_flags = launch_info.GetFlags().Get();
488 const char *stdin_path = NULL;
489 const char *stdout_path = NULL;
490 const char *stderr_path = NULL;
491 const char *working_dir = launch_info.GetWorkingDirectory();
492
493 const ProcessLaunchInfo::FileAction *file_action;
494 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
495 if (file_action)
496 {
497 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
498 stdin_path = file_action->GetPath();
499 }
500 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
501 if (file_action)
502 {
503 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
504 stdout_path = file_action->GetPath();
505 }
506 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
507 if (file_action)
508 {
509 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
510 stderr_path = file_action->GetPath();
511 }
512
Chris Lattner24943d22010-06-08 16:52:24 +0000513 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
514 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
515 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000516 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000517
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000518 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000519 if (object_file)
520 {
Chris Lattner24943d22010-06-08 16:52:24 +0000521 char host_port[128];
522 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000523 char connect_url[128];
524 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000525
Greg Claytona2f74232011-02-24 22:24:29 +0000526 // Make sure we aren't already connected?
527 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000528 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000529 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000530 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000531 {
Johnny Chenc143d622011-08-09 18:56:45 +0000532 if (log)
533 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000534 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000535 }
Chris Lattner24943d22010-06-08 16:52:24 +0000536
Greg Claytone71e2582011-02-04 01:58:07 +0000537 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000538 }
539
540 if (error.Success())
541 {
542 lldb_utility::PseudoTerminal pty;
543 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000544
545 // If the debugserver is local and we aren't disabling STDIO, lets use
546 // a pseudo terminal to instead of relying on the 'O' packets for stdio
547 // since 'O' packets can really slow down debugging if the inferior
548 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000549 PlatformSP platform_sp (m_target.GetPlatform());
550 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000551 {
552 const char *slave_name = NULL;
553 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000554 {
Greg Claytona2f74232011-02-24 22:24:29 +0000555 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
556 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000557 }
Greg Claytona2f74232011-02-24 22:24:29 +0000558 if (stdin_path == NULL)
559 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000560
Greg Claytona2f74232011-02-24 22:24:29 +0000561 if (stdout_path == NULL)
562 stdout_path = slave_name;
563
564 if (stderr_path == NULL)
565 stderr_path = slave_name;
566 }
567
Greg Claytonafb81862011-03-02 21:34:46 +0000568 // Set STDIN to /dev/null if we want STDIO disabled or if either
569 // STDOUT or STDERR have been set to something and STDIN hasn't
570 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000571 stdin_path = "/dev/null";
572
Greg Claytonafb81862011-03-02 21:34:46 +0000573 // Set STDOUT to /dev/null if we want STDIO disabled or if either
574 // STDIN or STDERR have been set to something and STDOUT hasn't
575 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000576 stdout_path = "/dev/null";
577
Greg Claytonafb81862011-03-02 21:34:46 +0000578 // Set STDERR to /dev/null if we want STDIO disabled or if either
579 // STDIN or STDOUT have been set to something and STDERR hasn't
580 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000581 stderr_path = "/dev/null";
582
583 if (stdin_path)
584 m_gdb_comm.SetSTDIN (stdin_path);
585 if (stdout_path)
586 m_gdb_comm.SetSTDOUT (stdout_path);
587 if (stderr_path)
588 m_gdb_comm.SetSTDERR (stderr_path);
589
590 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
591
Greg Claytona4582402011-05-08 04:53:50 +0000592 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000593
594 if (working_dir && working_dir[0])
595 {
596 m_gdb_comm.SetWorkingDir (working_dir);
597 }
598
599 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000600 const Args &environment = launch_info.GetEnvironmentEntries();
601 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000602 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000603 size_t num_environment_entries = environment.GetArgumentCount();
604 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000605 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000606 const char *env_entry = environment.GetArgumentAtIndex(i);
607 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000608 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000609 }
Greg Claytona2f74232011-02-24 22:24:29 +0000610 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000611
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000612 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000613 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000614 if (arg_packet_err == 0)
615 {
616 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000617 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000618 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000619 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000620 }
621 else
622 {
Greg Claytona2f74232011-02-24 22:24:29 +0000623 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000624 }
Greg Claytona2f74232011-02-24 22:24:29 +0000625 }
626 else
627 {
Greg Clayton9c236732011-10-26 00:56:27 +0000628 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000629 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000630
631 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000632
Greg Claytona2f74232011-02-24 22:24:29 +0000633 if (GetID() == LLDB_INVALID_PROCESS_ID)
634 {
Johnny Chenc143d622011-08-09 18:56:45 +0000635 if (log)
636 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000637 KillDebugserverProcess ();
638 return error;
639 }
640
Greg Clayton261a18b2011-06-02 22:22:38 +0000641 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000642 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000643 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000644
645 if (!disable_stdio)
646 {
647 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000648 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000649 }
Chris Lattner24943d22010-06-08 16:52:24 +0000650 }
651 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000652 else
653 {
Johnny Chenc143d622011-08-09 18:56:45 +0000654 if (log)
655 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000656 }
Chris Lattner24943d22010-06-08 16:52:24 +0000657 }
658 else
659 {
660 // Set our user ID to an invalid process ID.
661 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000662 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
663 exe_module->GetFileSpec().GetFilename().AsCString(),
664 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000665 }
Chris Lattner24943d22010-06-08 16:52:24 +0000666 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000667
Chris Lattner24943d22010-06-08 16:52:24 +0000668}
669
670
671Error
Greg Claytone71e2582011-02-04 01:58:07 +0000672ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000673{
674 Error error;
675 // Sleep and wait a bit for debugserver to start to listen...
676 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
677 if (conn_ap.get())
678 {
Chris Lattner24943d22010-06-08 16:52:24 +0000679 const uint32_t max_retry_count = 50;
680 uint32_t retry_count = 0;
681 while (!m_gdb_comm.IsConnected())
682 {
Greg Claytone71e2582011-02-04 01:58:07 +0000683 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000684 {
685 m_gdb_comm.SetConnection (conn_ap.release());
686 break;
687 }
688 retry_count++;
689
690 if (retry_count >= max_retry_count)
691 break;
692
693 usleep (100000);
694 }
695 }
696
697 if (!m_gdb_comm.IsConnected())
698 {
699 if (error.Success())
700 error.SetErrorString("not connected to remote gdb server");
701 return error;
702 }
703
Greg Clayton24bc5d92011-03-30 18:16:51 +0000704 // We always seem to be able to open a connection to a local port
705 // so we need to make sure we can then send data to it. If we can't
706 // then we aren't actually connected to anything, so try and do the
707 // handshake with the remote GDB server and make sure that goes
708 // alright.
709 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000710 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000711 m_gdb_comm.Disconnect();
712 if (error.Success())
713 error.SetErrorString("not connected to remote gdb server");
714 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000715 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000716 m_gdb_comm.ResetDiscoverableSettings();
717 m_gdb_comm.QueryNoAckModeSupported ();
718 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000719 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000720 m_gdb_comm.GetHostInfo ();
721 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000722 return error;
723}
724
725void
726ProcessGDBRemote::DidLaunchOrAttach ()
727{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000728 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
729 if (log)
730 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000731 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000732 {
733 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
734
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000735 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000736
Chris Lattner24943d22010-06-08 16:52:24 +0000737 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000738
Greg Claytoncb8977d2011-03-23 00:09:55 +0000739 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
740 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000741 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000742 ArchSpec &target_arch = GetTarget().GetArchitecture();
743
744 if (target_arch.IsValid())
745 {
746 // If the remote host is ARM and we have apple as the vendor, then
747 // ARM executables and shared libraries can have mixed ARM architectures.
748 // You can have an armv6 executable, and if the host is armv7, then the
749 // system will load the best possible architecture for all shared libraries
750 // it has, so we really need to take the remote host architecture as our
751 // defacto architecture in this case.
752
753 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
754 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
755 {
756 target_arch = gdb_remote_arch;
757 }
758 else
759 {
760 // Fill in what is missing in the triple
761 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
762 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000763 if (target_triple.getVendorName().size() == 0)
764 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000765 target_triple.setVendor (remote_triple.getVendor());
766
Greg Clayton2f085c62011-05-15 01:25:55 +0000767 if (target_triple.getOSName().size() == 0)
768 {
769 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000770
Greg Clayton2f085c62011-05-15 01:25:55 +0000771 if (target_triple.getEnvironmentName().size() == 0)
772 target_triple.setEnvironment (remote_triple.getEnvironment());
773 }
774 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000775 }
776 }
777 else
778 {
779 // The target doesn't have a valid architecture yet, set it from
780 // the architecture we got from the remote GDB server
781 target_arch = gdb_remote_arch;
782 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000783 }
Chris Lattner24943d22010-06-08 16:52:24 +0000784 }
785}
786
787void
788ProcessGDBRemote::DidLaunch ()
789{
790 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000791}
792
793Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000794ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000795{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000796 ProcessAttachInfo attach_info;
797 return DoAttachToProcessWithID(attach_pid, attach_info);
798}
799
800Error
801ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
802{
Chris Lattner24943d22010-06-08 16:52:24 +0000803 Error error;
804 // Clear out and clean up from any current state
805 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000806 if (attach_pid != LLDB_INVALID_PROCESS_ID)
807 {
Greg Claytona2f74232011-02-24 22:24:29 +0000808 // Make sure we aren't already connected?
809 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000810 {
Greg Claytona2f74232011-02-24 22:24:29 +0000811 char host_port[128];
812 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
813 char connect_url[128];
814 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000815
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000816 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000817
818 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000819 {
Greg Claytona2f74232011-02-24 22:24:29 +0000820 const char *error_string = error.AsCString();
821 if (error_string == NULL)
822 error_string = "unable to launch " DEBUGSERVER_BASENAME;
823
824 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000825 }
Greg Claytona2f74232011-02-24 22:24:29 +0000826 else
827 {
828 error = ConnectToDebugserver (connect_url);
829 }
830 }
831
832 if (error.Success())
833 {
834 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000835 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000836 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000837 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000838 }
839 }
Chris Lattner24943d22010-06-08 16:52:24 +0000840 return error;
841}
842
843size_t
844ProcessGDBRemote::AttachInputReaderCallback
845(
846 void *baton,
847 InputReader *reader,
848 lldb::InputReaderAction notification,
849 const char *bytes,
850 size_t bytes_len
851)
852{
853 if (notification == eInputReaderGotToken)
854 {
855 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
856 if (gdb_process->m_waiting_for_attach)
857 gdb_process->m_waiting_for_attach = false;
858 reader->SetIsDone(true);
859 return 1;
860 }
861 return 0;
862}
863
864Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000865ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000866{
867 Error error;
868 // Clear out and clean up from any current state
869 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000870
Chris Lattner24943d22010-06-08 16:52:24 +0000871 if (process_name && process_name[0])
872 {
Greg Claytona2f74232011-02-24 22:24:29 +0000873 // Make sure we aren't already connected?
874 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000875 {
Greg Claytona2f74232011-02-24 22:24:29 +0000876 char host_port[128];
877 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
878 char connect_url[128];
879 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
880
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000881 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000882 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000883 {
Greg Claytona2f74232011-02-24 22:24:29 +0000884 const char *error_string = error.AsCString();
885 if (error_string == NULL)
886 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000887
Greg Claytona2f74232011-02-24 22:24:29 +0000888 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000889 }
Greg Claytona2f74232011-02-24 22:24:29 +0000890 else
891 {
892 error = ConnectToDebugserver (connect_url);
893 }
894 }
895
896 if (error.Success())
897 {
898 StreamString packet;
899
900 if (wait_for_launch)
901 packet.PutCString("vAttachWait");
902 else
903 packet.PutCString("vAttachName");
904 packet.PutChar(';');
905 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
906
907 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
908
Chris Lattner24943d22010-06-08 16:52:24 +0000909 }
910 }
Chris Lattner24943d22010-06-08 16:52:24 +0000911 return error;
912}
913
Chris Lattner24943d22010-06-08 16:52:24 +0000914
915void
916ProcessGDBRemote::DidAttach ()
917{
Greg Claytone71e2582011-02-04 01:58:07 +0000918 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000919}
920
921Error
922ProcessGDBRemote::WillResume ()
923{
Greg Claytonc1f45872011-02-12 06:28:37 +0000924 m_continue_c_tids.clear();
925 m_continue_C_tids.clear();
926 m_continue_s_tids.clear();
927 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000928 return Error();
929}
930
931Error
932ProcessGDBRemote::DoResume ()
933{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000934 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000935 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
936 if (log)
937 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000938
939 Listener listener ("gdb-remote.resume-packet-sent");
940 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
941 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000942 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
943
Greg Claytonc1f45872011-02-12 06:28:37 +0000944 StreamString continue_packet;
945 bool continue_packet_error = false;
946 if (m_gdb_comm.HasAnyVContSupport ())
947 {
948 continue_packet.PutCString ("vCont");
949
950 if (!m_continue_c_tids.empty())
951 {
952 if (m_gdb_comm.GetVContSupported ('c'))
953 {
954 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 +0000955 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000956 }
957 else
958 continue_packet_error = true;
959 }
960
961 if (!continue_packet_error && !m_continue_C_tids.empty())
962 {
963 if (m_gdb_comm.GetVContSupported ('C'))
964 {
965 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 +0000966 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000967 }
968 else
969 continue_packet_error = true;
970 }
Greg Claytonb749a262010-12-03 06:02:24 +0000971
Greg Claytonc1f45872011-02-12 06:28:37 +0000972 if (!continue_packet_error && !m_continue_s_tids.empty())
973 {
974 if (m_gdb_comm.GetVContSupported ('s'))
975 {
976 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 +0000977 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000978 }
979 else
980 continue_packet_error = true;
981 }
982
983 if (!continue_packet_error && !m_continue_S_tids.empty())
984 {
985 if (m_gdb_comm.GetVContSupported ('S'))
986 {
987 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 +0000988 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000989 }
990 else
991 continue_packet_error = true;
992 }
993
994 if (continue_packet_error)
995 continue_packet.GetString().clear();
996 }
997 else
998 continue_packet_error = true;
999
1000 if (continue_packet_error)
1001 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001002 // Either no vCont support, or we tried to use part of the vCont
1003 // packet that wasn't supported by the remote GDB server.
1004 // We need to try and make a simple packet that can do our continue
1005 const size_t num_threads = GetThreadList().GetSize();
1006 const size_t num_continue_c_tids = m_continue_c_tids.size();
1007 const size_t num_continue_C_tids = m_continue_C_tids.size();
1008 const size_t num_continue_s_tids = m_continue_s_tids.size();
1009 const size_t num_continue_S_tids = m_continue_S_tids.size();
1010 if (num_continue_c_tids > 0)
1011 {
1012 if (num_continue_c_tids == num_threads)
1013 {
1014 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001015 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001016 continue_packet.PutChar ('c');
1017 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001018 }
1019 else if (num_continue_c_tids == 1 &&
1020 num_continue_C_tids == 0 &&
1021 num_continue_s_tids == 0 &&
1022 num_continue_S_tids == 0 )
1023 {
1024 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001025 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001026 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001027 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001028 }
1029 }
1030
Greg Claytonde1dd812011-06-24 03:21:43 +00001031 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001032 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001033 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1034 num_continue_C_tids > 0 &&
1035 num_continue_s_tids == 0 &&
1036 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001037 {
1038 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001039 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001040 if (num_continue_C_tids > 1)
1041 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001042 // More that one thread with a signal, yet we don't have
1043 // vCont support and we are being asked to resume each
1044 // thread with a signal, we need to make sure they are
1045 // all the same signal, or we can't issue the continue
1046 // accurately with the current support...
1047 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001048 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001049 continue_packet_error = false;
1050 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1051 {
1052 if (m_continue_C_tids[i].second != continue_signo)
1053 continue_packet_error = true;
1054 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001055 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001056 if (!continue_packet_error)
1057 m_gdb_comm.SetCurrentThreadForRun (-1);
1058 }
1059 else
1060 {
1061 // Set the continue thread ID
1062 continue_packet_error = false;
1063 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001064 }
1065 if (!continue_packet_error)
1066 {
1067 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001068 continue_packet.Printf("C%2.2x", continue_signo);
1069 }
1070 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001071 }
1072
Greg Claytonde1dd812011-06-24 03:21:43 +00001073 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001074 {
1075 if (num_continue_s_tids == num_threads)
1076 {
1077 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001078 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001079 continue_packet.PutChar ('s');
1080 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001081 }
1082 else if (num_continue_c_tids == 0 &&
1083 num_continue_C_tids == 0 &&
1084 num_continue_s_tids == 1 &&
1085 num_continue_S_tids == 0 )
1086 {
1087 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001088 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001089 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001090 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001091 }
1092 }
1093
1094 if (!continue_packet_error && num_continue_S_tids > 0)
1095 {
1096 if (num_continue_S_tids == num_threads)
1097 {
1098 const int step_signo = m_continue_S_tids.front().second;
1099 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001100 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001101 if (num_continue_S_tids > 1)
1102 {
1103 for (size_t i=1; i<num_threads; ++i)
1104 {
1105 if (m_continue_S_tids[i].second != step_signo)
1106 continue_packet_error = true;
1107 }
1108 }
1109 if (!continue_packet_error)
1110 {
1111 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001112 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001113 continue_packet.Printf("S%2.2x", step_signo);
1114 }
1115 }
1116 else if (num_continue_c_tids == 0 &&
1117 num_continue_C_tids == 0 &&
1118 num_continue_s_tids == 0 &&
1119 num_continue_S_tids == 1 )
1120 {
1121 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001122 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001123 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001124 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001125 }
1126 }
1127 }
1128
1129 if (continue_packet_error)
1130 {
1131 error.SetErrorString ("can't make continue packet for this resume");
1132 }
1133 else
1134 {
1135 EventSP event_sp;
1136 TimeValue timeout;
1137 timeout = TimeValue::Now();
1138 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001139 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1140 {
1141 error.SetErrorString ("Trying to resume but the async thread is dead.");
1142 if (log)
1143 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1144 return error;
1145 }
1146
Greg Claytonc1f45872011-02-12 06:28:37 +00001147 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1148
1149 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001150 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001151 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001152 if (log)
1153 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1154 }
1155 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1156 {
1157 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1158 if (log)
1159 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1160 return error;
1161 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001162 }
Greg Claytonb749a262010-12-03 06:02:24 +00001163 }
1164
Jim Ingham3ae449a2010-11-17 02:32:00 +00001165 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001166}
1167
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001168void
1169ProcessGDBRemote::ClearThreadIDList ()
1170{
Greg Claytonff3448e2012-04-13 02:11:32 +00001171 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001172 m_thread_ids.clear();
1173}
1174
1175bool
1176ProcessGDBRemote::UpdateThreadIDList ()
1177{
Greg Claytonff3448e2012-04-13 02:11:32 +00001178 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001179 bool sequence_mutex_unavailable = false;
1180 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1181 if (sequence_mutex_unavailable)
1182 {
1183#if defined (LLDB_CONFIGURATION_DEBUG)
1184 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1185#endif
1186 return false; // We just didn't get the list
1187 }
1188 return true;
1189}
1190
Greg Claytonae932352012-04-10 00:18:59 +00001191bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001192ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001193{
1194 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001195 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001196 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001197 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001198
1199 size_t num_thread_ids = m_thread_ids.size();
1200 // The "m_thread_ids" thread ID list should always be updated after each stop
1201 // reply packet, but in case it isn't, update it here.
1202 if (num_thread_ids == 0)
1203 {
1204 if (!UpdateThreadIDList ())
1205 return false;
1206 num_thread_ids = m_thread_ids.size();
1207 }
Chris Lattner24943d22010-06-08 16:52:24 +00001208
Greg Clayton37f962e2011-08-22 02:49:39 +00001209 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001210 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001211 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001212 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001213 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001214 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1215 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001216 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001217 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001218 }
Chris Lattner24943d22010-06-08 16:52:24 +00001219 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001220
Greg Claytonae932352012-04-10 00:18:59 +00001221 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001222}
1223
1224
1225StateType
1226ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1227{
Greg Clayton261a18b2011-06-02 22:22:38 +00001228 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001229 const char stop_type = stop_packet.GetChar();
1230 switch (stop_type)
1231 {
1232 case 'T':
1233 case 'S':
1234 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001235 if (GetStopID() == 0)
1236 {
1237 // Our first stop, make sure we have a process ID, and also make
1238 // sure we know about our registers
1239 if (GetID() == LLDB_INVALID_PROCESS_ID)
1240 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001241 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001242 if (pid != LLDB_INVALID_PROCESS_ID)
1243 SetID (pid);
1244 }
1245 BuildDynamicRegisterInfo (true);
1246 }
Chris Lattner24943d22010-06-08 16:52:24 +00001247 // Stop with signal and thread info
1248 const uint8_t signo = stop_packet.GetHexU8();
1249 std::string name;
1250 std::string value;
1251 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001252 std::string reason;
1253 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001254 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001255 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001256 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1257 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001258 ThreadSP thread_sp;
1259
Chris Lattner24943d22010-06-08 16:52:24 +00001260 while (stop_packet.GetNameColonValue(name, value))
1261 {
1262 if (name.compare("metype") == 0)
1263 {
1264 // exception type in big endian hex
1265 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1266 }
1267 else if (name.compare("mecount") == 0)
1268 {
1269 // exception count in big endian hex
1270 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1271 }
1272 else if (name.compare("medata") == 0)
1273 {
1274 // exception data in big endian hex
1275 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1276 }
1277 else if (name.compare("thread") == 0)
1278 {
1279 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001280 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001281 // m_thread_list does have its own mutex, but we need to
1282 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1283 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001284 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001285 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001286 if (!thread_sp)
1287 {
1288 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001289 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001290 m_thread_list.AddThread(thread_sp);
1291 }
Chris Lattner24943d22010-06-08 16:52:24 +00001292 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001293 else if (name.compare("threads") == 0)
1294 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001295 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001296 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001297 // A comma separated list of all threads in the current
1298 // process that includes the thread for this stop reply
1299 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001300 size_t comma_pos;
1301 lldb::tid_t tid;
1302 while ((comma_pos = value.find(',')) != std::string::npos)
1303 {
1304 value[comma_pos] = '\0';
1305 // thread in big endian hex
1306 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1307 if (tid != LLDB_INVALID_THREAD_ID)
1308 m_thread_ids.push_back (tid);
1309 value.erase(0, comma_pos + 1);
1310
1311 }
1312 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1313 if (tid != LLDB_INVALID_THREAD_ID)
1314 m_thread_ids.push_back (tid);
1315 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001316 else if (name.compare("hexname") == 0)
1317 {
1318 StringExtractor name_extractor;
1319 // Swap "value" over into "name_extractor"
1320 name_extractor.GetStringRef().swap(value);
1321 // Now convert the HEX bytes into a string value
1322 name_extractor.GetHexByteString (value);
1323 thread_name.swap (value);
1324 }
Chris Lattner24943d22010-06-08 16:52:24 +00001325 else if (name.compare("name") == 0)
1326 {
1327 thread_name.swap (value);
1328 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001329 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001330 {
1331 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1332 }
Greg Clayton65611552011-06-04 01:26:29 +00001333 else if (name.compare("reason") == 0)
1334 {
1335 reason.swap(value);
1336 }
1337 else if (name.compare("description") == 0)
1338 {
1339 StringExtractor desc_extractor;
1340 // Swap "value" over into "name_extractor"
1341 desc_extractor.GetStringRef().swap(value);
1342 // Now convert the HEX bytes into a string value
1343 desc_extractor.GetHexByteString (thread_name);
1344 }
Greg Claytona875b642011-01-09 21:07:35 +00001345 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1346 {
1347 // We have a register number that contains an expedited
1348 // register value. Lets supply this register to our thread
1349 // so it won't have to go and read it.
1350 if (thread_sp)
1351 {
1352 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1353
1354 if (reg != UINT32_MAX)
1355 {
1356 StringExtractor reg_value_extractor;
1357 // Swap "value" over into "reg_value_extractor"
1358 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001359 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1360 {
1361 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1362 name.c_str(),
1363 reg,
1364 reg,
1365 reg_value_extractor.GetStringRef().c_str(),
1366 stop_packet.GetStringRef().c_str());
1367 }
Greg Claytona875b642011-01-09 21:07:35 +00001368 }
1369 }
1370 }
Chris Lattner24943d22010-06-08 16:52:24 +00001371 }
Chris Lattner24943d22010-06-08 16:52:24 +00001372
1373 if (thread_sp)
1374 {
1375 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1376
1377 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001378 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001379 if (exc_type != 0)
1380 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001381 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001382
1383 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1384 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001385 exc_data_size,
1386 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001387 exc_data_size >= 2 ? exc_data[1] : 0,
1388 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001389 }
Greg Clayton65611552011-06-04 01:26:29 +00001390 else
Chris Lattner24943d22010-06-08 16:52:24 +00001391 {
Greg Clayton65611552011-06-04 01:26:29 +00001392 bool handled = false;
1393 if (!reason.empty())
1394 {
1395 if (reason.compare("trace") == 0)
1396 {
1397 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1398 handled = true;
1399 }
1400 else if (reason.compare("breakpoint") == 0)
1401 {
1402 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001403 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001404 if (bp_site_sp)
1405 {
1406 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1407 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1408 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1409 if (bp_site_sp->ValidForThisThread (gdb_thread))
1410 {
1411 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1412 handled = true;
1413 }
1414 }
1415
1416 if (!handled)
1417 {
1418 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1419 }
1420 }
1421 else if (reason.compare("trap") == 0)
1422 {
1423 // Let the trap just use the standard signal stop reason below...
1424 }
1425 else if (reason.compare("watchpoint") == 0)
1426 {
1427 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1428 // TODO: locate the watchpoint somehow...
1429 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1430 handled = true;
1431 }
1432 else if (reason.compare("exception") == 0)
1433 {
1434 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1435 handled = true;
1436 }
1437 }
1438
1439 if (signo)
1440 {
1441 if (signo == SIGTRAP)
1442 {
1443 // Currently we are going to assume SIGTRAP means we are either
1444 // hitting a breakpoint or hardware single stepping.
1445 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001446 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001447 if (bp_site_sp)
1448 {
1449 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1450 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1451 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1452 if (bp_site_sp->ValidForThisThread (gdb_thread))
1453 {
1454 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1455 handled = true;
1456 }
1457 }
1458 if (!handled)
1459 {
1460 // TODO: check for breakpoint or trap opcode in case there is a hard
1461 // coded software trap
1462 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1463 handled = true;
1464 }
1465 }
1466 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001467 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001468 }
1469 else
1470 {
Greg Clayton643ee732010-08-04 01:40:35 +00001471 StopInfoSP invalid_stop_info_sp;
1472 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001473 }
Greg Clayton65611552011-06-04 01:26:29 +00001474
1475 if (!description.empty())
1476 {
1477 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1478 if (stop_info_sp)
1479 {
1480 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001481 }
Greg Clayton65611552011-06-04 01:26:29 +00001482 else
1483 {
1484 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1485 }
1486 }
1487 }
Chris Lattner24943d22010-06-08 16:52:24 +00001488 }
1489 return eStateStopped;
1490 }
1491 break;
1492
1493 case 'W':
1494 // process exited
1495 return eStateExited;
1496
1497 default:
1498 break;
1499 }
1500 return eStateInvalid;
1501}
1502
1503void
1504ProcessGDBRemote::RefreshStateAfterStop ()
1505{
Greg Claytonff3448e2012-04-13 02:11:32 +00001506 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001507 m_thread_ids.clear();
1508 // Set the thread stop info. It might have a "threads" key whose value is
1509 // a list of all thread IDs in the current process, so m_thread_ids might
1510 // get set.
1511 SetThreadStopInfo (m_last_stop_packet);
1512 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1513 if (m_thread_ids.empty())
1514 {
1515 // No, we need to fetch the thread list manually
1516 UpdateThreadIDList();
1517 }
1518
Chris Lattner24943d22010-06-08 16:52:24 +00001519 // Let all threads recover from stopping and do any clean up based
1520 // on the previous thread state (if any).
1521 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001522
Chris Lattner24943d22010-06-08 16:52:24 +00001523}
1524
1525Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001526ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001527{
1528 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001529
Greg Claytona4881d02011-01-22 07:12:45 +00001530 bool timed_out = false;
1531 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001532
1533 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001534 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001535 // We are being asked to halt during an attach. We need to just close
1536 // our file handle and debugserver will go away, and we can be done...
1537 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001538 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001539 else
1540 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001541 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001542 {
1543 if (timed_out)
1544 error.SetErrorString("timed out sending interrupt packet");
1545 else
1546 error.SetErrorString("unknown error sending interrupt packet");
1547 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001548
1549 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001550 }
Chris Lattner24943d22010-06-08 16:52:24 +00001551 return error;
1552}
1553
1554Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001555ProcessGDBRemote::InterruptIfRunning
1556(
1557 bool discard_thread_plans,
1558 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001559 EventSP &stop_event_sp
1560)
Chris Lattner24943d22010-06-08 16:52:24 +00001561{
1562 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001563
Greg Clayton2860ba92011-01-23 19:58:49 +00001564 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1565
Greg Clayton68ca8232011-01-25 02:58:48 +00001566 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001567 const bool is_running = m_gdb_comm.IsRunning();
1568 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001569 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001570 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001571 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001572 is_running);
1573
Greg Clayton2860ba92011-01-23 19:58:49 +00001574 if (discard_thread_plans)
1575 {
1576 if (log)
1577 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1578 m_thread_list.DiscardThreadPlans();
1579 }
1580 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001581 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001582 if (catch_stop_event)
1583 {
1584 if (log)
1585 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1586 PausePrivateStateThread();
1587 paused_private_state_thread = true;
1588 }
1589
Greg Clayton4fb400f2010-09-27 21:07:38 +00001590 bool timed_out = false;
1591 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001592
Greg Clayton05e4d972012-03-29 01:55:41 +00001593 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001594 {
1595 if (timed_out)
1596 error.SetErrorString("timed out sending interrupt packet");
1597 else
1598 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001599 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001600 ResumePrivateStateThread();
1601 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001602 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001603
Greg Clayton72e1c782011-01-22 23:43:18 +00001604 if (catch_stop_event)
1605 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001606 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001607 TimeValue timeout_time;
1608 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001609 timeout_time.OffsetWithSeconds(5);
1610 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001611
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001612 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001613 if (log)
1614 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001615
Greg Clayton2860ba92011-01-23 19:58:49 +00001616 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001617 error.SetErrorString("unable to verify target stopped");
1618 }
1619
Greg Clayton68ca8232011-01-25 02:58:48 +00001620 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001621 {
1622 if (log)
1623 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001624 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001625 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001626 }
Chris Lattner24943d22010-06-08 16:52:24 +00001627 return error;
1628}
1629
Greg Clayton4fb400f2010-09-27 21:07:38 +00001630Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001631ProcessGDBRemote::WillDetach ()
1632{
Greg Clayton2860ba92011-01-23 19:58:49 +00001633 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1634 if (log)
1635 log->Printf ("ProcessGDBRemote::WillDetach()");
1636
Greg Clayton72e1c782011-01-22 23:43:18 +00001637 bool discard_thread_plans = true;
1638 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001639 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001640 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001641}
1642
1643Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001644ProcessGDBRemote::DoDetach()
1645{
1646 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001647 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001648 if (log)
1649 log->Printf ("ProcessGDBRemote::DoDetach()");
1650
1651 DisableAllBreakpointSites ();
1652
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001653 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001654
Greg Clayton516f0842012-04-11 00:24:49 +00001655 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001656 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001657 {
Greg Clayton516f0842012-04-11 00:24:49 +00001658 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001659 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1660 else
1661 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001662 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001663 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001664 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001665
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001666 SetPrivateState (eStateDetached);
1667 ResumePrivateStateThread();
1668
1669 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001670 return error;
1671}
Chris Lattner24943d22010-06-08 16:52:24 +00001672
1673Error
1674ProcessGDBRemote::DoDestroy ()
1675{
1676 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001677 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001678 if (log)
1679 log->Printf ("ProcessGDBRemote::DoDestroy()");
1680
1681 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001682 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001683 {
Jim Ingham8226e942011-10-28 01:11:35 +00001684 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001685 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001686
1687 StringExtractorGDBRemote response;
1688 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001689 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001690 {
1691 char packet_cmd = response.GetChar(0);
1692
1693 if (packet_cmd == 'W' || packet_cmd == 'X')
1694 {
Greg Clayton06709002011-12-06 04:51:14 +00001695 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001696 ClearThreadIDList ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001697 SetExitStatus(response.GetHexU8(), NULL);
1698 }
1699 }
1700 else
1701 {
1702 SetExitStatus(SIGABRT, NULL);
1703 //error.SetErrorString("kill packet failed");
1704 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001705 }
1706 }
Chris Lattner24943d22010-06-08 16:52:24 +00001707 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001708 KillDebugserverProcess ();
1709 return error;
1710}
1711
Chris Lattner24943d22010-06-08 16:52:24 +00001712//------------------------------------------------------------------
1713// Process Queries
1714//------------------------------------------------------------------
1715
1716bool
1717ProcessGDBRemote::IsAlive ()
1718{
Greg Clayton58e844b2010-12-08 05:08:21 +00001719 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001720}
1721
1722addr_t
1723ProcessGDBRemote::GetImageInfoAddress()
1724{
Greg Clayton516f0842012-04-11 00:24:49 +00001725 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001726}
1727
Chris Lattner24943d22010-06-08 16:52:24 +00001728//------------------------------------------------------------------
1729// Process Memory
1730//------------------------------------------------------------------
1731size_t
1732ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1733{
1734 if (size > m_max_memory_size)
1735 {
1736 // Keep memory read sizes down to a sane limit. This function will be
1737 // called multiple times in order to complete the task by
1738 // lldb_private::Process so it is ok to do this.
1739 size = m_max_memory_size;
1740 }
1741
1742 char packet[64];
1743 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1744 assert (packet_len + 1 < sizeof(packet));
1745 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001746 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001747 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001748 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001749 {
1750 error.Clear();
1751 return response.GetHexBytes(buf, size, '\xdd');
1752 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001753 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001754 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001755 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001756 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1757 else
1758 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1759 }
1760 else
1761 {
1762 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1763 }
1764 return 0;
1765}
1766
1767size_t
1768ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1769{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001770 if (size > m_max_memory_size)
1771 {
1772 // Keep memory read sizes down to a sane limit. This function will be
1773 // called multiple times in order to complete the task by
1774 // lldb_private::Process so it is ok to do this.
1775 size = m_max_memory_size;
1776 }
1777
Chris Lattner24943d22010-06-08 16:52:24 +00001778 StreamString packet;
1779 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001780 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001781 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001782 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001783 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001784 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001785 {
1786 error.Clear();
1787 return size;
1788 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001789 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001790 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001791 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001792 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1793 else
1794 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1795 }
1796 else
1797 {
1798 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1799 }
1800 return 0;
1801}
1802
1803lldb::addr_t
1804ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1805{
Greg Clayton989816b2011-05-14 01:50:35 +00001806 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1807
Greg Clayton2f085c62011-05-15 01:25:55 +00001808 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001809 switch (supported)
1810 {
1811 case eLazyBoolCalculate:
1812 case eLazyBoolYes:
1813 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1814 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1815 return allocated_addr;
1816
1817 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001818 // Call mmap() to create memory in the inferior..
1819 unsigned prot = 0;
1820 if (permissions & lldb::ePermissionsReadable)
1821 prot |= eMmapProtRead;
1822 if (permissions & lldb::ePermissionsWritable)
1823 prot |= eMmapProtWrite;
1824 if (permissions & lldb::ePermissionsExecutable)
1825 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001826
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001827 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1828 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1829 m_addr_to_mmap_size[allocated_addr] = size;
1830 else
1831 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001832 break;
1833 }
1834
Chris Lattner24943d22010-06-08 16:52:24 +00001835 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001836 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001837 else
1838 error.Clear();
1839 return allocated_addr;
1840}
1841
1842Error
Greg Claytona9385532011-11-18 07:03:08 +00001843ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1844 MemoryRegionInfo &region_info)
1845{
1846
1847 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1848 return error;
1849}
1850
1851Error
Chris Lattner24943d22010-06-08 16:52:24 +00001852ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1853{
1854 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001855 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1856
1857 switch (supported)
1858 {
1859 case eLazyBoolCalculate:
1860 // We should never be deallocating memory without allocating memory
1861 // first so we should never get eLazyBoolCalculate
1862 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1863 break;
1864
1865 case eLazyBoolYes:
1866 if (!m_gdb_comm.DeallocateMemory (addr))
1867 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1868 break;
1869
1870 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001871 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001872 {
1873 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001874 if (pos != m_addr_to_mmap_size.end() &&
1875 InferiorCallMunmap(this, addr, pos->second))
1876 m_addr_to_mmap_size.erase (pos);
1877 else
1878 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001879 }
1880 break;
1881 }
1882
Chris Lattner24943d22010-06-08 16:52:24 +00001883 return error;
1884}
1885
1886
1887//------------------------------------------------------------------
1888// Process STDIO
1889//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001890size_t
1891ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1892{
1893 if (m_stdio_communication.IsConnected())
1894 {
1895 ConnectionStatus status;
1896 m_stdio_communication.Write(src, src_len, status, NULL);
1897 }
1898 return 0;
1899}
1900
1901Error
1902ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1903{
1904 Error error;
1905 assert (bp_site != NULL);
1906
Greg Claytone005f2c2010-11-06 01:53:30 +00001907 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001908 user_id_t site_id = bp_site->GetID();
1909 const addr_t addr = bp_site->GetLoadAddress();
1910 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001911 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001912
1913 if (bp_site->IsEnabled())
1914 {
1915 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001916 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 +00001917 return error;
1918 }
1919 else
1920 {
1921 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1922
1923 if (bp_site->HardwarePreferred())
1924 {
1925 // Try and set hardware breakpoint, and if that fails, fall through
1926 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001927 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001928 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001929 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001930 {
1931 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001932 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001933 return error;
1934 }
Chris Lattner24943d22010-06-08 16:52:24 +00001935 }
1936 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001937
1938 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001939 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001940 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1941 {
1942 bp_site->SetEnabled(true);
1943 bp_site->SetType (BreakpointSite::eExternal);
1944 return error;
1945 }
Chris Lattner24943d22010-06-08 16:52:24 +00001946 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001947
1948 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001949 }
1950
1951 if (log)
1952 {
1953 const char *err_string = error.AsCString();
1954 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1955 bp_site->GetLoadAddress(),
1956 err_string ? err_string : "NULL");
1957 }
1958 // We shouldn't reach here on a successful breakpoint enable...
1959 if (error.Success())
1960 error.SetErrorToGenericError();
1961 return error;
1962}
1963
1964Error
1965ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1966{
1967 Error error;
1968 assert (bp_site != NULL);
1969 addr_t addr = bp_site->GetLoadAddress();
1970 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001971 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001972 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001973 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001974
1975 if (bp_site->IsEnabled())
1976 {
1977 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1978
Greg Claytonb72d0f02011-04-12 05:54:46 +00001979 BreakpointSite::Type bp_type = bp_site->GetType();
1980 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001981 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001982 case BreakpointSite::eSoftware:
1983 error = DisableSoftwareBreakpoint (bp_site);
1984 break;
1985
1986 case BreakpointSite::eHardware:
1987 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1988 error.SetErrorToGenericError();
1989 break;
1990
1991 case BreakpointSite::eExternal:
1992 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1993 error.SetErrorToGenericError();
1994 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001995 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001996 if (error.Success())
1997 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001998 }
1999 else
2000 {
2001 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002002 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 +00002003 return error;
2004 }
2005
2006 if (error.Success())
2007 error.SetErrorToGenericError();
2008 return error;
2009}
2010
Johnny Chen21900fb2011-09-06 22:38:36 +00002011// Pre-requisite: wp != NULL.
2012static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002013GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002014{
2015 assert(wp);
2016 bool watch_read = wp->WatchpointRead();
2017 bool watch_write = wp->WatchpointWrite();
2018
2019 // watch_read and watch_write cannot both be false.
2020 assert(watch_read || watch_write);
2021 if (watch_read && watch_write)
2022 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002023 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002024 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002025 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002026 return eWatchpointWrite;
2027}
2028
Chris Lattner24943d22010-06-08 16:52:24 +00002029Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002030ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002031{
2032 Error error;
2033 if (wp)
2034 {
2035 user_id_t watchID = wp->GetID();
2036 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002037 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002038 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002039 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002040 if (wp->IsEnabled())
2041 {
2042 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002043 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002044 return error;
2045 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002046
2047 GDBStoppointType type = GetGDBStoppointType(wp);
2048 // Pass down an appropriate z/Z packet...
2049 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002050 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002051 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2052 {
2053 wp->SetEnabled(true);
2054 return error;
2055 }
2056 else
2057 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002058 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002059 else
2060 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002061 }
2062 else
2063 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002064 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002065 }
2066 if (error.Success())
2067 error.SetErrorToGenericError();
2068 return error;
2069}
2070
2071Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002072ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002073{
2074 Error error;
2075 if (wp)
2076 {
2077 user_id_t watchID = wp->GetID();
2078
Greg Claytone005f2c2010-11-06 01:53:30 +00002079 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002080
2081 addr_t addr = wp->GetLoadAddress();
2082 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002083 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002084
Johnny Chen21900fb2011-09-06 22:38:36 +00002085 if (!wp->IsEnabled())
2086 {
2087 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002088 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002089 return error;
2090 }
2091
Chris Lattner24943d22010-06-08 16:52:24 +00002092 if (wp->IsHardware())
2093 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002094 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002095 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002096 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2097 {
2098 wp->SetEnabled(false);
2099 return error;
2100 }
2101 else
2102 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002103 }
2104 // TODO: clear software watchpoints if we implement them
2105 }
2106 else
2107 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002108 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002109 }
2110 if (error.Success())
2111 error.SetErrorToGenericError();
2112 return error;
2113}
2114
2115void
2116ProcessGDBRemote::Clear()
2117{
2118 m_flags = 0;
2119 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002120}
2121
2122Error
2123ProcessGDBRemote::DoSignal (int signo)
2124{
2125 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002126 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002127 if (log)
2128 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2129
2130 if (!m_gdb_comm.SendAsyncSignal (signo))
2131 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2132 return error;
2133}
2134
Chris Lattner24943d22010-06-08 16:52:24 +00002135Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002136ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2137{
2138 ProcessLaunchInfo launch_info;
2139 return StartDebugserverProcess(debugserver_url, launch_info);
2140}
2141
2142Error
2143ProcessGDBRemote::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 +00002144{
2145 Error error;
2146 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2147 {
2148 // If we locate debugserver, keep that located version around
2149 static FileSpec g_debugserver_file_spec;
2150
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002151 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002152 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002153 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002154
2155 // Always check to see if we have an environment override for the path
2156 // to the debugserver to use and use it if we do.
2157 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2158 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002159 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002160 else
2161 debugserver_file_spec = g_debugserver_file_spec;
2162 bool debugserver_exists = debugserver_file_spec.Exists();
2163 if (!debugserver_exists)
2164 {
2165 // The debugserver binary is in the LLDB.framework/Resources
2166 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002167 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002168 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002169 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002170 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002171 if (debugserver_exists)
2172 {
2173 g_debugserver_file_spec = debugserver_file_spec;
2174 }
2175 else
2176 {
2177 g_debugserver_file_spec.Clear();
2178 debugserver_file_spec.Clear();
2179 }
Chris Lattner24943d22010-06-08 16:52:24 +00002180 }
2181 }
2182
2183 if (debugserver_exists)
2184 {
2185 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2186
2187 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002188
Greg Claytone005f2c2010-11-06 01:53:30 +00002189 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002190
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002191 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002192 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002193
Chris Lattner24943d22010-06-08 16:52:24 +00002194 // Start args with "debugserver /file/path -r --"
2195 debugserver_args.AppendArgument(debugserver_path);
2196 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002197 // use native registers, not the GDB registers
2198 debugserver_args.AppendArgument("--native-regs");
2199 // make debugserver run in its own session so signals generated by
2200 // special terminal key sequences (^C) don't affect debugserver
2201 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002202
Chris Lattner24943d22010-06-08 16:52:24 +00002203 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2204 if (env_debugserver_log_file)
2205 {
2206 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2207 debugserver_args.AppendArgument(arg_cstr);
2208 }
2209
2210 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2211 if (env_debugserver_log_flags)
2212 {
2213 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2214 debugserver_args.AppendArgument(arg_cstr);
2215 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002216// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002217// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002218
Greg Claytonb72d0f02011-04-12 05:54:46 +00002219 // We currently send down all arguments, attach pids, or attach
2220 // process names in dedicated GDB server packets, so we don't need
2221 // to pass them as arguments. This is currently because of all the
2222 // things we need to setup prior to launching: the environment,
2223 // current working dir, file actions, etc.
2224#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002225 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002226 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002227 {
Greg Claytona2f74232011-02-24 22:24:29 +00002228 // Terminate the debugserver args so we can now append the inferior args
2229 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002230
Greg Claytona2f74232011-02-24 22:24:29 +00002231 for (int i = 0; inferior_argv[i] != NULL; ++i)
2232 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002233 }
2234 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2235 {
2236 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2237 debugserver_args.AppendArgument (arg_cstr);
2238 }
2239 else if (attach_name && attach_name[0])
2240 {
2241 if (wait_for_launch)
2242 debugserver_args.AppendArgument ("--waitfor");
2243 else
2244 debugserver_args.AppendArgument ("--attach");
2245 debugserver_args.AppendArgument (attach_name);
2246 }
Chris Lattner24943d22010-06-08 16:52:24 +00002247#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002248
2249 ProcessLaunchInfo::FileAction file_action;
2250
2251 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2252 // to "/dev/null" if we run into any problems.
2253 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002254 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002255 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002256 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002257 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002258 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002259
2260 if (log)
2261 {
2262 StreamString strm;
2263 debugserver_args.Dump (&strm);
2264 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2265 }
2266
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002267 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2268 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002269
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002270 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002271
Greg Claytonb72d0f02011-04-12 05:54:46 +00002272 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002273 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002274 else
Chris Lattner24943d22010-06-08 16:52:24 +00002275 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2276
2277 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002278 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002279 }
2280 else
2281 {
Greg Clayton9c236732011-10-26 00:56:27 +00002282 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002283 }
2284
2285 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2286 StartAsyncThread ();
2287 }
2288 return error;
2289}
2290
2291bool
2292ProcessGDBRemote::MonitorDebugserverProcess
2293(
2294 void *callback_baton,
2295 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002296 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002297 int signo, // Zero for no signal
2298 int exit_status // Exit value of process if signal is zero
2299)
2300{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002301 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2302 // and might not exist anymore, so we need to carefully try to get the
2303 // target for this process first since we have a race condition when
2304 // we are done running between getting the notice that the inferior
2305 // process has died and the debugserver that was debugging this process.
2306 // In our test suite, we are also continually running process after
2307 // process, so we must be very careful to make sure:
2308 // 1 - process object hasn't been deleted already
2309 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002310
2311 // "debugserver_pid" argument passed in is the process ID for
2312 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002313 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002314
Greg Clayton75ccf502010-08-21 02:22:51 +00002315 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002316
Greg Clayton1c4642c2011-11-16 05:37:56 +00002317 // Get a shared pointer to the target that has a matching process pointer.
2318 // This target could be gone, or the target could already have a new process
2319 // object inside of it
2320 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2321
Greg Clayton72e1c782011-01-22 23:43:18 +00002322 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002323 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 +00002324
Greg Clayton1c4642c2011-11-16 05:37:56 +00002325 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002326 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002327 // We found a process in a target that matches, but another thread
2328 // might be in the process of launching a new process that will
2329 // soon replace it, so get a shared pointer to the process so we
2330 // can keep it alive.
2331 ProcessSP process_sp (target_sp->GetProcessSP());
2332 // Now we have a shared pointer to the process that can't go away on us
2333 // so we now make sure it was the same as the one passed in, and also make
2334 // sure that our previous "process *" didn't get deleted and have a new
2335 // "process *" created in its place with the same pointer. To verify this
2336 // we make sure the process has our debugserver process ID. If we pass all
2337 // of these tests, then we are sure that this process is the one we were
2338 // looking for.
2339 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002340 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002341 // Sleep for a half a second to make sure our inferior process has
2342 // time to set its exit status before we set it incorrectly when
2343 // both the debugserver and the inferior process shut down.
2344 usleep (500000);
2345 // If our process hasn't yet exited, debugserver might have died.
2346 // If the process did exit, the we are reaping it.
2347 const StateType state = process->GetState();
2348
2349 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2350 state != eStateInvalid &&
2351 state != eStateUnloaded &&
2352 state != eStateExited &&
2353 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002354 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002355 char error_str[1024];
2356 if (signo)
2357 {
2358 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2359 if (signal_cstr)
2360 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2361 else
2362 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2363 }
Chris Lattner24943d22010-06-08 16:52:24 +00002364 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002365 {
2366 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2367 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002368
Greg Clayton1c4642c2011-11-16 05:37:56 +00002369 process->SetExitStatus (-1, error_str);
2370 }
2371 // Debugserver has exited we need to let our ProcessGDBRemote
2372 // know that it no longer has a debugserver instance
2373 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002374 }
Chris Lattner24943d22010-06-08 16:52:24 +00002375 }
2376 return true;
2377}
2378
2379void
2380ProcessGDBRemote::KillDebugserverProcess ()
2381{
2382 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2383 {
2384 ::kill (m_debugserver_pid, SIGINT);
2385 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2386 }
2387}
2388
2389void
2390ProcessGDBRemote::Initialize()
2391{
2392 static bool g_initialized = false;
2393
2394 if (g_initialized == false)
2395 {
2396 g_initialized = true;
2397 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2398 GetPluginDescriptionStatic(),
2399 CreateInstance);
2400
2401 Log::Callbacks log_callbacks = {
2402 ProcessGDBRemoteLog::DisableLog,
2403 ProcessGDBRemoteLog::EnableLog,
2404 ProcessGDBRemoteLog::ListLogCategories
2405 };
2406
2407 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2408 }
2409}
2410
2411bool
Chris Lattner24943d22010-06-08 16:52:24 +00002412ProcessGDBRemote::StartAsyncThread ()
2413{
Greg Claytone005f2c2010-11-06 01:53:30 +00002414 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002415
2416 if (log)
2417 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2418
2419 // Create a thread that watches our internal state and controls which
2420 // events make it to clients (into the DCProcess event queue).
2421 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002422 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002423}
2424
2425void
2426ProcessGDBRemote::StopAsyncThread ()
2427{
Greg Claytone005f2c2010-11-06 01:53:30 +00002428 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002429
2430 if (log)
2431 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2432
2433 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002434
2435 // This will shut down the async thread.
2436 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002437
2438 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002439 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002440 {
2441 Host::ThreadJoin (m_async_thread, NULL, NULL);
2442 }
2443}
2444
2445
2446void *
2447ProcessGDBRemote::AsyncThread (void *arg)
2448{
2449 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2450
Greg Claytone005f2c2010-11-06 01:53:30 +00002451 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002452 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002453 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002454
2455 Listener listener ("ProcessGDBRemote::AsyncThread");
2456 EventSP event_sp;
2457 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2458 eBroadcastBitAsyncThreadShouldExit;
2459
2460 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2461 {
Greg Claytona2f74232011-02-24 22:24:29 +00002462 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2463
Chris Lattner24943d22010-06-08 16:52:24 +00002464 bool done = false;
2465 while (!done)
2466 {
2467 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002468 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002469 if (listener.WaitForEvent (NULL, event_sp))
2470 {
2471 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002472 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002473 {
Greg Claytona2f74232011-02-24 22:24:29 +00002474 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002475 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 +00002476
Greg Claytona2f74232011-02-24 22:24:29 +00002477 switch (event_type)
2478 {
2479 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002480 {
Greg Claytona2f74232011-02-24 22:24:29 +00002481 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002482
Greg Claytona2f74232011-02-24 22:24:29 +00002483 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002484 {
Greg Claytona2f74232011-02-24 22:24:29 +00002485 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2486 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2487 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002488 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002489
Greg Claytona2f74232011-02-24 22:24:29 +00002490 if (::strstr (continue_cstr, "vAttach") == NULL)
2491 process->SetPrivateState(eStateRunning);
2492 StringExtractorGDBRemote response;
2493 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002494
Greg Claytona2f74232011-02-24 22:24:29 +00002495 switch (stop_state)
2496 {
2497 case eStateStopped:
2498 case eStateCrashed:
2499 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002500 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002501 process->SetPrivateState (stop_state);
2502 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002503
Greg Claytona2f74232011-02-24 22:24:29 +00002504 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002505 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002506 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002507 response.SetFilePos(1);
2508 process->SetExitStatus(response.GetHexU8(), NULL);
2509 done = true;
2510 break;
2511
2512 case eStateInvalid:
2513 process->SetExitStatus(-1, "lost connection");
2514 break;
2515
2516 default:
2517 process->SetPrivateState (stop_state);
2518 break;
2519 }
Chris Lattner24943d22010-06-08 16:52:24 +00002520 }
2521 }
Greg Claytona2f74232011-02-24 22:24:29 +00002522 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002523
Greg Claytona2f74232011-02-24 22:24:29 +00002524 case eBroadcastBitAsyncThreadShouldExit:
2525 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002526 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002527 done = true;
2528 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002529
Greg Claytona2f74232011-02-24 22:24:29 +00002530 default:
2531 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002532 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 +00002533 done = true;
2534 break;
2535 }
2536 }
2537 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2538 {
2539 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2540 {
2541 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002542 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002543 }
Chris Lattner24943d22010-06-08 16:52:24 +00002544 }
2545 }
2546 else
2547 {
2548 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002549 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 +00002550 done = true;
2551 }
2552 }
2553 }
2554
2555 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002556 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002557
2558 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2559 return NULL;
2560}
2561
Chris Lattner24943d22010-06-08 16:52:24 +00002562const char *
2563ProcessGDBRemote::GetDispatchQueueNameForThread
2564(
2565 addr_t thread_dispatch_qaddr,
2566 std::string &dispatch_queue_name
2567)
2568{
2569 dispatch_queue_name.clear();
2570 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2571 {
2572 // Cache the dispatch_queue_offsets_addr value so we don't always have
2573 // to look it up
2574 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2575 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002576 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2577 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002578 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2579 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002580 if (module_sp)
2581 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2582
2583 if (dispatch_queue_offsets_symbol == NULL)
2584 {
Greg Clayton444fe992012-02-26 05:51:37 +00002585 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2586 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002587 if (module_sp)
2588 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2589 }
Chris Lattner24943d22010-06-08 16:52:24 +00002590 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002591 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002592
2593 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2594 return NULL;
2595 }
2596
2597 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002598 DataExtractor data (memory_buffer,
2599 sizeof(memory_buffer),
2600 m_target.GetArchitecture().GetByteOrder(),
2601 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002602
2603 // Excerpt from src/queue_private.h
2604 struct dispatch_queue_offsets_s
2605 {
2606 uint16_t dqo_version;
2607 uint16_t dqo_label;
2608 uint16_t dqo_label_size;
2609 } dispatch_queue_offsets;
2610
2611
2612 Error error;
2613 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2614 {
2615 uint32_t data_offset = 0;
2616 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2617 {
2618 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2619 {
2620 data_offset = 0;
2621 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2622 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2623 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2624 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2625 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2626 dispatch_queue_name.erase (bytes_read);
2627 }
2628 }
2629 }
2630 }
2631 if (dispatch_queue_name.empty())
2632 return NULL;
2633 return dispatch_queue_name.c_str();
2634}
2635
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002636//uint32_t
2637//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2638//{
2639// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2640// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2641// if (m_local_debugserver)
2642// {
2643// return Host::ListProcessesMatchingName (name, matches, pids);
2644// }
2645// else
2646// {
2647// // FIXME: Implement talking to the remote debugserver.
2648// return 0;
2649// }
2650//
2651//}
2652//
Jim Ingham55e01d82011-01-22 01:33:44 +00002653bool
2654ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2655 lldb_private::StoppointCallbackContext *context,
2656 lldb::user_id_t break_id,
2657 lldb::user_id_t break_loc_id)
2658{
2659 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2660 // run so I can stop it if that's what I want to do.
2661 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2662 if (log)
2663 log->Printf("Hit New Thread Notification breakpoint.");
2664 return false;
2665}
2666
2667
2668bool
2669ProcessGDBRemote::StartNoticingNewThreads()
2670{
2671 static const char *bp_names[] =
2672 {
2673 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002674 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002675 "_pthread_start",
2676 NULL
2677 };
2678
2679 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2680 size_t num_bps = m_thread_observation_bps.size();
2681 if (num_bps != 0)
2682 {
2683 for (int i = 0; i < num_bps; i++)
2684 {
2685 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2686 if (break_sp)
2687 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002688 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002689 log->Printf("Enabled noticing new thread breakpoint.");
2690 break_sp->SetEnabled(true);
2691 }
2692 }
2693 }
2694 else
2695 {
2696 for (int i = 0; bp_names[i] != NULL; i++)
2697 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002698 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002699 if (breakpoint)
2700 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002701 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002702 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2703 m_thread_observation_bps.push_back(breakpoint->GetID());
2704 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2705 }
2706 else
2707 {
2708 if (log)
2709 log->Printf("Failed to create new thread notification breakpoint.");
2710 return false;
2711 }
2712 }
2713 }
2714
2715 return true;
2716}
2717
2718bool
2719ProcessGDBRemote::StopNoticingNewThreads()
2720{
Jim Inghamff276fe2011-02-08 05:19:01 +00002721 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002722 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002723 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002724 size_t num_bps = m_thread_observation_bps.size();
2725 if (num_bps != 0)
2726 {
2727 for (int i = 0; i < num_bps; i++)
2728 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002729
2730 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2731 if (break_sp)
2732 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002733 break_sp->SetEnabled(false);
2734 }
2735 }
2736 }
2737 return true;
2738}
2739
2740