blob: 0cad8366c66651155996ebf1bd288f4c117879a6 [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.
Greg Claytonb170aee2012-05-08 01:45:38 +0000386 const ArchSpec &target_arch = GetTarget().GetArchitecture();
387 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
388 if (!target_arch.IsValid())
Jason Molenda428b5502011-10-06 01:45:46 +0000389 {
Greg Claytonb170aee2012-05-08 01:45:38 +0000390 if (remote_arch.IsValid()
391 && remote_arch.GetMachine() == llvm::Triple::arm
392 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
393 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000394 }
Greg Claytonb170aee2012-05-08 01:45:38 +0000395 else if (target_arch.GetMachine() == llvm::Triple::arm)
Jason Molenda428b5502011-10-06 01:45:46 +0000396 {
397 m_register_info.HardcodeARMRegisters();
398 }
Chris Lattner24943d22010-06-08 16:52:24 +0000399 }
400 m_register_info.Finalize ();
401}
402
403Error
404ProcessGDBRemote::WillLaunch (Module* module)
405{
406 return WillLaunchOrAttach ();
407}
408
409Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000410ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000411{
412 return WillLaunchOrAttach ();
413}
414
415Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000416ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000417{
418 return WillLaunchOrAttach ();
419}
420
421Error
Greg Claytone71e2582011-02-04 01:58:07 +0000422ProcessGDBRemote::DoConnectRemote (const char *remote_url)
423{
424 Error error (WillLaunchOrAttach ());
425
426 if (error.Fail())
427 return error;
428
Greg Clayton180546b2011-04-30 01:09:13 +0000429 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000430
431 if (error.Fail())
432 return error;
433 StartAsyncThread ();
434
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000435 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000436 if (pid == LLDB_INVALID_PROCESS_ID)
437 {
438 // We don't have a valid process ID, so note that we are connected
439 // and could now request to launch or attach, or get remote process
440 // listings...
441 SetPrivateState (eStateConnected);
442 }
443 else
444 {
445 // We have a valid process
446 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000447 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000448 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000449 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000450 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000451 if (state == eStateStopped)
452 {
453 SetPrivateState (state);
454 }
455 else
Greg Claytond9919d32011-12-01 23:28:38 +0000456 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 +0000457 }
458 else
Greg Claytond9919d32011-12-01 23:28:38 +0000459 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 +0000460 }
Jason Molendacb740b32012-05-03 22:37:30 +0000461
462 if (error.Success()
463 && !GetTarget().GetArchitecture().IsValid()
464 && m_gdb_comm.GetHostArchitecture().IsValid())
465 {
466 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
467 }
468
Greg Claytone71e2582011-02-04 01:58:07 +0000469 return error;
470}
471
472Error
Chris Lattner24943d22010-06-08 16:52:24 +0000473ProcessGDBRemote::WillLaunchOrAttach ()
474{
475 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000476 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000477 return error;
478}
479
480//----------------------------------------------------------------------
481// Process Control
482//----------------------------------------------------------------------
483Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000484ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000485{
Greg Clayton4b407112010-09-30 21:49:03 +0000486 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000487
488 uint32_t launch_flags = launch_info.GetFlags().Get();
489 const char *stdin_path = NULL;
490 const char *stdout_path = NULL;
491 const char *stderr_path = NULL;
492 const char *working_dir = launch_info.GetWorkingDirectory();
493
494 const ProcessLaunchInfo::FileAction *file_action;
495 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
496 if (file_action)
497 {
498 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
499 stdin_path = file_action->GetPath();
500 }
501 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
502 if (file_action)
503 {
504 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
505 stdout_path = file_action->GetPath();
506 }
507 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
508 if (file_action)
509 {
510 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
511 stderr_path = file_action->GetPath();
512 }
513
Chris Lattner24943d22010-06-08 16:52:24 +0000514 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
515 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
516 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000517 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000518
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000519 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000520 if (object_file)
521 {
Chris Lattner24943d22010-06-08 16:52:24 +0000522 char host_port[128];
523 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000524 char connect_url[128];
525 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000526
Greg Claytona2f74232011-02-24 22:24:29 +0000527 // Make sure we aren't already connected?
528 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000529 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000530 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000531 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000532 {
Johnny Chenc143d622011-08-09 18:56:45 +0000533 if (log)
534 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000535 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000536 }
Chris Lattner24943d22010-06-08 16:52:24 +0000537
Greg Claytone71e2582011-02-04 01:58:07 +0000538 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000539 }
540
541 if (error.Success())
542 {
543 lldb_utility::PseudoTerminal pty;
544 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000545
546 // If the debugserver is local and we aren't disabling STDIO, lets use
547 // a pseudo terminal to instead of relying on the 'O' packets for stdio
548 // since 'O' packets can really slow down debugging if the inferior
549 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000550 PlatformSP platform_sp (m_target.GetPlatform());
551 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000552 {
553 const char *slave_name = NULL;
554 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000555 {
Greg Claytona2f74232011-02-24 22:24:29 +0000556 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
557 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000558 }
Greg Claytona2f74232011-02-24 22:24:29 +0000559 if (stdin_path == NULL)
560 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000561
Greg Claytona2f74232011-02-24 22:24:29 +0000562 if (stdout_path == NULL)
563 stdout_path = slave_name;
564
565 if (stderr_path == NULL)
566 stderr_path = slave_name;
567 }
568
Greg Claytonafb81862011-03-02 21:34:46 +0000569 // Set STDIN to /dev/null if we want STDIO disabled or if either
570 // STDOUT or STDERR have been set to something and STDIN hasn't
571 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000572 stdin_path = "/dev/null";
573
Greg Claytonafb81862011-03-02 21:34:46 +0000574 // Set STDOUT to /dev/null if we want STDIO disabled or if either
575 // STDIN or STDERR have been set to something and STDOUT hasn't
576 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000577 stdout_path = "/dev/null";
578
Greg Claytonafb81862011-03-02 21:34:46 +0000579 // Set STDERR to /dev/null if we want STDIO disabled or if either
580 // STDIN or STDOUT have been set to something and STDERR hasn't
581 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000582 stderr_path = "/dev/null";
583
584 if (stdin_path)
585 m_gdb_comm.SetSTDIN (stdin_path);
586 if (stdout_path)
587 m_gdb_comm.SetSTDOUT (stdout_path);
588 if (stderr_path)
589 m_gdb_comm.SetSTDERR (stderr_path);
590
591 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
592
Greg Claytona4582402011-05-08 04:53:50 +0000593 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000594
595 if (working_dir && working_dir[0])
596 {
597 m_gdb_comm.SetWorkingDir (working_dir);
598 }
599
600 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000601 const Args &environment = launch_info.GetEnvironmentEntries();
602 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000603 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000604 size_t num_environment_entries = environment.GetArgumentCount();
605 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000606 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000607 const char *env_entry = environment.GetArgumentAtIndex(i);
608 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000609 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000610 }
Greg Claytona2f74232011-02-24 22:24:29 +0000611 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000612
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000613 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000614 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000615 if (arg_packet_err == 0)
616 {
617 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000618 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000619 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000620 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000621 }
622 else
623 {
Greg Claytona2f74232011-02-24 22:24:29 +0000624 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000625 }
Greg Claytona2f74232011-02-24 22:24:29 +0000626 }
627 else
628 {
Greg Clayton9c236732011-10-26 00:56:27 +0000629 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000630 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000631
632 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000633
Greg Claytona2f74232011-02-24 22:24:29 +0000634 if (GetID() == LLDB_INVALID_PROCESS_ID)
635 {
Johnny Chenc143d622011-08-09 18:56:45 +0000636 if (log)
637 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000638 KillDebugserverProcess ();
639 return error;
640 }
641
Greg Clayton261a18b2011-06-02 22:22:38 +0000642 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000643 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000644 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000645
646 if (!disable_stdio)
647 {
648 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000649 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000650 }
Chris Lattner24943d22010-06-08 16:52:24 +0000651 }
652 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000653 else
654 {
Johnny Chenc143d622011-08-09 18:56:45 +0000655 if (log)
656 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000657 }
Chris Lattner24943d22010-06-08 16:52:24 +0000658 }
659 else
660 {
661 // Set our user ID to an invalid process ID.
662 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000663 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
664 exe_module->GetFileSpec().GetFilename().AsCString(),
665 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000666 }
Chris Lattner24943d22010-06-08 16:52:24 +0000667 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000668
Chris Lattner24943d22010-06-08 16:52:24 +0000669}
670
671
672Error
Greg Claytone71e2582011-02-04 01:58:07 +0000673ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000674{
675 Error error;
676 // Sleep and wait a bit for debugserver to start to listen...
677 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
678 if (conn_ap.get())
679 {
Chris Lattner24943d22010-06-08 16:52:24 +0000680 const uint32_t max_retry_count = 50;
681 uint32_t retry_count = 0;
682 while (!m_gdb_comm.IsConnected())
683 {
Greg Claytone71e2582011-02-04 01:58:07 +0000684 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000685 {
686 m_gdb_comm.SetConnection (conn_ap.release());
687 break;
688 }
689 retry_count++;
690
691 if (retry_count >= max_retry_count)
692 break;
693
694 usleep (100000);
695 }
696 }
697
698 if (!m_gdb_comm.IsConnected())
699 {
700 if (error.Success())
701 error.SetErrorString("not connected to remote gdb server");
702 return error;
703 }
704
Greg Clayton24bc5d92011-03-30 18:16:51 +0000705 // We always seem to be able to open a connection to a local port
706 // so we need to make sure we can then send data to it. If we can't
707 // then we aren't actually connected to anything, so try and do the
708 // handshake with the remote GDB server and make sure that goes
709 // alright.
710 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000711 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000712 m_gdb_comm.Disconnect();
713 if (error.Success())
714 error.SetErrorString("not connected to remote gdb server");
715 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000716 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000717 m_gdb_comm.ResetDiscoverableSettings();
718 m_gdb_comm.QueryNoAckModeSupported ();
719 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000720 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000721 m_gdb_comm.GetHostInfo ();
722 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000723 return error;
724}
725
726void
727ProcessGDBRemote::DidLaunchOrAttach ()
728{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000729 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
730 if (log)
731 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000732 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000733 {
734 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
735
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000736 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000737
Chris Lattner24943d22010-06-08 16:52:24 +0000738 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000739
Greg Claytoncb8977d2011-03-23 00:09:55 +0000740 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
741 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000742 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000743 ArchSpec &target_arch = GetTarget().GetArchitecture();
744
745 if (target_arch.IsValid())
746 {
747 // If the remote host is ARM and we have apple as the vendor, then
748 // ARM executables and shared libraries can have mixed ARM architectures.
749 // You can have an armv6 executable, and if the host is armv7, then the
750 // system will load the best possible architecture for all shared libraries
751 // it has, so we really need to take the remote host architecture as our
752 // defacto architecture in this case.
753
754 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
755 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
756 {
757 target_arch = gdb_remote_arch;
758 }
759 else
760 {
761 // Fill in what is missing in the triple
762 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
763 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000764 if (target_triple.getVendorName().size() == 0)
765 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000766 target_triple.setVendor (remote_triple.getVendor());
767
Greg Clayton2f085c62011-05-15 01:25:55 +0000768 if (target_triple.getOSName().size() == 0)
769 {
770 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000771
Greg Clayton2f085c62011-05-15 01:25:55 +0000772 if (target_triple.getEnvironmentName().size() == 0)
773 target_triple.setEnvironment (remote_triple.getEnvironment());
774 }
775 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000776 }
777 }
778 else
779 {
780 // The target doesn't have a valid architecture yet, set it from
781 // the architecture we got from the remote GDB server
782 target_arch = gdb_remote_arch;
783 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000784 }
Chris Lattner24943d22010-06-08 16:52:24 +0000785 }
786}
787
788void
789ProcessGDBRemote::DidLaunch ()
790{
791 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000792}
793
794Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000795ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000796{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000797 ProcessAttachInfo attach_info;
798 return DoAttachToProcessWithID(attach_pid, attach_info);
799}
800
801Error
802ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
803{
Chris Lattner24943d22010-06-08 16:52:24 +0000804 Error error;
805 // Clear out and clean up from any current state
806 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000807 if (attach_pid != LLDB_INVALID_PROCESS_ID)
808 {
Greg Claytona2f74232011-02-24 22:24:29 +0000809 // Make sure we aren't already connected?
810 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000811 {
Greg Claytona2f74232011-02-24 22:24:29 +0000812 char host_port[128];
813 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
814 char connect_url[128];
815 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000816
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000817 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000818
819 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000820 {
Greg Claytona2f74232011-02-24 22:24:29 +0000821 const char *error_string = error.AsCString();
822 if (error_string == NULL)
823 error_string = "unable to launch " DEBUGSERVER_BASENAME;
824
825 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000826 }
Greg Claytona2f74232011-02-24 22:24:29 +0000827 else
828 {
829 error = ConnectToDebugserver (connect_url);
830 }
831 }
832
833 if (error.Success())
834 {
835 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000836 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000837 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000838 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000839 }
840 }
Chris Lattner24943d22010-06-08 16:52:24 +0000841 return error;
842}
843
844size_t
845ProcessGDBRemote::AttachInputReaderCallback
846(
847 void *baton,
848 InputReader *reader,
849 lldb::InputReaderAction notification,
850 const char *bytes,
851 size_t bytes_len
852)
853{
854 if (notification == eInputReaderGotToken)
855 {
856 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
857 if (gdb_process->m_waiting_for_attach)
858 gdb_process->m_waiting_for_attach = false;
859 reader->SetIsDone(true);
860 return 1;
861 }
862 return 0;
863}
864
865Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000866ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000867{
868 Error error;
869 // Clear out and clean up from any current state
870 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000871
Chris Lattner24943d22010-06-08 16:52:24 +0000872 if (process_name && process_name[0])
873 {
Greg Claytona2f74232011-02-24 22:24:29 +0000874 // Make sure we aren't already connected?
875 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000876 {
Greg Claytona2f74232011-02-24 22:24:29 +0000877 char host_port[128];
878 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
879 char connect_url[128];
880 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
881
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000882 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000883 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000884 {
Greg Claytona2f74232011-02-24 22:24:29 +0000885 const char *error_string = error.AsCString();
886 if (error_string == NULL)
887 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000888
Greg Claytona2f74232011-02-24 22:24:29 +0000889 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000890 }
Greg Claytona2f74232011-02-24 22:24:29 +0000891 else
892 {
893 error = ConnectToDebugserver (connect_url);
894 }
895 }
896
897 if (error.Success())
898 {
899 StreamString packet;
900
901 if (wait_for_launch)
902 packet.PutCString("vAttachWait");
903 else
904 packet.PutCString("vAttachName");
905 packet.PutChar(';');
906 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
907
908 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
909
Chris Lattner24943d22010-06-08 16:52:24 +0000910 }
911 }
Chris Lattner24943d22010-06-08 16:52:24 +0000912 return error;
913}
914
Chris Lattner24943d22010-06-08 16:52:24 +0000915
916void
917ProcessGDBRemote::DidAttach ()
918{
Greg Claytone71e2582011-02-04 01:58:07 +0000919 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000920}
921
922Error
923ProcessGDBRemote::WillResume ()
924{
Greg Claytonc1f45872011-02-12 06:28:37 +0000925 m_continue_c_tids.clear();
926 m_continue_C_tids.clear();
927 m_continue_s_tids.clear();
928 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000929 return Error();
930}
931
932Error
933ProcessGDBRemote::DoResume ()
934{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000935 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000936 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
937 if (log)
938 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000939
940 Listener listener ("gdb-remote.resume-packet-sent");
941 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
942 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000943 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
944
Greg Claytonc1f45872011-02-12 06:28:37 +0000945 StreamString continue_packet;
946 bool continue_packet_error = false;
947 if (m_gdb_comm.HasAnyVContSupport ())
948 {
949 continue_packet.PutCString ("vCont");
950
951 if (!m_continue_c_tids.empty())
952 {
953 if (m_gdb_comm.GetVContSupported ('c'))
954 {
955 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 +0000956 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000957 }
958 else
959 continue_packet_error = true;
960 }
961
962 if (!continue_packet_error && !m_continue_C_tids.empty())
963 {
964 if (m_gdb_comm.GetVContSupported ('C'))
965 {
966 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 +0000967 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000968 }
969 else
970 continue_packet_error = true;
971 }
Greg Claytonb749a262010-12-03 06:02:24 +0000972
Greg Claytonc1f45872011-02-12 06:28:37 +0000973 if (!continue_packet_error && !m_continue_s_tids.empty())
974 {
975 if (m_gdb_comm.GetVContSupported ('s'))
976 {
977 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 +0000978 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000979 }
980 else
981 continue_packet_error = true;
982 }
983
984 if (!continue_packet_error && !m_continue_S_tids.empty())
985 {
986 if (m_gdb_comm.GetVContSupported ('S'))
987 {
988 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 +0000989 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000990 }
991 else
992 continue_packet_error = true;
993 }
994
995 if (continue_packet_error)
996 continue_packet.GetString().clear();
997 }
998 else
999 continue_packet_error = true;
1000
1001 if (continue_packet_error)
1002 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001003 // Either no vCont support, or we tried to use part of the vCont
1004 // packet that wasn't supported by the remote GDB server.
1005 // We need to try and make a simple packet that can do our continue
1006 const size_t num_threads = GetThreadList().GetSize();
1007 const size_t num_continue_c_tids = m_continue_c_tids.size();
1008 const size_t num_continue_C_tids = m_continue_C_tids.size();
1009 const size_t num_continue_s_tids = m_continue_s_tids.size();
1010 const size_t num_continue_S_tids = m_continue_S_tids.size();
1011 if (num_continue_c_tids > 0)
1012 {
1013 if (num_continue_c_tids == num_threads)
1014 {
1015 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001016 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001017 continue_packet.PutChar ('c');
1018 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001019 }
1020 else if (num_continue_c_tids == 1 &&
1021 num_continue_C_tids == 0 &&
1022 num_continue_s_tids == 0 &&
1023 num_continue_S_tids == 0 )
1024 {
1025 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001026 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001027 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001028 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001029 }
1030 }
1031
Greg Claytonde1dd812011-06-24 03:21:43 +00001032 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001033 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001034 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1035 num_continue_C_tids > 0 &&
1036 num_continue_s_tids == 0 &&
1037 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001038 {
1039 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001040 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001041 if (num_continue_C_tids > 1)
1042 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001043 // More that one thread with a signal, yet we don't have
1044 // vCont support and we are being asked to resume each
1045 // thread with a signal, we need to make sure they are
1046 // all the same signal, or we can't issue the continue
1047 // accurately with the current support...
1048 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001049 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001050 continue_packet_error = false;
1051 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1052 {
1053 if (m_continue_C_tids[i].second != continue_signo)
1054 continue_packet_error = true;
1055 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001056 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001057 if (!continue_packet_error)
1058 m_gdb_comm.SetCurrentThreadForRun (-1);
1059 }
1060 else
1061 {
1062 // Set the continue thread ID
1063 continue_packet_error = false;
1064 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001065 }
1066 if (!continue_packet_error)
1067 {
1068 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001069 continue_packet.Printf("C%2.2x", continue_signo);
1070 }
1071 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001072 }
1073
Greg Claytonde1dd812011-06-24 03:21:43 +00001074 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001075 {
1076 if (num_continue_s_tids == num_threads)
1077 {
1078 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001079 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001080 continue_packet.PutChar ('s');
1081 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001082 }
1083 else if (num_continue_c_tids == 0 &&
1084 num_continue_C_tids == 0 &&
1085 num_continue_s_tids == 1 &&
1086 num_continue_S_tids == 0 )
1087 {
1088 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001089 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001090 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001091 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001092 }
1093 }
1094
1095 if (!continue_packet_error && num_continue_S_tids > 0)
1096 {
1097 if (num_continue_S_tids == num_threads)
1098 {
1099 const int step_signo = m_continue_S_tids.front().second;
1100 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001101 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001102 if (num_continue_S_tids > 1)
1103 {
1104 for (size_t i=1; i<num_threads; ++i)
1105 {
1106 if (m_continue_S_tids[i].second != step_signo)
1107 continue_packet_error = true;
1108 }
1109 }
1110 if (!continue_packet_error)
1111 {
1112 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001113 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001114 continue_packet.Printf("S%2.2x", step_signo);
1115 }
1116 }
1117 else if (num_continue_c_tids == 0 &&
1118 num_continue_C_tids == 0 &&
1119 num_continue_s_tids == 0 &&
1120 num_continue_S_tids == 1 )
1121 {
1122 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001123 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001124 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001125 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001126 }
1127 }
1128 }
1129
1130 if (continue_packet_error)
1131 {
1132 error.SetErrorString ("can't make continue packet for this resume");
1133 }
1134 else
1135 {
1136 EventSP event_sp;
1137 TimeValue timeout;
1138 timeout = TimeValue::Now();
1139 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001140 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1141 {
1142 error.SetErrorString ("Trying to resume but the async thread is dead.");
1143 if (log)
1144 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1145 return error;
1146 }
1147
Greg Claytonc1f45872011-02-12 06:28:37 +00001148 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1149
1150 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001151 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001152 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001153 if (log)
1154 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1155 }
1156 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1157 {
1158 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1159 if (log)
1160 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1161 return error;
1162 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001163 }
Greg Claytonb749a262010-12-03 06:02:24 +00001164 }
1165
Jim Ingham3ae449a2010-11-17 02:32:00 +00001166 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001167}
1168
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001169void
1170ProcessGDBRemote::ClearThreadIDList ()
1171{
Greg Claytonff3448e2012-04-13 02:11:32 +00001172 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001173 m_thread_ids.clear();
1174}
1175
1176bool
1177ProcessGDBRemote::UpdateThreadIDList ()
1178{
Greg Claytonff3448e2012-04-13 02:11:32 +00001179 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001180 bool sequence_mutex_unavailable = false;
1181 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1182 if (sequence_mutex_unavailable)
1183 {
1184#if defined (LLDB_CONFIGURATION_DEBUG)
1185 assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
1186#endif
1187 return false; // We just didn't get the list
1188 }
1189 return true;
1190}
1191
Greg Claytonae932352012-04-10 00:18:59 +00001192bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001193ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001194{
1195 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001196 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001197 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001198 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001199
1200 size_t num_thread_ids = m_thread_ids.size();
1201 // The "m_thread_ids" thread ID list should always be updated after each stop
1202 // reply packet, but in case it isn't, update it here.
1203 if (num_thread_ids == 0)
1204 {
1205 if (!UpdateThreadIDList ())
1206 return false;
1207 num_thread_ids = m_thread_ids.size();
1208 }
Chris Lattner24943d22010-06-08 16:52:24 +00001209
Greg Clayton37f962e2011-08-22 02:49:39 +00001210 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001211 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001212 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001213 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001214 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001215 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1216 if (!thread_sp)
Greg Claytonf4124de2012-02-21 00:09:25 +00001217 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001218 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001219 }
Chris Lattner24943d22010-06-08 16:52:24 +00001220 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001221
Greg Claytonae932352012-04-10 00:18:59 +00001222 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001223}
1224
1225
1226StateType
1227ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1228{
Greg Clayton261a18b2011-06-02 22:22:38 +00001229 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001230 const char stop_type = stop_packet.GetChar();
1231 switch (stop_type)
1232 {
1233 case 'T':
1234 case 'S':
1235 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001236 if (GetStopID() == 0)
1237 {
1238 // Our first stop, make sure we have a process ID, and also make
1239 // sure we know about our registers
1240 if (GetID() == LLDB_INVALID_PROCESS_ID)
1241 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001242 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001243 if (pid != LLDB_INVALID_PROCESS_ID)
1244 SetID (pid);
1245 }
1246 BuildDynamicRegisterInfo (true);
1247 }
Chris Lattner24943d22010-06-08 16:52:24 +00001248 // Stop with signal and thread info
1249 const uint8_t signo = stop_packet.GetHexU8();
1250 std::string name;
1251 std::string value;
1252 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001253 std::string reason;
1254 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001255 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001256 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001257 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1258 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001259 ThreadSP thread_sp;
1260
Chris Lattner24943d22010-06-08 16:52:24 +00001261 while (stop_packet.GetNameColonValue(name, value))
1262 {
1263 if (name.compare("metype") == 0)
1264 {
1265 // exception type in big endian hex
1266 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1267 }
1268 else if (name.compare("mecount") == 0)
1269 {
1270 // exception count in big endian hex
1271 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1272 }
1273 else if (name.compare("medata") == 0)
1274 {
1275 // exception data in big endian hex
1276 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1277 }
1278 else if (name.compare("thread") == 0)
1279 {
1280 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001281 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001282 // m_thread_list does have its own mutex, but we need to
1283 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1284 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001285 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001286 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001287 if (!thread_sp)
1288 {
1289 // Create the thread if we need to
Greg Claytonf4124de2012-02-21 00:09:25 +00001290 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001291 m_thread_list.AddThread(thread_sp);
1292 }
Chris Lattner24943d22010-06-08 16:52:24 +00001293 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001294 else if (name.compare("threads") == 0)
1295 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001296 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001297 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001298 // A comma separated list of all threads in the current
1299 // process that includes the thread for this stop reply
1300 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001301 size_t comma_pos;
1302 lldb::tid_t tid;
1303 while ((comma_pos = value.find(',')) != std::string::npos)
1304 {
1305 value[comma_pos] = '\0';
1306 // thread in big endian hex
1307 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1308 if (tid != LLDB_INVALID_THREAD_ID)
1309 m_thread_ids.push_back (tid);
1310 value.erase(0, comma_pos + 1);
1311
1312 }
1313 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1314 if (tid != LLDB_INVALID_THREAD_ID)
1315 m_thread_ids.push_back (tid);
1316 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001317 else if (name.compare("hexname") == 0)
1318 {
1319 StringExtractor name_extractor;
1320 // Swap "value" over into "name_extractor"
1321 name_extractor.GetStringRef().swap(value);
1322 // Now convert the HEX bytes into a string value
1323 name_extractor.GetHexByteString (value);
1324 thread_name.swap (value);
1325 }
Chris Lattner24943d22010-06-08 16:52:24 +00001326 else if (name.compare("name") == 0)
1327 {
1328 thread_name.swap (value);
1329 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001330 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001331 {
1332 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1333 }
Greg Clayton65611552011-06-04 01:26:29 +00001334 else if (name.compare("reason") == 0)
1335 {
1336 reason.swap(value);
1337 }
1338 else if (name.compare("description") == 0)
1339 {
1340 StringExtractor desc_extractor;
1341 // Swap "value" over into "name_extractor"
1342 desc_extractor.GetStringRef().swap(value);
1343 // Now convert the HEX bytes into a string value
1344 desc_extractor.GetHexByteString (thread_name);
1345 }
Greg Claytona875b642011-01-09 21:07:35 +00001346 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1347 {
1348 // We have a register number that contains an expedited
1349 // register value. Lets supply this register to our thread
1350 // so it won't have to go and read it.
1351 if (thread_sp)
1352 {
1353 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1354
1355 if (reg != UINT32_MAX)
1356 {
1357 StringExtractor reg_value_extractor;
1358 // Swap "value" over into "reg_value_extractor"
1359 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001360 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1361 {
1362 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1363 name.c_str(),
1364 reg,
1365 reg,
1366 reg_value_extractor.GetStringRef().c_str(),
1367 stop_packet.GetStringRef().c_str());
1368 }
Greg Claytona875b642011-01-09 21:07:35 +00001369 }
1370 }
1371 }
Chris Lattner24943d22010-06-08 16:52:24 +00001372 }
Chris Lattner24943d22010-06-08 16:52:24 +00001373
1374 if (thread_sp)
1375 {
1376 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1377
1378 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001379 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001380 if (exc_type != 0)
1381 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001382 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001383
1384 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1385 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001386 exc_data_size,
1387 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001388 exc_data_size >= 2 ? exc_data[1] : 0,
1389 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001390 }
Greg Clayton65611552011-06-04 01:26:29 +00001391 else
Chris Lattner24943d22010-06-08 16:52:24 +00001392 {
Greg Clayton65611552011-06-04 01:26:29 +00001393 bool handled = false;
1394 if (!reason.empty())
1395 {
1396 if (reason.compare("trace") == 0)
1397 {
1398 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1399 handled = true;
1400 }
1401 else if (reason.compare("breakpoint") == 0)
1402 {
1403 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001404 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001405 if (bp_site_sp)
1406 {
1407 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1408 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1409 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1410 if (bp_site_sp->ValidForThisThread (gdb_thread))
1411 {
1412 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1413 handled = true;
1414 }
1415 }
1416
1417 if (!handled)
1418 {
1419 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1420 }
1421 }
1422 else if (reason.compare("trap") == 0)
1423 {
1424 // Let the trap just use the standard signal stop reason below...
1425 }
1426 else if (reason.compare("watchpoint") == 0)
1427 {
1428 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1429 // TODO: locate the watchpoint somehow...
1430 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1431 handled = true;
1432 }
1433 else if (reason.compare("exception") == 0)
1434 {
1435 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1436 handled = true;
1437 }
1438 }
1439
1440 if (signo)
1441 {
1442 if (signo == SIGTRAP)
1443 {
1444 // Currently we are going to assume SIGTRAP means we are either
1445 // hitting a breakpoint or hardware single stepping.
1446 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001447 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001448 if (bp_site_sp)
1449 {
1450 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1451 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1452 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1453 if (bp_site_sp->ValidForThisThread (gdb_thread))
1454 {
1455 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1456 handled = true;
1457 }
1458 }
1459 if (!handled)
1460 {
1461 // TODO: check for breakpoint or trap opcode in case there is a hard
1462 // coded software trap
1463 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1464 handled = true;
1465 }
1466 }
1467 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001468 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001469 }
1470 else
1471 {
Greg Clayton643ee732010-08-04 01:40:35 +00001472 StopInfoSP invalid_stop_info_sp;
1473 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001474 }
Greg Clayton65611552011-06-04 01:26:29 +00001475
1476 if (!description.empty())
1477 {
1478 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1479 if (stop_info_sp)
1480 {
1481 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001482 }
Greg Clayton65611552011-06-04 01:26:29 +00001483 else
1484 {
1485 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1486 }
1487 }
1488 }
Chris Lattner24943d22010-06-08 16:52:24 +00001489 }
1490 return eStateStopped;
1491 }
1492 break;
1493
1494 case 'W':
1495 // process exited
1496 return eStateExited;
1497
1498 default:
1499 break;
1500 }
1501 return eStateInvalid;
1502}
1503
1504void
1505ProcessGDBRemote::RefreshStateAfterStop ()
1506{
Greg Claytonff3448e2012-04-13 02:11:32 +00001507 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001508 m_thread_ids.clear();
1509 // Set the thread stop info. It might have a "threads" key whose value is
1510 // a list of all thread IDs in the current process, so m_thread_ids might
1511 // get set.
1512 SetThreadStopInfo (m_last_stop_packet);
1513 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1514 if (m_thread_ids.empty())
1515 {
1516 // No, we need to fetch the thread list manually
1517 UpdateThreadIDList();
1518 }
1519
Chris Lattner24943d22010-06-08 16:52:24 +00001520 // Let all threads recover from stopping and do any clean up based
1521 // on the previous thread state (if any).
1522 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001523
Chris Lattner24943d22010-06-08 16:52:24 +00001524}
1525
1526Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001527ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001528{
1529 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001530
Greg Claytona4881d02011-01-22 07:12:45 +00001531 bool timed_out = false;
1532 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001533
1534 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001535 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001536 // We are being asked to halt during an attach. We need to just close
1537 // our file handle and debugserver will go away, and we can be done...
1538 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001539 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001540 else
1541 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001542 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001543 {
1544 if (timed_out)
1545 error.SetErrorString("timed out sending interrupt packet");
1546 else
1547 error.SetErrorString("unknown error sending interrupt packet");
1548 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001549
1550 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001551 }
Chris Lattner24943d22010-06-08 16:52:24 +00001552 return error;
1553}
1554
1555Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001556ProcessGDBRemote::InterruptIfRunning
1557(
1558 bool discard_thread_plans,
1559 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001560 EventSP &stop_event_sp
1561)
Chris Lattner24943d22010-06-08 16:52:24 +00001562{
1563 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001564
Greg Clayton2860ba92011-01-23 19:58:49 +00001565 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1566
Greg Clayton68ca8232011-01-25 02:58:48 +00001567 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001568 const bool is_running = m_gdb_comm.IsRunning();
1569 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001570 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001571 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001572 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001573 is_running);
1574
Greg Clayton2860ba92011-01-23 19:58:49 +00001575 if (discard_thread_plans)
1576 {
1577 if (log)
1578 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1579 m_thread_list.DiscardThreadPlans();
1580 }
1581 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001582 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001583 if (catch_stop_event)
1584 {
1585 if (log)
1586 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1587 PausePrivateStateThread();
1588 paused_private_state_thread = true;
1589 }
1590
Greg Clayton4fb400f2010-09-27 21:07:38 +00001591 bool timed_out = false;
1592 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001593
Greg Clayton05e4d972012-03-29 01:55:41 +00001594 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001595 {
1596 if (timed_out)
1597 error.SetErrorString("timed out sending interrupt packet");
1598 else
1599 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001600 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001601 ResumePrivateStateThread();
1602 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001603 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001604
Greg Clayton72e1c782011-01-22 23:43:18 +00001605 if (catch_stop_event)
1606 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001607 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001608 TimeValue timeout_time;
1609 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001610 timeout_time.OffsetWithSeconds(5);
1611 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001612
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001613 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001614 if (log)
1615 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001616
Greg Clayton2860ba92011-01-23 19:58:49 +00001617 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001618 error.SetErrorString("unable to verify target stopped");
1619 }
1620
Greg Clayton68ca8232011-01-25 02:58:48 +00001621 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001622 {
1623 if (log)
1624 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001625 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001626 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001627 }
Chris Lattner24943d22010-06-08 16:52:24 +00001628 return error;
1629}
1630
Greg Clayton4fb400f2010-09-27 21:07:38 +00001631Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001632ProcessGDBRemote::WillDetach ()
1633{
Greg Clayton2860ba92011-01-23 19:58:49 +00001634 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1635 if (log)
1636 log->Printf ("ProcessGDBRemote::WillDetach()");
1637
Greg Clayton72e1c782011-01-22 23:43:18 +00001638 bool discard_thread_plans = true;
1639 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001640 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001641 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001642}
1643
1644Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001645ProcessGDBRemote::DoDetach()
1646{
1647 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001648 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001649 if (log)
1650 log->Printf ("ProcessGDBRemote::DoDetach()");
1651
1652 DisableAllBreakpointSites ();
1653
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001654 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001655
Greg Clayton516f0842012-04-11 00:24:49 +00001656 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001657 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001658 {
Greg Clayton516f0842012-04-11 00:24:49 +00001659 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001660 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1661 else
1662 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001663 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001664 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001665 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001666
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001667 SetPrivateState (eStateDetached);
1668 ResumePrivateStateThread();
1669
1670 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001671 return error;
1672}
Chris Lattner24943d22010-06-08 16:52:24 +00001673
1674Error
1675ProcessGDBRemote::DoDestroy ()
1676{
1677 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001678 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001679 if (log)
1680 log->Printf ("ProcessGDBRemote::DoDestroy()");
1681
1682 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001683 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001684 {
Jim Ingham8226e942011-10-28 01:11:35 +00001685 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001686 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001687
1688 StringExtractorGDBRemote response;
1689 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001690 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001691 {
1692 char packet_cmd = response.GetChar(0);
1693
1694 if (packet_cmd == 'W' || packet_cmd == 'X')
1695 {
Greg Clayton06709002011-12-06 04:51:14 +00001696 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001697 ClearThreadIDList ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001698 SetExitStatus(response.GetHexU8(), NULL);
1699 }
1700 }
1701 else
1702 {
1703 SetExitStatus(SIGABRT, NULL);
1704 //error.SetErrorString("kill packet failed");
1705 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001706 }
1707 }
Chris Lattner24943d22010-06-08 16:52:24 +00001708 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001709 KillDebugserverProcess ();
1710 return error;
1711}
1712
Chris Lattner24943d22010-06-08 16:52:24 +00001713//------------------------------------------------------------------
1714// Process Queries
1715//------------------------------------------------------------------
1716
1717bool
1718ProcessGDBRemote::IsAlive ()
1719{
Greg Clayton58e844b2010-12-08 05:08:21 +00001720 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001721}
1722
1723addr_t
1724ProcessGDBRemote::GetImageInfoAddress()
1725{
Greg Clayton516f0842012-04-11 00:24:49 +00001726 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001727}
1728
Chris Lattner24943d22010-06-08 16:52:24 +00001729//------------------------------------------------------------------
1730// Process Memory
1731//------------------------------------------------------------------
1732size_t
1733ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1734{
1735 if (size > m_max_memory_size)
1736 {
1737 // Keep memory read sizes down to a sane limit. This function will be
1738 // called multiple times in order to complete the task by
1739 // lldb_private::Process so it is ok to do this.
1740 size = m_max_memory_size;
1741 }
1742
1743 char packet[64];
1744 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1745 assert (packet_len + 1 < sizeof(packet));
1746 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001747 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001748 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001749 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001750 {
1751 error.Clear();
1752 return response.GetHexBytes(buf, size, '\xdd');
1753 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001754 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001755 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001756 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001757 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1758 else
1759 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1760 }
1761 else
1762 {
1763 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1764 }
1765 return 0;
1766}
1767
1768size_t
1769ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1770{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001771 if (size > m_max_memory_size)
1772 {
1773 // Keep memory read sizes down to a sane limit. This function will be
1774 // called multiple times in order to complete the task by
1775 // lldb_private::Process so it is ok to do this.
1776 size = m_max_memory_size;
1777 }
1778
Chris Lattner24943d22010-06-08 16:52:24 +00001779 StreamString packet;
1780 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001781 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001782 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001783 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001784 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001785 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001786 {
1787 error.Clear();
1788 return size;
1789 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001790 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001791 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001792 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001793 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1794 else
1795 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1796 }
1797 else
1798 {
1799 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1800 }
1801 return 0;
1802}
1803
1804lldb::addr_t
1805ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1806{
Greg Clayton989816b2011-05-14 01:50:35 +00001807 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1808
Greg Clayton2f085c62011-05-15 01:25:55 +00001809 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001810 switch (supported)
1811 {
1812 case eLazyBoolCalculate:
1813 case eLazyBoolYes:
1814 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1815 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1816 return allocated_addr;
1817
1818 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001819 // Call mmap() to create memory in the inferior..
1820 unsigned prot = 0;
1821 if (permissions & lldb::ePermissionsReadable)
1822 prot |= eMmapProtRead;
1823 if (permissions & lldb::ePermissionsWritable)
1824 prot |= eMmapProtWrite;
1825 if (permissions & lldb::ePermissionsExecutable)
1826 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001827
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001828 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1829 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1830 m_addr_to_mmap_size[allocated_addr] = size;
1831 else
1832 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001833 break;
1834 }
1835
Chris Lattner24943d22010-06-08 16:52:24 +00001836 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001837 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001838 else
1839 error.Clear();
1840 return allocated_addr;
1841}
1842
1843Error
Greg Claytona9385532011-11-18 07:03:08 +00001844ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1845 MemoryRegionInfo &region_info)
1846{
1847
1848 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1849 return error;
1850}
1851
1852Error
Chris Lattner24943d22010-06-08 16:52:24 +00001853ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1854{
1855 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001856 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1857
1858 switch (supported)
1859 {
1860 case eLazyBoolCalculate:
1861 // We should never be deallocating memory without allocating memory
1862 // first so we should never get eLazyBoolCalculate
1863 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1864 break;
1865
1866 case eLazyBoolYes:
1867 if (!m_gdb_comm.DeallocateMemory (addr))
1868 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1869 break;
1870
1871 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001872 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001873 {
1874 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001875 if (pos != m_addr_to_mmap_size.end() &&
1876 InferiorCallMunmap(this, addr, pos->second))
1877 m_addr_to_mmap_size.erase (pos);
1878 else
1879 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001880 }
1881 break;
1882 }
1883
Chris Lattner24943d22010-06-08 16:52:24 +00001884 return error;
1885}
1886
1887
1888//------------------------------------------------------------------
1889// Process STDIO
1890//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001891size_t
1892ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1893{
1894 if (m_stdio_communication.IsConnected())
1895 {
1896 ConnectionStatus status;
1897 m_stdio_communication.Write(src, src_len, status, NULL);
1898 }
1899 return 0;
1900}
1901
1902Error
1903ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1904{
1905 Error error;
1906 assert (bp_site != NULL);
1907
Greg Claytone005f2c2010-11-06 01:53:30 +00001908 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001909 user_id_t site_id = bp_site->GetID();
1910 const addr_t addr = bp_site->GetLoadAddress();
1911 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001912 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001913
1914 if (bp_site->IsEnabled())
1915 {
1916 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001917 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 +00001918 return error;
1919 }
1920 else
1921 {
1922 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1923
1924 if (bp_site->HardwarePreferred())
1925 {
1926 // Try and set hardware breakpoint, and if that fails, fall through
1927 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001928 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001929 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001930 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001931 {
1932 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001933 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001934 return error;
1935 }
Chris Lattner24943d22010-06-08 16:52:24 +00001936 }
1937 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001938
1939 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001940 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001941 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1942 {
1943 bp_site->SetEnabled(true);
1944 bp_site->SetType (BreakpointSite::eExternal);
1945 return error;
1946 }
Chris Lattner24943d22010-06-08 16:52:24 +00001947 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001948
1949 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001950 }
1951
1952 if (log)
1953 {
1954 const char *err_string = error.AsCString();
1955 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1956 bp_site->GetLoadAddress(),
1957 err_string ? err_string : "NULL");
1958 }
1959 // We shouldn't reach here on a successful breakpoint enable...
1960 if (error.Success())
1961 error.SetErrorToGenericError();
1962 return error;
1963}
1964
1965Error
1966ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1967{
1968 Error error;
1969 assert (bp_site != NULL);
1970 addr_t addr = bp_site->GetLoadAddress();
1971 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001972 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001973 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001974 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001975
1976 if (bp_site->IsEnabled())
1977 {
1978 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1979
Greg Claytonb72d0f02011-04-12 05:54:46 +00001980 BreakpointSite::Type bp_type = bp_site->GetType();
1981 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001982 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001983 case BreakpointSite::eSoftware:
1984 error = DisableSoftwareBreakpoint (bp_site);
1985 break;
1986
1987 case BreakpointSite::eHardware:
1988 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1989 error.SetErrorToGenericError();
1990 break;
1991
1992 case BreakpointSite::eExternal:
1993 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1994 error.SetErrorToGenericError();
1995 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001996 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001997 if (error.Success())
1998 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001999 }
2000 else
2001 {
2002 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002003 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 +00002004 return error;
2005 }
2006
2007 if (error.Success())
2008 error.SetErrorToGenericError();
2009 return error;
2010}
2011
Johnny Chen21900fb2011-09-06 22:38:36 +00002012// Pre-requisite: wp != NULL.
2013static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002014GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002015{
2016 assert(wp);
2017 bool watch_read = wp->WatchpointRead();
2018 bool watch_write = wp->WatchpointWrite();
2019
2020 // watch_read and watch_write cannot both be false.
2021 assert(watch_read || watch_write);
2022 if (watch_read && watch_write)
2023 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002024 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002025 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002026 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002027 return eWatchpointWrite;
2028}
2029
Chris Lattner24943d22010-06-08 16:52:24 +00002030Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002031ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002032{
2033 Error error;
2034 if (wp)
2035 {
2036 user_id_t watchID = wp->GetID();
2037 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002038 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002039 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002040 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002041 if (wp->IsEnabled())
2042 {
2043 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002044 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002045 return error;
2046 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002047
2048 GDBStoppointType type = GetGDBStoppointType(wp);
2049 // Pass down an appropriate z/Z packet...
2050 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002051 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002052 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2053 {
2054 wp->SetEnabled(true);
2055 return error;
2056 }
2057 else
2058 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002059 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002060 else
2061 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002062 }
2063 else
2064 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002065 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002066 }
2067 if (error.Success())
2068 error.SetErrorToGenericError();
2069 return error;
2070}
2071
2072Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002073ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002074{
2075 Error error;
2076 if (wp)
2077 {
2078 user_id_t watchID = wp->GetID();
2079
Greg Claytone005f2c2010-11-06 01:53:30 +00002080 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002081
2082 addr_t addr = wp->GetLoadAddress();
2083 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002084 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002085
Johnny Chen21900fb2011-09-06 22:38:36 +00002086 if (!wp->IsEnabled())
2087 {
2088 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002089 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00002090 return error;
2091 }
2092
Chris Lattner24943d22010-06-08 16:52:24 +00002093 if (wp->IsHardware())
2094 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002095 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002096 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002097 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2098 {
2099 wp->SetEnabled(false);
2100 return error;
2101 }
2102 else
2103 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002104 }
2105 // TODO: clear software watchpoints if we implement them
2106 }
2107 else
2108 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002109 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002110 }
2111 if (error.Success())
2112 error.SetErrorToGenericError();
2113 return error;
2114}
2115
2116void
2117ProcessGDBRemote::Clear()
2118{
2119 m_flags = 0;
2120 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002121}
2122
2123Error
2124ProcessGDBRemote::DoSignal (int signo)
2125{
2126 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002127 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002128 if (log)
2129 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2130
2131 if (!m_gdb_comm.SendAsyncSignal (signo))
2132 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2133 return error;
2134}
2135
Chris Lattner24943d22010-06-08 16:52:24 +00002136Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002137ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2138{
2139 ProcessLaunchInfo launch_info;
2140 return StartDebugserverProcess(debugserver_url, launch_info);
2141}
2142
2143Error
2144ProcessGDBRemote::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 +00002145{
2146 Error error;
2147 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2148 {
2149 // If we locate debugserver, keep that located version around
2150 static FileSpec g_debugserver_file_spec;
2151
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002152 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002153 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002154 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002155
2156 // Always check to see if we have an environment override for the path
2157 // to the debugserver to use and use it if we do.
2158 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2159 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002160 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002161 else
2162 debugserver_file_spec = g_debugserver_file_spec;
2163 bool debugserver_exists = debugserver_file_spec.Exists();
2164 if (!debugserver_exists)
2165 {
2166 // The debugserver binary is in the LLDB.framework/Resources
2167 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002168 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002169 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002170 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002171 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002172 if (debugserver_exists)
2173 {
2174 g_debugserver_file_spec = debugserver_file_spec;
2175 }
2176 else
2177 {
2178 g_debugserver_file_spec.Clear();
2179 debugserver_file_spec.Clear();
2180 }
Chris Lattner24943d22010-06-08 16:52:24 +00002181 }
2182 }
2183
2184 if (debugserver_exists)
2185 {
2186 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2187
2188 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002189
Greg Claytone005f2c2010-11-06 01:53:30 +00002190 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002191
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002192 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002193 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002194
Chris Lattner24943d22010-06-08 16:52:24 +00002195 // Start args with "debugserver /file/path -r --"
2196 debugserver_args.AppendArgument(debugserver_path);
2197 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002198 // use native registers, not the GDB registers
2199 debugserver_args.AppendArgument("--native-regs");
2200 // make debugserver run in its own session so signals generated by
2201 // special terminal key sequences (^C) don't affect debugserver
2202 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002203
Chris Lattner24943d22010-06-08 16:52:24 +00002204 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2205 if (env_debugserver_log_file)
2206 {
2207 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2208 debugserver_args.AppendArgument(arg_cstr);
2209 }
2210
2211 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2212 if (env_debugserver_log_flags)
2213 {
2214 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2215 debugserver_args.AppendArgument(arg_cstr);
2216 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002217// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002218// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002219
Greg Claytonb72d0f02011-04-12 05:54:46 +00002220 // We currently send down all arguments, attach pids, or attach
2221 // process names in dedicated GDB server packets, so we don't need
2222 // to pass them as arguments. This is currently because of all the
2223 // things we need to setup prior to launching: the environment,
2224 // current working dir, file actions, etc.
2225#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002226 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002227 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002228 {
Greg Claytona2f74232011-02-24 22:24:29 +00002229 // Terminate the debugserver args so we can now append the inferior args
2230 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002231
Greg Claytona2f74232011-02-24 22:24:29 +00002232 for (int i = 0; inferior_argv[i] != NULL; ++i)
2233 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002234 }
2235 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2236 {
2237 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2238 debugserver_args.AppendArgument (arg_cstr);
2239 }
2240 else if (attach_name && attach_name[0])
2241 {
2242 if (wait_for_launch)
2243 debugserver_args.AppendArgument ("--waitfor");
2244 else
2245 debugserver_args.AppendArgument ("--attach");
2246 debugserver_args.AppendArgument (attach_name);
2247 }
Chris Lattner24943d22010-06-08 16:52:24 +00002248#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002249
2250 ProcessLaunchInfo::FileAction file_action;
2251
2252 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2253 // to "/dev/null" if we run into any problems.
2254 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002255 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002256 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002257 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002258 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002259 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002260
2261 if (log)
2262 {
2263 StreamString strm;
2264 debugserver_args.Dump (&strm);
2265 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2266 }
2267
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002268 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2269 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002270
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002271 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002272
Greg Claytonb72d0f02011-04-12 05:54:46 +00002273 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002274 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002275 else
Chris Lattner24943d22010-06-08 16:52:24 +00002276 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2277
2278 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002279 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002280 }
2281 else
2282 {
Greg Clayton9c236732011-10-26 00:56:27 +00002283 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002284 }
2285
2286 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2287 StartAsyncThread ();
2288 }
2289 return error;
2290}
2291
2292bool
2293ProcessGDBRemote::MonitorDebugserverProcess
2294(
2295 void *callback_baton,
2296 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002297 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002298 int signo, // Zero for no signal
2299 int exit_status // Exit value of process if signal is zero
2300)
2301{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002302 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2303 // and might not exist anymore, so we need to carefully try to get the
2304 // target for this process first since we have a race condition when
2305 // we are done running between getting the notice that the inferior
2306 // process has died and the debugserver that was debugging this process.
2307 // In our test suite, we are also continually running process after
2308 // process, so we must be very careful to make sure:
2309 // 1 - process object hasn't been deleted already
2310 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002311
2312 // "debugserver_pid" argument passed in is the process ID for
2313 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002314 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002315
Greg Clayton75ccf502010-08-21 02:22:51 +00002316 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002317
Greg Clayton1c4642c2011-11-16 05:37:56 +00002318 // Get a shared pointer to the target that has a matching process pointer.
2319 // This target could be gone, or the target could already have a new process
2320 // object inside of it
2321 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2322
Greg Clayton72e1c782011-01-22 23:43:18 +00002323 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002324 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 +00002325
Greg Clayton1c4642c2011-11-16 05:37:56 +00002326 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002327 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002328 // We found a process in a target that matches, but another thread
2329 // might be in the process of launching a new process that will
2330 // soon replace it, so get a shared pointer to the process so we
2331 // can keep it alive.
2332 ProcessSP process_sp (target_sp->GetProcessSP());
2333 // Now we have a shared pointer to the process that can't go away on us
2334 // so we now make sure it was the same as the one passed in, and also make
2335 // sure that our previous "process *" didn't get deleted and have a new
2336 // "process *" created in its place with the same pointer. To verify this
2337 // we make sure the process has our debugserver process ID. If we pass all
2338 // of these tests, then we are sure that this process is the one we were
2339 // looking for.
2340 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002341 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002342 // Sleep for a half a second to make sure our inferior process has
2343 // time to set its exit status before we set it incorrectly when
2344 // both the debugserver and the inferior process shut down.
2345 usleep (500000);
2346 // If our process hasn't yet exited, debugserver might have died.
2347 // If the process did exit, the we are reaping it.
2348 const StateType state = process->GetState();
2349
2350 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2351 state != eStateInvalid &&
2352 state != eStateUnloaded &&
2353 state != eStateExited &&
2354 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002355 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002356 char error_str[1024];
2357 if (signo)
2358 {
2359 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2360 if (signal_cstr)
2361 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2362 else
2363 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2364 }
Chris Lattner24943d22010-06-08 16:52:24 +00002365 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002366 {
2367 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2368 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002369
Greg Clayton1c4642c2011-11-16 05:37:56 +00002370 process->SetExitStatus (-1, error_str);
2371 }
2372 // Debugserver has exited we need to let our ProcessGDBRemote
2373 // know that it no longer has a debugserver instance
2374 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002375 }
Chris Lattner24943d22010-06-08 16:52:24 +00002376 }
2377 return true;
2378}
2379
2380void
2381ProcessGDBRemote::KillDebugserverProcess ()
2382{
2383 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2384 {
2385 ::kill (m_debugserver_pid, SIGINT);
2386 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2387 }
2388}
2389
2390void
2391ProcessGDBRemote::Initialize()
2392{
2393 static bool g_initialized = false;
2394
2395 if (g_initialized == false)
2396 {
2397 g_initialized = true;
2398 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2399 GetPluginDescriptionStatic(),
2400 CreateInstance);
2401
2402 Log::Callbacks log_callbacks = {
2403 ProcessGDBRemoteLog::DisableLog,
2404 ProcessGDBRemoteLog::EnableLog,
2405 ProcessGDBRemoteLog::ListLogCategories
2406 };
2407
2408 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2409 }
2410}
2411
2412bool
Chris Lattner24943d22010-06-08 16:52:24 +00002413ProcessGDBRemote::StartAsyncThread ()
2414{
Greg Claytone005f2c2010-11-06 01:53:30 +00002415 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002416
2417 if (log)
2418 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2419
2420 // Create a thread that watches our internal state and controls which
2421 // events make it to clients (into the DCProcess event queue).
2422 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002423 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002424}
2425
2426void
2427ProcessGDBRemote::StopAsyncThread ()
2428{
Greg Claytone005f2c2010-11-06 01:53:30 +00002429 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002430
2431 if (log)
2432 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2433
2434 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002435
2436 // This will shut down the async thread.
2437 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002438
2439 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002440 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002441 {
2442 Host::ThreadJoin (m_async_thread, NULL, NULL);
2443 }
2444}
2445
2446
2447void *
2448ProcessGDBRemote::AsyncThread (void *arg)
2449{
2450 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2451
Greg Claytone005f2c2010-11-06 01:53:30 +00002452 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002453 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002454 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002455
2456 Listener listener ("ProcessGDBRemote::AsyncThread");
2457 EventSP event_sp;
2458 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2459 eBroadcastBitAsyncThreadShouldExit;
2460
2461 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2462 {
Greg Claytona2f74232011-02-24 22:24:29 +00002463 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2464
Chris Lattner24943d22010-06-08 16:52:24 +00002465 bool done = false;
2466 while (!done)
2467 {
2468 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002469 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002470 if (listener.WaitForEvent (NULL, event_sp))
2471 {
2472 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002473 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002474 {
Greg Claytona2f74232011-02-24 22:24:29 +00002475 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002476 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 +00002477
Greg Claytona2f74232011-02-24 22:24:29 +00002478 switch (event_type)
2479 {
2480 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002481 {
Greg Claytona2f74232011-02-24 22:24:29 +00002482 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002483
Greg Claytona2f74232011-02-24 22:24:29 +00002484 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002485 {
Greg Claytona2f74232011-02-24 22:24:29 +00002486 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2487 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2488 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002489 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002490
Greg Claytona2f74232011-02-24 22:24:29 +00002491 if (::strstr (continue_cstr, "vAttach") == NULL)
2492 process->SetPrivateState(eStateRunning);
2493 StringExtractorGDBRemote response;
2494 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002495
Greg Claytona2f74232011-02-24 22:24:29 +00002496 switch (stop_state)
2497 {
2498 case eStateStopped:
2499 case eStateCrashed:
2500 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002501 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002502 process->SetPrivateState (stop_state);
2503 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002504
Greg Claytona2f74232011-02-24 22:24:29 +00002505 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002506 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002507 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002508 response.SetFilePos(1);
2509 process->SetExitStatus(response.GetHexU8(), NULL);
2510 done = true;
2511 break;
2512
2513 case eStateInvalid:
2514 process->SetExitStatus(-1, "lost connection");
2515 break;
2516
2517 default:
2518 process->SetPrivateState (stop_state);
2519 break;
2520 }
Chris Lattner24943d22010-06-08 16:52:24 +00002521 }
2522 }
Greg Claytona2f74232011-02-24 22:24:29 +00002523 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002524
Greg Claytona2f74232011-02-24 22:24:29 +00002525 case eBroadcastBitAsyncThreadShouldExit:
2526 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002527 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002528 done = true;
2529 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002530
Greg Claytona2f74232011-02-24 22:24:29 +00002531 default:
2532 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002533 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 +00002534 done = true;
2535 break;
2536 }
2537 }
2538 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2539 {
2540 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2541 {
2542 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002543 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002544 }
Chris Lattner24943d22010-06-08 16:52:24 +00002545 }
2546 }
2547 else
2548 {
2549 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002550 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 +00002551 done = true;
2552 }
2553 }
2554 }
2555
2556 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002557 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002558
2559 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2560 return NULL;
2561}
2562
Chris Lattner24943d22010-06-08 16:52:24 +00002563const char *
2564ProcessGDBRemote::GetDispatchQueueNameForThread
2565(
2566 addr_t thread_dispatch_qaddr,
2567 std::string &dispatch_queue_name
2568)
2569{
2570 dispatch_queue_name.clear();
2571 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2572 {
2573 // Cache the dispatch_queue_offsets_addr value so we don't always have
2574 // to look it up
2575 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2576 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002577 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2578 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002579 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2580 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002581 if (module_sp)
2582 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2583
2584 if (dispatch_queue_offsets_symbol == NULL)
2585 {
Greg Clayton444fe992012-02-26 05:51:37 +00002586 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2587 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002588 if (module_sp)
2589 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2590 }
Chris Lattner24943d22010-06-08 16:52:24 +00002591 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002592 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002593
2594 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2595 return NULL;
2596 }
2597
2598 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002599 DataExtractor data (memory_buffer,
2600 sizeof(memory_buffer),
2601 m_target.GetArchitecture().GetByteOrder(),
2602 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002603
2604 // Excerpt from src/queue_private.h
2605 struct dispatch_queue_offsets_s
2606 {
2607 uint16_t dqo_version;
2608 uint16_t dqo_label;
2609 uint16_t dqo_label_size;
2610 } dispatch_queue_offsets;
2611
2612
2613 Error error;
2614 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2615 {
2616 uint32_t data_offset = 0;
2617 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2618 {
2619 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2620 {
2621 data_offset = 0;
2622 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2623 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2624 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2625 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2626 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2627 dispatch_queue_name.erase (bytes_read);
2628 }
2629 }
2630 }
2631 }
2632 if (dispatch_queue_name.empty())
2633 return NULL;
2634 return dispatch_queue_name.c_str();
2635}
2636
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002637//uint32_t
2638//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2639//{
2640// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2641// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2642// if (m_local_debugserver)
2643// {
2644// return Host::ListProcessesMatchingName (name, matches, pids);
2645// }
2646// else
2647// {
2648// // FIXME: Implement talking to the remote debugserver.
2649// return 0;
2650// }
2651//
2652//}
2653//
Jim Ingham55e01d82011-01-22 01:33:44 +00002654bool
2655ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2656 lldb_private::StoppointCallbackContext *context,
2657 lldb::user_id_t break_id,
2658 lldb::user_id_t break_loc_id)
2659{
2660 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2661 // run so I can stop it if that's what I want to do.
2662 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2663 if (log)
2664 log->Printf("Hit New Thread Notification breakpoint.");
2665 return false;
2666}
2667
2668
2669bool
2670ProcessGDBRemote::StartNoticingNewThreads()
2671{
2672 static const char *bp_names[] =
2673 {
2674 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002675 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002676 "_pthread_start",
2677 NULL
2678 };
2679
2680 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2681 size_t num_bps = m_thread_observation_bps.size();
2682 if (num_bps != 0)
2683 {
2684 for (int i = 0; i < num_bps; i++)
2685 {
2686 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2687 if (break_sp)
2688 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002689 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002690 log->Printf("Enabled noticing new thread breakpoint.");
2691 break_sp->SetEnabled(true);
2692 }
2693 }
2694 }
2695 else
2696 {
2697 for (int i = 0; bp_names[i] != NULL; i++)
2698 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002699 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002700 if (breakpoint)
2701 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002702 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002703 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2704 m_thread_observation_bps.push_back(breakpoint->GetID());
2705 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2706 }
2707 else
2708 {
2709 if (log)
2710 log->Printf("Failed to create new thread notification breakpoint.");
2711 return false;
2712 }
2713 }
2714 }
2715
2716 return true;
2717}
2718
2719bool
2720ProcessGDBRemote::StopNoticingNewThreads()
2721{
Jim Inghamff276fe2011-02-08 05:19:01 +00002722 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002723 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002724 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002725 size_t num_bps = m_thread_observation_bps.size();
2726 if (num_bps != 0)
2727 {
2728 for (int i = 0; i < num_bps; i++)
2729 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002730
2731 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2732 if (break_sp)
2733 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002734 break_sp->SetEnabled(false);
2735 }
2736 }
2737 }
2738 return true;
2739}
2740
2741