blob: ffb165d279cb10373eb3cd7465f4e5c2f171ef0d [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 }
460 return error;
461}
462
463Error
Chris Lattner24943d22010-06-08 16:52:24 +0000464ProcessGDBRemote::WillLaunchOrAttach ()
465{
466 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000467 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000468 return error;
469}
470
471//----------------------------------------------------------------------
472// Process Control
473//----------------------------------------------------------------------
474Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000475ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000476{
Greg Clayton4b407112010-09-30 21:49:03 +0000477 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000478
479 uint32_t launch_flags = launch_info.GetFlags().Get();
480 const char *stdin_path = NULL;
481 const char *stdout_path = NULL;
482 const char *stderr_path = NULL;
483 const char *working_dir = launch_info.GetWorkingDirectory();
484
485 const ProcessLaunchInfo::FileAction *file_action;
486 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
487 if (file_action)
488 {
489 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
490 stdin_path = file_action->GetPath();
491 }
492 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
493 if (file_action)
494 {
495 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
496 stdout_path = file_action->GetPath();
497 }
498 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
499 if (file_action)
500 {
501 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
502 stderr_path = file_action->GetPath();
503 }
504
Chris Lattner24943d22010-06-08 16:52:24 +0000505 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
506 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
507 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000508 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000509
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000510 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000511 if (object_file)
512 {
Chris Lattner24943d22010-06-08 16:52:24 +0000513 char host_port[128];
514 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000515 char connect_url[128];
516 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000517
Greg Claytona2f74232011-02-24 22:24:29 +0000518 // Make sure we aren't already connected?
519 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000520 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000521 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000522 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000523 {
Johnny Chenc143d622011-08-09 18:56:45 +0000524 if (log)
525 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000526 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000527 }
Chris Lattner24943d22010-06-08 16:52:24 +0000528
Greg Claytone71e2582011-02-04 01:58:07 +0000529 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000530 }
531
532 if (error.Success())
533 {
534 lldb_utility::PseudoTerminal pty;
535 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000536
537 // If the debugserver is local and we aren't disabling STDIO, lets use
538 // a pseudo terminal to instead of relying on the 'O' packets for stdio
539 // since 'O' packets can really slow down debugging if the inferior
540 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000541 PlatformSP platform_sp (m_target.GetPlatform());
542 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000543 {
544 const char *slave_name = NULL;
545 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000546 {
Greg Claytona2f74232011-02-24 22:24:29 +0000547 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
548 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000549 }
Greg Claytona2f74232011-02-24 22:24:29 +0000550 if (stdin_path == NULL)
551 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000552
Greg Claytona2f74232011-02-24 22:24:29 +0000553 if (stdout_path == NULL)
554 stdout_path = slave_name;
555
556 if (stderr_path == NULL)
557 stderr_path = slave_name;
558 }
559
Greg Claytonafb81862011-03-02 21:34:46 +0000560 // Set STDIN to /dev/null if we want STDIO disabled or if either
561 // STDOUT or STDERR have been set to something and STDIN hasn't
562 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000563 stdin_path = "/dev/null";
564
Greg Claytonafb81862011-03-02 21:34:46 +0000565 // Set STDOUT to /dev/null if we want STDIO disabled or if either
566 // STDIN or STDERR have been set to something and STDOUT hasn't
567 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000568 stdout_path = "/dev/null";
569
Greg Claytonafb81862011-03-02 21:34:46 +0000570 // Set STDERR to /dev/null if we want STDIO disabled or if either
571 // STDIN or STDOUT have been set to something and STDERR hasn't
572 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000573 stderr_path = "/dev/null";
574
575 if (stdin_path)
576 m_gdb_comm.SetSTDIN (stdin_path);
577 if (stdout_path)
578 m_gdb_comm.SetSTDOUT (stdout_path);
579 if (stderr_path)
580 m_gdb_comm.SetSTDERR (stderr_path);
581
582 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
583
Greg Claytona4582402011-05-08 04:53:50 +0000584 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000585
586 if (working_dir && working_dir[0])
587 {
588 m_gdb_comm.SetWorkingDir (working_dir);
589 }
590
591 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000592 const Args &environment = launch_info.GetEnvironmentEntries();
593 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000594 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000595 size_t num_environment_entries = environment.GetArgumentCount();
596 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000597 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000598 const char *env_entry = environment.GetArgumentAtIndex(i);
599 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000600 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000601 }
Greg Claytona2f74232011-02-24 22:24:29 +0000602 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000603
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000604 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000605 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000606 if (arg_packet_err == 0)
607 {
608 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000609 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000610 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000611 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000612 }
613 else
614 {
Greg Claytona2f74232011-02-24 22:24:29 +0000615 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000616 }
Greg Claytona2f74232011-02-24 22:24:29 +0000617 }
618 else
619 {
Greg Clayton9c236732011-10-26 00:56:27 +0000620 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000621 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000622
623 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000624
Greg Claytona2f74232011-02-24 22:24:29 +0000625 if (GetID() == LLDB_INVALID_PROCESS_ID)
626 {
Johnny Chenc143d622011-08-09 18:56:45 +0000627 if (log)
628 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000629 KillDebugserverProcess ();
630 return error;
631 }
632
Greg Clayton261a18b2011-06-02 22:22:38 +0000633 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000634 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000635 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000636
637 if (!disable_stdio)
638 {
639 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000640 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000641 }
Chris Lattner24943d22010-06-08 16:52:24 +0000642 }
643 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000644 else
645 {
Johnny Chenc143d622011-08-09 18:56:45 +0000646 if (log)
647 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000648 }
Chris Lattner24943d22010-06-08 16:52:24 +0000649 }
650 else
651 {
652 // Set our user ID to an invalid process ID.
653 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000654 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
655 exe_module->GetFileSpec().GetFilename().AsCString(),
656 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000657 }
Chris Lattner24943d22010-06-08 16:52:24 +0000658 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000659
Chris Lattner24943d22010-06-08 16:52:24 +0000660}
661
662
663Error
Greg Claytone71e2582011-02-04 01:58:07 +0000664ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000665{
666 Error error;
667 // Sleep and wait a bit for debugserver to start to listen...
668 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
669 if (conn_ap.get())
670 {
Chris Lattner24943d22010-06-08 16:52:24 +0000671 const uint32_t max_retry_count = 50;
672 uint32_t retry_count = 0;
673 while (!m_gdb_comm.IsConnected())
674 {
Greg Claytone71e2582011-02-04 01:58:07 +0000675 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000676 {
677 m_gdb_comm.SetConnection (conn_ap.release());
678 break;
679 }
680 retry_count++;
681
682 if (retry_count >= max_retry_count)
683 break;
684
685 usleep (100000);
686 }
687 }
688
689 if (!m_gdb_comm.IsConnected())
690 {
691 if (error.Success())
692 error.SetErrorString("not connected to remote gdb server");
693 return error;
694 }
695
Greg Clayton24bc5d92011-03-30 18:16:51 +0000696 // We always seem to be able to open a connection to a local port
697 // so we need to make sure we can then send data to it. If we can't
698 // then we aren't actually connected to anything, so try and do the
699 // handshake with the remote GDB server and make sure that goes
700 // alright.
701 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000702 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000703 m_gdb_comm.Disconnect();
704 if (error.Success())
705 error.SetErrorString("not connected to remote gdb server");
706 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000707 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000708 m_gdb_comm.ResetDiscoverableSettings();
709 m_gdb_comm.QueryNoAckModeSupported ();
710 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000711 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000712 m_gdb_comm.GetHostInfo ();
713 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000714 return error;
715}
716
717void
718ProcessGDBRemote::DidLaunchOrAttach ()
719{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000720 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
721 if (log)
722 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000723 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000724 {
725 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
726
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000727 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000728
Chris Lattner24943d22010-06-08 16:52:24 +0000729 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000730
Greg Claytoncb8977d2011-03-23 00:09:55 +0000731 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
732 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000733 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000734 ArchSpec &target_arch = GetTarget().GetArchitecture();
735
736 if (target_arch.IsValid())
737 {
738 // If the remote host is ARM and we have apple as the vendor, then
739 // ARM executables and shared libraries can have mixed ARM architectures.
740 // You can have an armv6 executable, and if the host is armv7, then the
741 // system will load the best possible architecture for all shared libraries
742 // it has, so we really need to take the remote host architecture as our
743 // defacto architecture in this case.
744
745 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
746 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
747 {
748 target_arch = gdb_remote_arch;
749 }
750 else
751 {
752 // Fill in what is missing in the triple
753 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
754 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000755 if (target_triple.getVendorName().size() == 0)
756 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000757 target_triple.setVendor (remote_triple.getVendor());
758
Greg Clayton2f085c62011-05-15 01:25:55 +0000759 if (target_triple.getOSName().size() == 0)
760 {
761 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000762
Greg Clayton2f085c62011-05-15 01:25:55 +0000763 if (target_triple.getEnvironmentName().size() == 0)
764 target_triple.setEnvironment (remote_triple.getEnvironment());
765 }
766 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000767 }
768 }
769 else
770 {
771 // The target doesn't have a valid architecture yet, set it from
772 // the architecture we got from the remote GDB server
773 target_arch = gdb_remote_arch;
774 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000775 }
Chris Lattner24943d22010-06-08 16:52:24 +0000776 }
777}
778
779void
780ProcessGDBRemote::DidLaunch ()
781{
782 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000783}
784
785Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000786ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000787{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000788 ProcessAttachInfo attach_info;
789 return DoAttachToProcessWithID(attach_pid, attach_info);
790}
791
792Error
793ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
794{
Chris Lattner24943d22010-06-08 16:52:24 +0000795 Error error;
796 // Clear out and clean up from any current state
797 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000798 if (attach_pid != LLDB_INVALID_PROCESS_ID)
799 {
Greg Claytona2f74232011-02-24 22:24:29 +0000800 // Make sure we aren't already connected?
801 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000802 {
Greg Claytona2f74232011-02-24 22:24:29 +0000803 char host_port[128];
804 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
805 char connect_url[128];
806 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000807
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000808 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000809
810 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000811 {
Greg Claytona2f74232011-02-24 22:24:29 +0000812 const char *error_string = error.AsCString();
813 if (error_string == NULL)
814 error_string = "unable to launch " DEBUGSERVER_BASENAME;
815
816 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000817 }
Greg Claytona2f74232011-02-24 22:24:29 +0000818 else
819 {
820 error = ConnectToDebugserver (connect_url);
821 }
822 }
823
824 if (error.Success())
825 {
826 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000827 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000828 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000829 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000830 }
831 }
Chris Lattner24943d22010-06-08 16:52:24 +0000832 return error;
833}
834
835size_t
836ProcessGDBRemote::AttachInputReaderCallback
837(
838 void *baton,
839 InputReader *reader,
840 lldb::InputReaderAction notification,
841 const char *bytes,
842 size_t bytes_len
843)
844{
845 if (notification == eInputReaderGotToken)
846 {
847 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
848 if (gdb_process->m_waiting_for_attach)
849 gdb_process->m_waiting_for_attach = false;
850 reader->SetIsDone(true);
851 return 1;
852 }
853 return 0;
854}
855
856Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000857ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000858{
859 Error error;
860 // Clear out and clean up from any current state
861 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000862
Chris Lattner24943d22010-06-08 16:52:24 +0000863 if (process_name && process_name[0])
864 {
Greg Claytona2f74232011-02-24 22:24:29 +0000865 // Make sure we aren't already connected?
866 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000867 {
Greg Claytona2f74232011-02-24 22:24:29 +0000868 char host_port[128];
869 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
870 char connect_url[128];
871 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
872
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000873 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000874 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000875 {
Greg Claytona2f74232011-02-24 22:24:29 +0000876 const char *error_string = error.AsCString();
877 if (error_string == NULL)
878 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000879
Greg Claytona2f74232011-02-24 22:24:29 +0000880 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000881 }
Greg Claytona2f74232011-02-24 22:24:29 +0000882 else
883 {
884 error = ConnectToDebugserver (connect_url);
885 }
886 }
887
888 if (error.Success())
889 {
890 StreamString packet;
891
892 if (wait_for_launch)
893 packet.PutCString("vAttachWait");
894 else
895 packet.PutCString("vAttachName");
896 packet.PutChar(';');
897 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
898
899 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
900
Chris Lattner24943d22010-06-08 16:52:24 +0000901 }
902 }
Chris Lattner24943d22010-06-08 16:52:24 +0000903 return error;
904}
905
Chris Lattner24943d22010-06-08 16:52:24 +0000906
907void
908ProcessGDBRemote::DidAttach ()
909{
Greg Claytone71e2582011-02-04 01:58:07 +0000910 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000911}
912
913Error
914ProcessGDBRemote::WillResume ()
915{
Greg Claytonc1f45872011-02-12 06:28:37 +0000916 m_continue_c_tids.clear();
917 m_continue_C_tids.clear();
918 m_continue_s_tids.clear();
919 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000920 return Error();
921}
922
923Error
924ProcessGDBRemote::DoResume ()
925{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000926 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000927 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
928 if (log)
929 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000930
931 Listener listener ("gdb-remote.resume-packet-sent");
932 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
933 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000934 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
935
Greg Claytonc1f45872011-02-12 06:28:37 +0000936 StreamString continue_packet;
937 bool continue_packet_error = false;
938 if (m_gdb_comm.HasAnyVContSupport ())
939 {
940 continue_packet.PutCString ("vCont");
941
942 if (!m_continue_c_tids.empty())
943 {
944 if (m_gdb_comm.GetVContSupported ('c'))
945 {
946 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 +0000947 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000948 }
949 else
950 continue_packet_error = true;
951 }
952
953 if (!continue_packet_error && !m_continue_C_tids.empty())
954 {
955 if (m_gdb_comm.GetVContSupported ('C'))
956 {
957 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 +0000958 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000959 }
960 else
961 continue_packet_error = true;
962 }
Greg Claytonb749a262010-12-03 06:02:24 +0000963
Greg Claytonc1f45872011-02-12 06:28:37 +0000964 if (!continue_packet_error && !m_continue_s_tids.empty())
965 {
966 if (m_gdb_comm.GetVContSupported ('s'))
967 {
968 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 +0000969 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000970 }
971 else
972 continue_packet_error = true;
973 }
974
975 if (!continue_packet_error && !m_continue_S_tids.empty())
976 {
977 if (m_gdb_comm.GetVContSupported ('S'))
978 {
979 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 +0000980 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000981 }
982 else
983 continue_packet_error = true;
984 }
985
986 if (continue_packet_error)
987 continue_packet.GetString().clear();
988 }
989 else
990 continue_packet_error = true;
991
992 if (continue_packet_error)
993 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000994 // Either no vCont support, or we tried to use part of the vCont
995 // packet that wasn't supported by the remote GDB server.
996 // We need to try and make a simple packet that can do our continue
997 const size_t num_threads = GetThreadList().GetSize();
998 const size_t num_continue_c_tids = m_continue_c_tids.size();
999 const size_t num_continue_C_tids = m_continue_C_tids.size();
1000 const size_t num_continue_s_tids = m_continue_s_tids.size();
1001 const size_t num_continue_S_tids = m_continue_S_tids.size();
1002 if (num_continue_c_tids > 0)
1003 {
1004 if (num_continue_c_tids == num_threads)
1005 {
1006 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001007 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001008 continue_packet.PutChar ('c');
1009 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001010 }
1011 else if (num_continue_c_tids == 1 &&
1012 num_continue_C_tids == 0 &&
1013 num_continue_s_tids == 0 &&
1014 num_continue_S_tids == 0 )
1015 {
1016 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001017 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001018 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001019 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001020 }
1021 }
1022
Greg Claytonde1dd812011-06-24 03:21:43 +00001023 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001024 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001025 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1026 num_continue_C_tids > 0 &&
1027 num_continue_s_tids == 0 &&
1028 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001029 {
1030 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001031 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001032 if (num_continue_C_tids > 1)
1033 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001034 // More that one thread with a signal, yet we don't have
1035 // vCont support and we are being asked to resume each
1036 // thread with a signal, we need to make sure they are
1037 // all the same signal, or we can't issue the continue
1038 // accurately with the current support...
1039 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001040 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001041 continue_packet_error = false;
1042 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1043 {
1044 if (m_continue_C_tids[i].second != continue_signo)
1045 continue_packet_error = true;
1046 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001047 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001048 if (!continue_packet_error)
1049 m_gdb_comm.SetCurrentThreadForRun (-1);
1050 }
1051 else
1052 {
1053 // Set the continue thread ID
1054 continue_packet_error = false;
1055 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001056 }
1057 if (!continue_packet_error)
1058 {
1059 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001060 continue_packet.Printf("C%2.2x", continue_signo);
1061 }
1062 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001063 }
1064
Greg Claytonde1dd812011-06-24 03:21:43 +00001065 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001066 {
1067 if (num_continue_s_tids == num_threads)
1068 {
1069 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001070 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001071 continue_packet.PutChar ('s');
1072 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001073 }
1074 else if (num_continue_c_tids == 0 &&
1075 num_continue_C_tids == 0 &&
1076 num_continue_s_tids == 1 &&
1077 num_continue_S_tids == 0 )
1078 {
1079 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001080 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001081 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001082 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001083 }
1084 }
1085
1086 if (!continue_packet_error && num_continue_S_tids > 0)
1087 {
1088 if (num_continue_S_tids == num_threads)
1089 {
1090 const int step_signo = m_continue_S_tids.front().second;
1091 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001092 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001093 if (num_continue_S_tids > 1)
1094 {
1095 for (size_t i=1; i<num_threads; ++i)
1096 {
1097 if (m_continue_S_tids[i].second != step_signo)
1098 continue_packet_error = true;
1099 }
1100 }
1101 if (!continue_packet_error)
1102 {
1103 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001104 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001105 continue_packet.Printf("S%2.2x", step_signo);
1106 }
1107 }
1108 else if (num_continue_c_tids == 0 &&
1109 num_continue_C_tids == 0 &&
1110 num_continue_s_tids == 0 &&
1111 num_continue_S_tids == 1 )
1112 {
1113 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001114 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001115 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001116 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001117 }
1118 }
1119 }
1120
1121 if (continue_packet_error)
1122 {
1123 error.SetErrorString ("can't make continue packet for this resume");
1124 }
1125 else
1126 {
1127 EventSP event_sp;
1128 TimeValue timeout;
1129 timeout = TimeValue::Now();
1130 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001131 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1132 {
1133 error.SetErrorString ("Trying to resume but the async thread is dead.");
1134 if (log)
1135 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1136 return error;
1137 }
1138
Greg Claytonc1f45872011-02-12 06:28:37 +00001139 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1140
1141 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001142 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001143 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001144 if (log)
1145 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1146 }
1147 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1148 {
1149 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1150 if (log)
1151 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1152 return error;
1153 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001154 }
Greg Claytonb749a262010-12-03 06:02:24 +00001155 }
1156
Jim Ingham3ae449a2010-11-17 02:32:00 +00001157 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001158}
1159
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001160void
1161ProcessGDBRemote::ClearThreadIDList ()
1162{
Greg Claytonff3448e2012-04-13 02:11:32 +00001163 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001164 m_thread_ids.clear();
1165}
1166
1167bool
1168ProcessGDBRemote::UpdateThreadIDList ()
1169{
Greg Claytonff3448e2012-04-13 02:11:32 +00001170 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001171 bool sequence_mutex_unavailable = false;
1172 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1173 if (sequence_mutex_unavailable)
1174 {
1175#if defined (LLDB_CONFIGURATION_DEBUG)
1176 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1177#endif
1178 return false; // We just didn't get the list
1179 }
1180 return true;
1181}
1182
Greg Claytonae932352012-04-10 00:18:59 +00001183bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001184ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001185{
1186 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001187 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001188 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001189 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001190
1191 size_t num_thread_ids = m_thread_ids.size();
1192 // The "m_thread_ids" thread ID list should always be updated after each stop
1193 // reply packet, but in case it isn't, update it here.
1194 if (num_thread_ids == 0)
1195 {
1196 if (!UpdateThreadIDList ())
1197 return false;
1198 num_thread_ids = m_thread_ids.size();
1199 }
Chris Lattner24943d22010-06-08 16:52:24 +00001200
Greg Clayton37f962e2011-08-22 02:49:39 +00001201 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001202 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001203 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001204 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001205 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001206 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1207 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001208 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001209 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001210 }
Chris Lattner24943d22010-06-08 16:52:24 +00001211 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001212
Greg Claytonae932352012-04-10 00:18:59 +00001213 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001214}
1215
1216
1217StateType
1218ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1219{
Greg Clayton261a18b2011-06-02 22:22:38 +00001220 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001221 const char stop_type = stop_packet.GetChar();
1222 switch (stop_type)
1223 {
1224 case 'T':
1225 case 'S':
1226 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001227 if (GetStopID() == 0)
1228 {
1229 // Our first stop, make sure we have a process ID, and also make
1230 // sure we know about our registers
1231 if (GetID() == LLDB_INVALID_PROCESS_ID)
1232 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001233 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001234 if (pid != LLDB_INVALID_PROCESS_ID)
1235 SetID (pid);
1236 }
1237 BuildDynamicRegisterInfo (true);
1238 }
Chris Lattner24943d22010-06-08 16:52:24 +00001239 // Stop with signal and thread info
1240 const uint8_t signo = stop_packet.GetHexU8();
1241 std::string name;
1242 std::string value;
1243 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001244 std::string reason;
1245 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001246 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001247 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001248 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1249 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001250 ThreadSP thread_sp;
1251
Chris Lattner24943d22010-06-08 16:52:24 +00001252 while (stop_packet.GetNameColonValue(name, value))
1253 {
1254 if (name.compare("metype") == 0)
1255 {
1256 // exception type in big endian hex
1257 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1258 }
1259 else if (name.compare("mecount") == 0)
1260 {
1261 // exception count in big endian hex
1262 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1263 }
1264 else if (name.compare("medata") == 0)
1265 {
1266 // exception data in big endian hex
1267 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1268 }
1269 else if (name.compare("thread") == 0)
1270 {
1271 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001272 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001273 // m_thread_list does have its own mutex, but we need to
1274 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1275 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001276 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001277 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001278 if (!thread_sp)
1279 {
1280 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001281 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001282 m_thread_list.AddThread(thread_sp);
1283 }
Chris Lattner24943d22010-06-08 16:52:24 +00001284 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001285 else if (name.compare("threads") == 0)
1286 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001287 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001288 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001289 // A comma separated list of all threads in the current
1290 // process that includes the thread for this stop reply
1291 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001292 size_t comma_pos;
1293 lldb::tid_t tid;
1294 while ((comma_pos = value.find(',')) != std::string::npos)
1295 {
1296 value[comma_pos] = '\0';
1297 // thread in big endian hex
1298 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1299 if (tid != LLDB_INVALID_THREAD_ID)
1300 m_thread_ids.push_back (tid);
1301 value.erase(0, comma_pos + 1);
1302
1303 }
1304 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1305 if (tid != LLDB_INVALID_THREAD_ID)
1306 m_thread_ids.push_back (tid);
1307 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001308 else if (name.compare("hexname") == 0)
1309 {
1310 StringExtractor name_extractor;
1311 // Swap "value" over into "name_extractor"
1312 name_extractor.GetStringRef().swap(value);
1313 // Now convert the HEX bytes into a string value
1314 name_extractor.GetHexByteString (value);
1315 thread_name.swap (value);
1316 }
Chris Lattner24943d22010-06-08 16:52:24 +00001317 else if (name.compare("name") == 0)
1318 {
1319 thread_name.swap (value);
1320 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001321 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001322 {
1323 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1324 }
Greg Clayton65611552011-06-04 01:26:29 +00001325 else if (name.compare("reason") == 0)
1326 {
1327 reason.swap(value);
1328 }
1329 else if (name.compare("description") == 0)
1330 {
1331 StringExtractor desc_extractor;
1332 // Swap "value" over into "name_extractor"
1333 desc_extractor.GetStringRef().swap(value);
1334 // Now convert the HEX bytes into a string value
1335 desc_extractor.GetHexByteString (thread_name);
1336 }
Greg Claytona875b642011-01-09 21:07:35 +00001337 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1338 {
1339 // We have a register number that contains an expedited
1340 // register value. Lets supply this register to our thread
1341 // so it won't have to go and read it.
1342 if (thread_sp)
1343 {
1344 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1345
1346 if (reg != UINT32_MAX)
1347 {
1348 StringExtractor reg_value_extractor;
1349 // Swap "value" over into "reg_value_extractor"
1350 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001351 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1352 {
1353 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1354 name.c_str(),
1355 reg,
1356 reg,
1357 reg_value_extractor.GetStringRef().c_str(),
1358 stop_packet.GetStringRef().c_str());
1359 }
Greg Claytona875b642011-01-09 21:07:35 +00001360 }
1361 }
1362 }
Chris Lattner24943d22010-06-08 16:52:24 +00001363 }
Chris Lattner24943d22010-06-08 16:52:24 +00001364
1365 if (thread_sp)
1366 {
1367 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1368
1369 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001370 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001371 if (exc_type != 0)
1372 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001373 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001374
1375 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1376 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001377 exc_data_size,
1378 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001379 exc_data_size >= 2 ? exc_data[1] : 0,
1380 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001381 }
Greg Clayton65611552011-06-04 01:26:29 +00001382 else
Chris Lattner24943d22010-06-08 16:52:24 +00001383 {
Greg Clayton65611552011-06-04 01:26:29 +00001384 bool handled = false;
1385 if (!reason.empty())
1386 {
1387 if (reason.compare("trace") == 0)
1388 {
1389 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1390 handled = true;
1391 }
1392 else if (reason.compare("breakpoint") == 0)
1393 {
1394 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001395 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001396 if (bp_site_sp)
1397 {
1398 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1399 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1400 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1401 if (bp_site_sp->ValidForThisThread (gdb_thread))
1402 {
1403 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1404 handled = true;
1405 }
1406 }
1407
1408 if (!handled)
1409 {
1410 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1411 }
1412 }
1413 else if (reason.compare("trap") == 0)
1414 {
1415 // Let the trap just use the standard signal stop reason below...
1416 }
1417 else if (reason.compare("watchpoint") == 0)
1418 {
1419 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1420 // TODO: locate the watchpoint somehow...
1421 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1422 handled = true;
1423 }
1424 else if (reason.compare("exception") == 0)
1425 {
1426 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1427 handled = true;
1428 }
1429 }
1430
1431 if (signo)
1432 {
1433 if (signo == SIGTRAP)
1434 {
1435 // Currently we are going to assume SIGTRAP means we are either
1436 // hitting a breakpoint or hardware single stepping.
1437 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001438 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001439 if (bp_site_sp)
1440 {
1441 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1442 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1443 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1444 if (bp_site_sp->ValidForThisThread (gdb_thread))
1445 {
1446 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1447 handled = true;
1448 }
1449 }
1450 if (!handled)
1451 {
1452 // TODO: check for breakpoint or trap opcode in case there is a hard
1453 // coded software trap
1454 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1455 handled = true;
1456 }
1457 }
1458 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001459 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001460 }
1461 else
1462 {
Greg Clayton643ee732010-08-04 01:40:35 +00001463 StopInfoSP invalid_stop_info_sp;
1464 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001465 }
Greg Clayton65611552011-06-04 01:26:29 +00001466
1467 if (!description.empty())
1468 {
1469 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1470 if (stop_info_sp)
1471 {
1472 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001473 }
Greg Clayton65611552011-06-04 01:26:29 +00001474 else
1475 {
1476 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1477 }
1478 }
1479 }
Chris Lattner24943d22010-06-08 16:52:24 +00001480 }
1481 return eStateStopped;
1482 }
1483 break;
1484
1485 case 'W':
1486 // process exited
1487 return eStateExited;
1488
1489 default:
1490 break;
1491 }
1492 return eStateInvalid;
1493}
1494
1495void
1496ProcessGDBRemote::RefreshStateAfterStop ()
1497{
Greg Claytonff3448e2012-04-13 02:11:32 +00001498 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001499 m_thread_ids.clear();
1500 // Set the thread stop info. It might have a "threads" key whose value is
1501 // a list of all thread IDs in the current process, so m_thread_ids might
1502 // get set.
1503 SetThreadStopInfo (m_last_stop_packet);
1504 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1505 if (m_thread_ids.empty())
1506 {
1507 // No, we need to fetch the thread list manually
1508 UpdateThreadIDList();
1509 }
1510
Chris Lattner24943d22010-06-08 16:52:24 +00001511 // Let all threads recover from stopping and do any clean up based
1512 // on the previous thread state (if any).
1513 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001514
Chris Lattner24943d22010-06-08 16:52:24 +00001515}
1516
1517Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001518ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001519{
1520 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001521
Greg Claytona4881d02011-01-22 07:12:45 +00001522 bool timed_out = false;
1523 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001524
1525 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001526 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001527 // We are being asked to halt during an attach. We need to just close
1528 // our file handle and debugserver will go away, and we can be done...
1529 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001530 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001531 else
1532 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001533 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001534 {
1535 if (timed_out)
1536 error.SetErrorString("timed out sending interrupt packet");
1537 else
1538 error.SetErrorString("unknown error sending interrupt packet");
1539 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001540
1541 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001542 }
Chris Lattner24943d22010-06-08 16:52:24 +00001543 return error;
1544}
1545
1546Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001547ProcessGDBRemote::InterruptIfRunning
1548(
1549 bool discard_thread_plans,
1550 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001551 EventSP &stop_event_sp
1552)
Chris Lattner24943d22010-06-08 16:52:24 +00001553{
1554 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001555
Greg Clayton2860ba92011-01-23 19:58:49 +00001556 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1557
Greg Clayton68ca8232011-01-25 02:58:48 +00001558 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001559 const bool is_running = m_gdb_comm.IsRunning();
1560 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001561 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001562 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001563 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001564 is_running);
1565
Greg Clayton2860ba92011-01-23 19:58:49 +00001566 if (discard_thread_plans)
1567 {
1568 if (log)
1569 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1570 m_thread_list.DiscardThreadPlans();
1571 }
1572 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001573 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001574 if (catch_stop_event)
1575 {
1576 if (log)
1577 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1578 PausePrivateStateThread();
1579 paused_private_state_thread = true;
1580 }
1581
Greg Clayton4fb400f2010-09-27 21:07:38 +00001582 bool timed_out = false;
1583 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001584
Greg Clayton05e4d972012-03-29 01:55:41 +00001585 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001586 {
1587 if (timed_out)
1588 error.SetErrorString("timed out sending interrupt packet");
1589 else
1590 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001591 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001592 ResumePrivateStateThread();
1593 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001594 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001595
Greg Clayton72e1c782011-01-22 23:43:18 +00001596 if (catch_stop_event)
1597 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001598 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001599 TimeValue timeout_time;
1600 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001601 timeout_time.OffsetWithSeconds(5);
1602 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001603
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001604 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001605 if (log)
1606 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001607
Greg Clayton2860ba92011-01-23 19:58:49 +00001608 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001609 error.SetErrorString("unable to verify target stopped");
1610 }
1611
Greg Clayton68ca8232011-01-25 02:58:48 +00001612 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001613 {
1614 if (log)
1615 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001616 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001617 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001618 }
Chris Lattner24943d22010-06-08 16:52:24 +00001619 return error;
1620}
1621
Greg Clayton4fb400f2010-09-27 21:07:38 +00001622Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001623ProcessGDBRemote::WillDetach ()
1624{
Greg Clayton2860ba92011-01-23 19:58:49 +00001625 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1626 if (log)
1627 log->Printf ("ProcessGDBRemote::WillDetach()");
1628
Greg Clayton72e1c782011-01-22 23:43:18 +00001629 bool discard_thread_plans = true;
1630 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001631 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001632 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001633}
1634
1635Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001636ProcessGDBRemote::DoDetach()
1637{
1638 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001639 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001640 if (log)
1641 log->Printf ("ProcessGDBRemote::DoDetach()");
1642
1643 DisableAllBreakpointSites ();
1644
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001645 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001646
Greg Clayton516f0842012-04-11 00:24:49 +00001647 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001648 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001649 {
Greg Clayton516f0842012-04-11 00:24:49 +00001650 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001651 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1652 else
1653 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001654 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001655 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001656 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001657
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001658 SetPrivateState (eStateDetached);
1659 ResumePrivateStateThread();
1660
1661 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001662 return error;
1663}
Chris Lattner24943d22010-06-08 16:52:24 +00001664
1665Error
1666ProcessGDBRemote::DoDestroy ()
1667{
1668 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001669 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001670 if (log)
1671 log->Printf ("ProcessGDBRemote::DoDestroy()");
1672
1673 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001674 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001675 {
Jim Ingham8226e942011-10-28 01:11:35 +00001676 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001677 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001678
1679 StringExtractorGDBRemote response;
1680 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001681 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001682 {
1683 char packet_cmd = response.GetChar(0);
1684
1685 if (packet_cmd == 'W' || packet_cmd == 'X')
1686 {
Greg Clayton06709002011-12-06 04:51:14 +00001687 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001688 ClearThreadIDList ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001689 SetExitStatus(response.GetHexU8(), NULL);
1690 }
1691 }
1692 else
1693 {
1694 SetExitStatus(SIGABRT, NULL);
1695 //error.SetErrorString("kill packet failed");
1696 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001697 }
1698 }
Chris Lattner24943d22010-06-08 16:52:24 +00001699 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001700 KillDebugserverProcess ();
1701 return error;
1702}
1703
Chris Lattner24943d22010-06-08 16:52:24 +00001704//------------------------------------------------------------------
1705// Process Queries
1706//------------------------------------------------------------------
1707
1708bool
1709ProcessGDBRemote::IsAlive ()
1710{
Greg Clayton58e844b2010-12-08 05:08:21 +00001711 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001712}
1713
1714addr_t
1715ProcessGDBRemote::GetImageInfoAddress()
1716{
Greg Clayton516f0842012-04-11 00:24:49 +00001717 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001718}
1719
Chris Lattner24943d22010-06-08 16:52:24 +00001720//------------------------------------------------------------------
1721// Process Memory
1722//------------------------------------------------------------------
1723size_t
1724ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1725{
1726 if (size > m_max_memory_size)
1727 {
1728 // Keep memory read sizes down to a sane limit. This function will be
1729 // called multiple times in order to complete the task by
1730 // lldb_private::Process so it is ok to do this.
1731 size = m_max_memory_size;
1732 }
1733
1734 char packet[64];
1735 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1736 assert (packet_len + 1 < sizeof(packet));
1737 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001738 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001739 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001740 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001741 {
1742 error.Clear();
1743 return response.GetHexBytes(buf, size, '\xdd');
1744 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001745 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001746 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001747 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001748 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1749 else
1750 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1751 }
1752 else
1753 {
1754 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1755 }
1756 return 0;
1757}
1758
1759size_t
1760ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1761{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001762 if (size > m_max_memory_size)
1763 {
1764 // Keep memory read sizes down to a sane limit. This function will be
1765 // called multiple times in order to complete the task by
1766 // lldb_private::Process so it is ok to do this.
1767 size = m_max_memory_size;
1768 }
1769
Chris Lattner24943d22010-06-08 16:52:24 +00001770 StreamString packet;
1771 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001772 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001773 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001774 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001775 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001776 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001777 {
1778 error.Clear();
1779 return size;
1780 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001781 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001782 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001783 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001784 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1785 else
1786 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1787 }
1788 else
1789 {
1790 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1791 }
1792 return 0;
1793}
1794
1795lldb::addr_t
1796ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1797{
Greg Clayton989816b2011-05-14 01:50:35 +00001798 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1799
Greg Clayton2f085c62011-05-15 01:25:55 +00001800 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001801 switch (supported)
1802 {
1803 case eLazyBoolCalculate:
1804 case eLazyBoolYes:
1805 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1806 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1807 return allocated_addr;
1808
1809 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001810 // Call mmap() to create memory in the inferior..
1811 unsigned prot = 0;
1812 if (permissions & lldb::ePermissionsReadable)
1813 prot |= eMmapProtRead;
1814 if (permissions & lldb::ePermissionsWritable)
1815 prot |= eMmapProtWrite;
1816 if (permissions & lldb::ePermissionsExecutable)
1817 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001818
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001819 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1820 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1821 m_addr_to_mmap_size[allocated_addr] = size;
1822 else
1823 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001824 break;
1825 }
1826
Chris Lattner24943d22010-06-08 16:52:24 +00001827 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001828 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001829 else
1830 error.Clear();
1831 return allocated_addr;
1832}
1833
1834Error
Greg Claytona9385532011-11-18 07:03:08 +00001835ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1836 MemoryRegionInfo &region_info)
1837{
1838
1839 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1840 return error;
1841}
1842
1843Error
Chris Lattner24943d22010-06-08 16:52:24 +00001844ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1845{
1846 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001847 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1848
1849 switch (supported)
1850 {
1851 case eLazyBoolCalculate:
1852 // We should never be deallocating memory without allocating memory
1853 // first so we should never get eLazyBoolCalculate
1854 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1855 break;
1856
1857 case eLazyBoolYes:
1858 if (!m_gdb_comm.DeallocateMemory (addr))
1859 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1860 break;
1861
1862 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001863 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001864 {
1865 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001866 if (pos != m_addr_to_mmap_size.end() &&
1867 InferiorCallMunmap(this, addr, pos->second))
1868 m_addr_to_mmap_size.erase (pos);
1869 else
1870 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001871 }
1872 break;
1873 }
1874
Chris Lattner24943d22010-06-08 16:52:24 +00001875 return error;
1876}
1877
1878
1879//------------------------------------------------------------------
1880// Process STDIO
1881//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001882size_t
1883ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1884{
1885 if (m_stdio_communication.IsConnected())
1886 {
1887 ConnectionStatus status;
1888 m_stdio_communication.Write(src, src_len, status, NULL);
1889 }
1890 return 0;
1891}
1892
1893Error
1894ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1895{
1896 Error error;
1897 assert (bp_site != NULL);
1898
Greg Claytone005f2c2010-11-06 01:53:30 +00001899 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001900 user_id_t site_id = bp_site->GetID();
1901 const addr_t addr = bp_site->GetLoadAddress();
1902 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001903 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001904
1905 if (bp_site->IsEnabled())
1906 {
1907 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001908 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 +00001909 return error;
1910 }
1911 else
1912 {
1913 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1914
1915 if (bp_site->HardwarePreferred())
1916 {
1917 // Try and set hardware breakpoint, and if that fails, fall through
1918 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001919 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001920 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001921 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001922 {
1923 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001924 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001925 return error;
1926 }
Chris Lattner24943d22010-06-08 16:52:24 +00001927 }
1928 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001929
1930 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001931 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001932 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1933 {
1934 bp_site->SetEnabled(true);
1935 bp_site->SetType (BreakpointSite::eExternal);
1936 return error;
1937 }
Chris Lattner24943d22010-06-08 16:52:24 +00001938 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001939
1940 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001941 }
1942
1943 if (log)
1944 {
1945 const char *err_string = error.AsCString();
1946 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1947 bp_site->GetLoadAddress(),
1948 err_string ? err_string : "NULL");
1949 }
1950 // We shouldn't reach here on a successful breakpoint enable...
1951 if (error.Success())
1952 error.SetErrorToGenericError();
1953 return error;
1954}
1955
1956Error
1957ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1958{
1959 Error error;
1960 assert (bp_site != NULL);
1961 addr_t addr = bp_site->GetLoadAddress();
1962 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001963 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001964 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001965 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001966
1967 if (bp_site->IsEnabled())
1968 {
1969 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1970
Greg Claytonb72d0f02011-04-12 05:54:46 +00001971 BreakpointSite::Type bp_type = bp_site->GetType();
1972 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001973 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001974 case BreakpointSite::eSoftware:
1975 error = DisableSoftwareBreakpoint (bp_site);
1976 break;
1977
1978 case BreakpointSite::eHardware:
1979 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1980 error.SetErrorToGenericError();
1981 break;
1982
1983 case BreakpointSite::eExternal:
1984 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1985 error.SetErrorToGenericError();
1986 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001987 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001988 if (error.Success())
1989 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001990 }
1991 else
1992 {
1993 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001994 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 +00001995 return error;
1996 }
1997
1998 if (error.Success())
1999 error.SetErrorToGenericError();
2000 return error;
2001}
2002
Johnny Chen21900fb2011-09-06 22:38:36 +00002003// Pre-requisite: wp != NULL.
2004static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002005GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002006{
2007 assert(wp);
2008 bool watch_read = wp->WatchpointRead();
2009 bool watch_write = wp->WatchpointWrite();
2010
2011 // watch_read and watch_write cannot both be false.
2012 assert(watch_read || watch_write);
2013 if (watch_read && watch_write)
2014 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002015 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002016 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002017 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002018 return eWatchpointWrite;
2019}
2020
Chris Lattner24943d22010-06-08 16:52:24 +00002021Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002022ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002023{
2024 Error error;
2025 if (wp)
2026 {
2027 user_id_t watchID = wp->GetID();
2028 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002029 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002030 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002031 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002032 if (wp->IsEnabled())
2033 {
2034 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002035 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002036 return error;
2037 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002038
2039 GDBStoppointType type = GetGDBStoppointType(wp);
2040 // Pass down an appropriate z/Z packet...
2041 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002042 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002043 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2044 {
2045 wp->SetEnabled(true);
2046 return error;
2047 }
2048 else
2049 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002050 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002051 else
2052 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002053 }
2054 else
2055 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002056 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002057 }
2058 if (error.Success())
2059 error.SetErrorToGenericError();
2060 return error;
2061}
2062
2063Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002064ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002065{
2066 Error error;
2067 if (wp)
2068 {
2069 user_id_t watchID = wp->GetID();
2070
Greg Claytone005f2c2010-11-06 01:53:30 +00002071 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002072
2073 addr_t addr = wp->GetLoadAddress();
2074 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002075 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002076
Johnny Chen21900fb2011-09-06 22:38:36 +00002077 if (!wp->IsEnabled())
2078 {
2079 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002080 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002081 return error;
2082 }
2083
Chris Lattner24943d22010-06-08 16:52:24 +00002084 if (wp->IsHardware())
2085 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002086 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002087 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002088 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2089 {
2090 wp->SetEnabled(false);
2091 return error;
2092 }
2093 else
2094 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002095 }
2096 // TODO: clear software watchpoints if we implement them
2097 }
2098 else
2099 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002100 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002101 }
2102 if (error.Success())
2103 error.SetErrorToGenericError();
2104 return error;
2105}
2106
2107void
2108ProcessGDBRemote::Clear()
2109{
2110 m_flags = 0;
2111 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002112}
2113
2114Error
2115ProcessGDBRemote::DoSignal (int signo)
2116{
2117 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002118 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002119 if (log)
2120 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2121
2122 if (!m_gdb_comm.SendAsyncSignal (signo))
2123 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2124 return error;
2125}
2126
Chris Lattner24943d22010-06-08 16:52:24 +00002127Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002128ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2129{
2130 ProcessLaunchInfo launch_info;
2131 return StartDebugserverProcess(debugserver_url, launch_info);
2132}
2133
2134Error
2135ProcessGDBRemote::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 +00002136{
2137 Error error;
2138 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2139 {
2140 // If we locate debugserver, keep that located version around
2141 static FileSpec g_debugserver_file_spec;
2142
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002143 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002144 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002145 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002146
2147 // Always check to see if we have an environment override for the path
2148 // to the debugserver to use and use it if we do.
2149 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2150 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002151 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002152 else
2153 debugserver_file_spec = g_debugserver_file_spec;
2154 bool debugserver_exists = debugserver_file_spec.Exists();
2155 if (!debugserver_exists)
2156 {
2157 // The debugserver binary is in the LLDB.framework/Resources
2158 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002159 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002160 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002161 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002162 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002163 if (debugserver_exists)
2164 {
2165 g_debugserver_file_spec = debugserver_file_spec;
2166 }
2167 else
2168 {
2169 g_debugserver_file_spec.Clear();
2170 debugserver_file_spec.Clear();
2171 }
Chris Lattner24943d22010-06-08 16:52:24 +00002172 }
2173 }
2174
2175 if (debugserver_exists)
2176 {
2177 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2178
2179 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002180
Greg Claytone005f2c2010-11-06 01:53:30 +00002181 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002182
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002183 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002184 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002185
Chris Lattner24943d22010-06-08 16:52:24 +00002186 // Start args with "debugserver /file/path -r --"
2187 debugserver_args.AppendArgument(debugserver_path);
2188 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002189 // use native registers, not the GDB registers
2190 debugserver_args.AppendArgument("--native-regs");
2191 // make debugserver run in its own session so signals generated by
2192 // special terminal key sequences (^C) don't affect debugserver
2193 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002194
Chris Lattner24943d22010-06-08 16:52:24 +00002195 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2196 if (env_debugserver_log_file)
2197 {
2198 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2199 debugserver_args.AppendArgument(arg_cstr);
2200 }
2201
2202 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2203 if (env_debugserver_log_flags)
2204 {
2205 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2206 debugserver_args.AppendArgument(arg_cstr);
2207 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002208// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002209// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002210
Greg Claytonb72d0f02011-04-12 05:54:46 +00002211 // We currently send down all arguments, attach pids, or attach
2212 // process names in dedicated GDB server packets, so we don't need
2213 // to pass them as arguments. This is currently because of all the
2214 // things we need to setup prior to launching: the environment,
2215 // current working dir, file actions, etc.
2216#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002217 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002218 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002219 {
Greg Claytona2f74232011-02-24 22:24:29 +00002220 // Terminate the debugserver args so we can now append the inferior args
2221 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002222
Greg Claytona2f74232011-02-24 22:24:29 +00002223 for (int i = 0; inferior_argv[i] != NULL; ++i)
2224 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002225 }
2226 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2227 {
2228 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2229 debugserver_args.AppendArgument (arg_cstr);
2230 }
2231 else if (attach_name && attach_name[0])
2232 {
2233 if (wait_for_launch)
2234 debugserver_args.AppendArgument ("--waitfor");
2235 else
2236 debugserver_args.AppendArgument ("--attach");
2237 debugserver_args.AppendArgument (attach_name);
2238 }
Chris Lattner24943d22010-06-08 16:52:24 +00002239#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002240
2241 ProcessLaunchInfo::FileAction file_action;
2242
2243 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2244 // to "/dev/null" if we run into any problems.
2245 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002246 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002247 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002248 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002249 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002250 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002251
2252 if (log)
2253 {
2254 StreamString strm;
2255 debugserver_args.Dump (&strm);
2256 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2257 }
2258
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002259 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2260 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002261
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002262 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002263
Greg Claytonb72d0f02011-04-12 05:54:46 +00002264 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002265 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002266 else
Chris Lattner24943d22010-06-08 16:52:24 +00002267 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2268
2269 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002270 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002271 }
2272 else
2273 {
Greg Clayton9c236732011-10-26 00:56:27 +00002274 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002275 }
2276
2277 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2278 StartAsyncThread ();
2279 }
2280 return error;
2281}
2282
2283bool
2284ProcessGDBRemote::MonitorDebugserverProcess
2285(
2286 void *callback_baton,
2287 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002288 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002289 int signo, // Zero for no signal
2290 int exit_status // Exit value of process if signal is zero
2291)
2292{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002293 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2294 // and might not exist anymore, so we need to carefully try to get the
2295 // target for this process first since we have a race condition when
2296 // we are done running between getting the notice that the inferior
2297 // process has died and the debugserver that was debugging this process.
2298 // In our test suite, we are also continually running process after
2299 // process, so we must be very careful to make sure:
2300 // 1 - process object hasn't been deleted already
2301 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002302
2303 // "debugserver_pid" argument passed in is the process ID for
2304 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002305 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002306
Greg Clayton75ccf502010-08-21 02:22:51 +00002307 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002308
Greg Clayton1c4642c2011-11-16 05:37:56 +00002309 // Get a shared pointer to the target that has a matching process pointer.
2310 // This target could be gone, or the target could already have a new process
2311 // object inside of it
2312 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2313
Greg Clayton72e1c782011-01-22 23:43:18 +00002314 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002315 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 +00002316
Greg Clayton1c4642c2011-11-16 05:37:56 +00002317 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002318 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002319 // We found a process in a target that matches, but another thread
2320 // might be in the process of launching a new process that will
2321 // soon replace it, so get a shared pointer to the process so we
2322 // can keep it alive.
2323 ProcessSP process_sp (target_sp->GetProcessSP());
2324 // Now we have a shared pointer to the process that can't go away on us
2325 // so we now make sure it was the same as the one passed in, and also make
2326 // sure that our previous "process *" didn't get deleted and have a new
2327 // "process *" created in its place with the same pointer. To verify this
2328 // we make sure the process has our debugserver process ID. If we pass all
2329 // of these tests, then we are sure that this process is the one we were
2330 // looking for.
2331 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002332 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002333 // Sleep for a half a second to make sure our inferior process has
2334 // time to set its exit status before we set it incorrectly when
2335 // both the debugserver and the inferior process shut down.
2336 usleep (500000);
2337 // If our process hasn't yet exited, debugserver might have died.
2338 // If the process did exit, the we are reaping it.
2339 const StateType state = process->GetState();
2340
2341 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2342 state != eStateInvalid &&
2343 state != eStateUnloaded &&
2344 state != eStateExited &&
2345 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002346 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002347 char error_str[1024];
2348 if (signo)
2349 {
2350 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2351 if (signal_cstr)
2352 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2353 else
2354 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2355 }
Chris Lattner24943d22010-06-08 16:52:24 +00002356 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002357 {
2358 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2359 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002360
Greg Clayton1c4642c2011-11-16 05:37:56 +00002361 process->SetExitStatus (-1, error_str);
2362 }
2363 // Debugserver has exited we need to let our ProcessGDBRemote
2364 // know that it no longer has a debugserver instance
2365 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002366 }
Chris Lattner24943d22010-06-08 16:52:24 +00002367 }
2368 return true;
2369}
2370
2371void
2372ProcessGDBRemote::KillDebugserverProcess ()
2373{
2374 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2375 {
2376 ::kill (m_debugserver_pid, SIGINT);
2377 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2378 }
2379}
2380
2381void
2382ProcessGDBRemote::Initialize()
2383{
2384 static bool g_initialized = false;
2385
2386 if (g_initialized == false)
2387 {
2388 g_initialized = true;
2389 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2390 GetPluginDescriptionStatic(),
2391 CreateInstance);
2392
2393 Log::Callbacks log_callbacks = {
2394 ProcessGDBRemoteLog::DisableLog,
2395 ProcessGDBRemoteLog::EnableLog,
2396 ProcessGDBRemoteLog::ListLogCategories
2397 };
2398
2399 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2400 }
2401}
2402
2403bool
Chris Lattner24943d22010-06-08 16:52:24 +00002404ProcessGDBRemote::StartAsyncThread ()
2405{
Greg Claytone005f2c2010-11-06 01:53:30 +00002406 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002407
2408 if (log)
2409 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2410
2411 // Create a thread that watches our internal state and controls which
2412 // events make it to clients (into the DCProcess event queue).
2413 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002414 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002415}
2416
2417void
2418ProcessGDBRemote::StopAsyncThread ()
2419{
Greg Claytone005f2c2010-11-06 01:53:30 +00002420 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002421
2422 if (log)
2423 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2424
2425 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002426
2427 // This will shut down the async thread.
2428 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002429
2430 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002431 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002432 {
2433 Host::ThreadJoin (m_async_thread, NULL, NULL);
2434 }
2435}
2436
2437
2438void *
2439ProcessGDBRemote::AsyncThread (void *arg)
2440{
2441 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2442
Greg Claytone005f2c2010-11-06 01:53:30 +00002443 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002444 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002445 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002446
2447 Listener listener ("ProcessGDBRemote::AsyncThread");
2448 EventSP event_sp;
2449 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2450 eBroadcastBitAsyncThreadShouldExit;
2451
2452 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2453 {
Greg Claytona2f74232011-02-24 22:24:29 +00002454 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2455
Chris Lattner24943d22010-06-08 16:52:24 +00002456 bool done = false;
2457 while (!done)
2458 {
2459 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002460 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002461 if (listener.WaitForEvent (NULL, event_sp))
2462 {
2463 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002464 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002465 {
Greg Claytona2f74232011-02-24 22:24:29 +00002466 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002467 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 +00002468
Greg Claytona2f74232011-02-24 22:24:29 +00002469 switch (event_type)
2470 {
2471 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002472 {
Greg Claytona2f74232011-02-24 22:24:29 +00002473 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002474
Greg Claytona2f74232011-02-24 22:24:29 +00002475 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002476 {
Greg Claytona2f74232011-02-24 22:24:29 +00002477 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2478 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2479 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002480 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002481
Greg Claytona2f74232011-02-24 22:24:29 +00002482 if (::strstr (continue_cstr, "vAttach") == NULL)
2483 process->SetPrivateState(eStateRunning);
2484 StringExtractorGDBRemote response;
2485 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002486
Greg Claytona2f74232011-02-24 22:24:29 +00002487 switch (stop_state)
2488 {
2489 case eStateStopped:
2490 case eStateCrashed:
2491 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002492 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002493 process->SetPrivateState (stop_state);
2494 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002495
Greg Claytona2f74232011-02-24 22:24:29 +00002496 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002497 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002498 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002499 response.SetFilePos(1);
2500 process->SetExitStatus(response.GetHexU8(), NULL);
2501 done = true;
2502 break;
2503
2504 case eStateInvalid:
2505 process->SetExitStatus(-1, "lost connection");
2506 break;
2507
2508 default:
2509 process->SetPrivateState (stop_state);
2510 break;
2511 }
Chris Lattner24943d22010-06-08 16:52:24 +00002512 }
2513 }
Greg Claytona2f74232011-02-24 22:24:29 +00002514 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002515
Greg Claytona2f74232011-02-24 22:24:29 +00002516 case eBroadcastBitAsyncThreadShouldExit:
2517 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002518 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002519 done = true;
2520 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002521
Greg Claytona2f74232011-02-24 22:24:29 +00002522 default:
2523 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002524 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 +00002525 done = true;
2526 break;
2527 }
2528 }
2529 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2530 {
2531 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2532 {
2533 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002534 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002535 }
Chris Lattner24943d22010-06-08 16:52:24 +00002536 }
2537 }
2538 else
2539 {
2540 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002541 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 +00002542 done = true;
2543 }
2544 }
2545 }
2546
2547 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002548 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002549
2550 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2551 return NULL;
2552}
2553
Chris Lattner24943d22010-06-08 16:52:24 +00002554const char *
2555ProcessGDBRemote::GetDispatchQueueNameForThread
2556(
2557 addr_t thread_dispatch_qaddr,
2558 std::string &dispatch_queue_name
2559)
2560{
2561 dispatch_queue_name.clear();
2562 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2563 {
2564 // Cache the dispatch_queue_offsets_addr value so we don't always have
2565 // to look it up
2566 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2567 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002568 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2569 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002570 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2571 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002572 if (module_sp)
2573 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2574
2575 if (dispatch_queue_offsets_symbol == NULL)
2576 {
Greg Clayton444fe992012-02-26 05:51:37 +00002577 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2578 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002579 if (module_sp)
2580 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2581 }
Chris Lattner24943d22010-06-08 16:52:24 +00002582 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002583 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002584
2585 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2586 return NULL;
2587 }
2588
2589 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002590 DataExtractor data (memory_buffer,
2591 sizeof(memory_buffer),
2592 m_target.GetArchitecture().GetByteOrder(),
2593 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002594
2595 // Excerpt from src/queue_private.h
2596 struct dispatch_queue_offsets_s
2597 {
2598 uint16_t dqo_version;
2599 uint16_t dqo_label;
2600 uint16_t dqo_label_size;
2601 } dispatch_queue_offsets;
2602
2603
2604 Error error;
2605 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2606 {
2607 uint32_t data_offset = 0;
2608 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2609 {
2610 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2611 {
2612 data_offset = 0;
2613 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2614 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2615 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2616 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2617 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2618 dispatch_queue_name.erase (bytes_read);
2619 }
2620 }
2621 }
2622 }
2623 if (dispatch_queue_name.empty())
2624 return NULL;
2625 return dispatch_queue_name.c_str();
2626}
2627
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002628//uint32_t
2629//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2630//{
2631// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2632// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2633// if (m_local_debugserver)
2634// {
2635// return Host::ListProcessesMatchingName (name, matches, pids);
2636// }
2637// else
2638// {
2639// // FIXME: Implement talking to the remote debugserver.
2640// return 0;
2641// }
2642//
2643//}
2644//
Jim Ingham55e01d82011-01-22 01:33:44 +00002645bool
2646ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2647 lldb_private::StoppointCallbackContext *context,
2648 lldb::user_id_t break_id,
2649 lldb::user_id_t break_loc_id)
2650{
2651 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2652 // run so I can stop it if that's what I want to do.
2653 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2654 if (log)
2655 log->Printf("Hit New Thread Notification breakpoint.");
2656 return false;
2657}
2658
2659
2660bool
2661ProcessGDBRemote::StartNoticingNewThreads()
2662{
2663 static const char *bp_names[] =
2664 {
2665 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002666 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002667 "_pthread_start",
2668 NULL
2669 };
2670
2671 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2672 size_t num_bps = m_thread_observation_bps.size();
2673 if (num_bps != 0)
2674 {
2675 for (int i = 0; i < num_bps; i++)
2676 {
2677 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2678 if (break_sp)
2679 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002680 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002681 log->Printf("Enabled noticing new thread breakpoint.");
2682 break_sp->SetEnabled(true);
2683 }
2684 }
2685 }
2686 else
2687 {
2688 for (int i = 0; bp_names[i] != NULL; i++)
2689 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002690 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002691 if (breakpoint)
2692 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002693 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002694 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2695 m_thread_observation_bps.push_back(breakpoint->GetID());
2696 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2697 }
2698 else
2699 {
2700 if (log)
2701 log->Printf("Failed to create new thread notification breakpoint.");
2702 return false;
2703 }
2704 }
2705 }
2706
2707 return true;
2708}
2709
2710bool
2711ProcessGDBRemote::StopNoticingNewThreads()
2712{
Jim Inghamff276fe2011-02-08 05:19:01 +00002713 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002714 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002715 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002716 size_t num_bps = m_thread_observation_bps.size();
2717 if (num_bps != 0)
2718 {
2719 for (int i = 0; i < num_bps; i++)
2720 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002721
2722 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2723 if (break_sp)
2724 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002725 break_sp->SetEnabled(false);
2726 }
2727 }
2728 }
2729 return true;
2730}
2731
2732