blob: 5ac3e0325793a1fa24451e1a18e96dde8074c1ad [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
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner24943d22010-06-08 16:52:24 +000012// C Includes
13#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000015#include <stdlib.h>
Sean Callanan483d00a2012-07-19 18:07:36 +000016#include <netinet/in.h>
Greg Clayton989816b2011-05-14 01:50:35 +000017#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000018#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000019#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000020#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000021
22// C++ Includes
23#include <algorithm>
24#include <map>
25
26// Other libraries and framework includes
27
Johnny Chenecd4feb2011-10-14 00:42:25 +000028#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000029#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/ArchSpec.h"
31#include "lldb/Core/Debugger.h"
32#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000033#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/InputReader.h"
35#include "lldb/Core/Module.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000036#include "lldb/Core/ModuleSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000037#include "lldb/Core/PluginManager.h"
38#include "lldb/Core/State.h"
Greg Clayton33559462012-04-13 21:24:18 +000039#include "lldb/Core/StreamFile.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040#include "lldb/Core/StreamString.h"
41#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000042#include "lldb/Core/Value.h"
Jason Molendab0e3c7c2012-09-29 08:03:33 +000043#include "lldb/Host/Symbols.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Host/TimeValue.h"
Greg Claytonb8596392012-10-15 22:42:16 +000045#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton307c7fd2012-10-19 22:22:57 +000046#include "lldb/Interpreter/CommandObject.h"
47#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Claytonb8596392012-10-15 22:42:16 +000048#include "lldb/Interpreter/CommandReturnObject.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "lldb/Symbol/ObjectFile.h"
50#include "lldb/Target/DynamicLoader.h"
51#include "lldb/Target/Target.h"
52#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000053#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000054#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000055
56// Project includes
57#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000058#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molenda3aeb2862012-07-25 03:40:06 +000059#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham06b84492012-07-04 00:35:43 +000060#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000061#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000062#include "GDBRemoteRegisterContext.h"
63#include "ProcessGDBRemote.h"
64#include "ProcessGDBRemoteLog.h"
65#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000066
Jason Molendab46937c2012-10-03 01:29:34 +000067
Greg Clayton451fa822012-04-09 22:46:21 +000068namespace lldb
69{
70 // Provide a function that can easily dump the packet history if we know a
71 // ProcessGDBRemote * value (which we can get from logs or from debugging).
72 // We need the function in the lldb namespace so it makes it into the final
73 // executable since the LLDB shared library only exports stuff in the lldb
74 // namespace. This allows you to attach with a debugger and call this
75 // function and get the packet history dumped to a file.
76 void
77 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
78 {
Greg Clayton33559462012-04-13 21:24:18 +000079 lldb_private::StreamFile strm;
80 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
81 if (error.Success())
82 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000083 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000084}
Chris Lattner24943d22010-06-08 16:52:24 +000085
Chris Lattner24943d22010-06-08 16:52:24 +000086
87#define DEBUGSERVER_BASENAME "debugserver"
88using namespace lldb;
89using namespace lldb_private;
90
Jim Inghamf9600482011-03-29 21:45:47 +000091static bool rand_initialized = false;
92
Sean Callanan483d00a2012-07-19 18:07:36 +000093// TODO Randomly assigning a port is unsafe. We should get an unused
94// ephemeral port from the kernel and make sure we reserve it before passing
95// it to debugserver.
96
97#if defined (__APPLE__)
98#define LOW_PORT (IPPORT_RESERVED)
99#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
100#else
101#define LOW_PORT (1024u)
102#define HIGH_PORT (49151u)
103#endif
104
Chris Lattner24943d22010-06-08 16:52:24 +0000105static inline uint16_t
106get_random_port ()
107{
Jim Inghamf9600482011-03-29 21:45:47 +0000108 if (!rand_initialized)
109 {
Stephen Wilson60f19d52011-03-30 00:12:40 +0000110 time_t seed = time(NULL);
111
Jim Inghamf9600482011-03-29 21:45:47 +0000112 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +0000113 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +0000114 }
Sean Callanan483d00a2012-07-19 18:07:36 +0000115 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner24943d22010-06-08 16:52:24 +0000116}
117
118
119const char *
120ProcessGDBRemote::GetPluginNameStatic()
121{
Greg Claytonb1888f22011-03-19 01:12:21 +0000122 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000123}
124
125const char *
126ProcessGDBRemote::GetPluginDescriptionStatic()
127{
128 return "GDB Remote protocol based debugging plug-in.";
129}
130
131void
132ProcessGDBRemote::Terminate()
133{
134 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
135}
136
137
Greg Clayton46c9a352012-02-09 06:16:32 +0000138lldb::ProcessSP
139ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000140{
Greg Clayton46c9a352012-02-09 06:16:32 +0000141 lldb::ProcessSP process_sp;
142 if (crash_file_path == NULL)
143 process_sp.reset (new ProcessGDBRemote (target, listener));
144 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000145}
146
147bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000148ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000149{
Greg Clayton61ddf562011-10-21 21:41:45 +0000150 if (plugin_specified_by_name)
151 return true;
152
Chris Lattner24943d22010-06-08 16:52:24 +0000153 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000154 Module *exe_module = target.GetExecutableModulePointer();
155 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000156 {
157 ObjectFile *exe_objfile = exe_module->GetObjectFile();
158 // We can't debug core files...
159 switch (exe_objfile->GetType())
160 {
161 case ObjectFile::eTypeInvalid:
162 case ObjectFile::eTypeCoreFile:
163 case ObjectFile::eTypeDebugInfo:
164 case ObjectFile::eTypeObjectFile:
165 case ObjectFile::eTypeSharedLibrary:
166 case ObjectFile::eTypeStubLibrary:
167 return false;
168 case ObjectFile::eTypeExecutable:
169 case ObjectFile::eTypeDynamicLinker:
170 case ObjectFile::eTypeUnknown:
171 break;
172 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000173 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000174 }
Jim Ingham7508e732010-08-09 23:31:02 +0000175 // However, if there is no executable module, we return true since we might be preparing to attach.
176 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000177}
178
179//----------------------------------------------------------------------
180// ProcessGDBRemote constructor
181//----------------------------------------------------------------------
182ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
183 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000184 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000185 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000186 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000187 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000188 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000189 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000190 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000191 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Inghama9488302012-11-01 01:15:33 +0000192 m_async_thread_state(eAsyncThreadNotStarted),
193 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000194 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000195 m_continue_c_tids (),
196 m_continue_C_tids (),
197 m_continue_s_tids (),
198 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000199 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000200 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000201 m_addr_to_mmap_size (),
202 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000203 m_waiting_for_attach (false),
Jason Molendab46937c2012-10-03 01:29:34 +0000204 m_destroy_tried_resuming (false),
205 m_dyld_plugin_name(),
Greg Clayton13193d52012-10-13 02:07:45 +0000206 m_command_sp ()
Chris Lattner24943d22010-06-08 16:52:24 +0000207{
Greg Claytonff39f742011-04-01 00:29:43 +0000208 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
209 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000210 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000211}
212
213//----------------------------------------------------------------------
214// Destructor
215//----------------------------------------------------------------------
216ProcessGDBRemote::~ProcessGDBRemote()
217{
218 // m_mach_process.UnregisterNotificationCallbacks (this);
219 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000220 // We need to call finalize on the process before destroying ourselves
221 // to make sure all of the broadcaster cleanup goes as planned. If we
222 // destruct this class, then Process::~Process() might have problems
223 // trying to fully destroy the broadcaster.
224 Finalize();
Jim Inghama9488302012-11-01 01:15:33 +0000225
226 // The general Finalize is going to try to destroy the process and that SHOULD
227 // shut down the async thread. However, if we don't kill it it will get stranded and
228 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
229 StopAsyncThread();
230 KillDebugserverProcess();
Chris Lattner24943d22010-06-08 16:52:24 +0000231}
232
233//----------------------------------------------------------------------
234// PluginInterface
235//----------------------------------------------------------------------
236const char *
237ProcessGDBRemote::GetPluginName()
238{
239 return "Process debugging plug-in that uses the GDB remote protocol";
240}
241
242const char *
243ProcessGDBRemote::GetShortPluginName()
244{
245 return GetPluginNameStatic();
246}
247
248uint32_t
249ProcessGDBRemote::GetPluginVersion()
250{
251 return 1;
252}
253
254void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000255ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000256{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000257 if (!force && m_register_info.GetNumRegisters() > 0)
258 return;
259
260 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000261 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000262 uint32_t reg_offset = 0;
263 uint32_t reg_num = 0;
Greg Clayton4a379b12012-07-17 03:23:13 +0000264 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton61d043b2011-03-22 04:00:09 +0000265 response_type == StringExtractorGDBRemote::eResponse;
266 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000267 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000268 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
269 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000270 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000271 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000272 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000273 response_type = response.GetResponseType();
274 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000275 {
276 std::string name;
277 std::string value;
278 ConstString reg_name;
279 ConstString alt_name;
280 ConstString set_name;
Greg Claytonc290ba42013-01-21 22:17:50 +0000281 std::vector<uint32_t> value_regs;
282 std::vector<uint32_t> invalidate_regs;
Chris Lattner24943d22010-06-08 16:52:24 +0000283 RegisterInfo reg_info = { NULL, // Name
284 NULL, // Alt name
285 0, // byte size
286 reg_offset, // offset
287 eEncodingUint, // encoding
288 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000289 {
290 LLDB_INVALID_REGNUM, // GCC reg num
291 LLDB_INVALID_REGNUM, // DWARF reg num
292 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000293 reg_num, // GDB reg num
294 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000295 },
296 NULL,
297 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000298 };
299
300 while (response.GetNameColonValue(name, value))
301 {
302 if (name.compare("name") == 0)
303 {
304 reg_name.SetCString(value.c_str());
305 }
306 else if (name.compare("alt-name") == 0)
307 {
308 alt_name.SetCString(value.c_str());
309 }
310 else if (name.compare("bitsize") == 0)
311 {
312 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
313 }
314 else if (name.compare("offset") == 0)
315 {
316 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000317 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000318 {
319 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000320 }
321 }
322 else if (name.compare("encoding") == 0)
323 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000324 const Encoding encoding = Args::StringToEncoding (value.c_str());
325 if (encoding != eEncodingInvalid)
326 reg_info.encoding = encoding;
Chris Lattner24943d22010-06-08 16:52:24 +0000327 }
328 else if (name.compare("format") == 0)
329 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000330 Format format = eFormatInvalid;
331 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
332 reg_info.format = format;
333 else if (value.compare("binary") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000334 reg_info.format = eFormatBinary;
335 else if (value.compare("decimal") == 0)
336 reg_info.format = eFormatDecimal;
337 else if (value.compare("hex") == 0)
338 reg_info.format = eFormatHex;
339 else if (value.compare("float") == 0)
340 reg_info.format = eFormatFloat;
341 else if (value.compare("vector-sint8") == 0)
342 reg_info.format = eFormatVectorOfSInt8;
343 else if (value.compare("vector-uint8") == 0)
344 reg_info.format = eFormatVectorOfUInt8;
345 else if (value.compare("vector-sint16") == 0)
346 reg_info.format = eFormatVectorOfSInt16;
347 else if (value.compare("vector-uint16") == 0)
348 reg_info.format = eFormatVectorOfUInt16;
349 else if (value.compare("vector-sint32") == 0)
350 reg_info.format = eFormatVectorOfSInt32;
351 else if (value.compare("vector-uint32") == 0)
352 reg_info.format = eFormatVectorOfUInt32;
353 else if (value.compare("vector-float32") == 0)
354 reg_info.format = eFormatVectorOfFloat32;
355 else if (value.compare("vector-uint128") == 0)
356 reg_info.format = eFormatVectorOfUInt128;
357 }
358 else if (name.compare("set") == 0)
359 {
360 set_name.SetCString(value.c_str());
361 }
362 else if (name.compare("gcc") == 0)
363 {
364 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
365 }
366 else if (name.compare("dwarf") == 0)
367 {
368 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
369 }
370 else if (name.compare("generic") == 0)
371 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000372 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000373 }
Greg Claytonc290ba42013-01-21 22:17:50 +0000374 else if (name.compare("container-regs") == 0)
375 {
376 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
377 value_pair.second = value;
378 do
379 {
380 value_pair = value_pair.second.split(',');
381 if (!value_pair.first.empty())
382 {
Greg Clayton679ba162013-01-21 23:32:42 +0000383 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
384 if (reg != LLDB_INVALID_REGNUM)
385 value_regs.push_back (reg);
Greg Claytonc290ba42013-01-21 22:17:50 +0000386 }
387 } while (!value_pair.second.empty());
388 }
389 else if (name.compare("invalidate-regs") == 0)
390 {
391 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
392 value_pair.second = value;
393 do
394 {
395 value_pair = value_pair.second.split(',');
396 if (!value_pair.first.empty())
397 {
Greg Clayton679ba162013-01-21 23:32:42 +0000398 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
399 if (reg != LLDB_INVALID_REGNUM)
400 invalidate_regs.push_back (reg);
Greg Claytonc290ba42013-01-21 22:17:50 +0000401 }
402 } while (!value_pair.second.empty());
403 }
Chris Lattner24943d22010-06-08 16:52:24 +0000404 }
405
Jason Molenda53d96862010-06-11 23:44:18 +0000406 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000407 assert (reg_info.byte_size != 0);
408 reg_offset += reg_info.byte_size;
Greg Claytonc290ba42013-01-21 22:17:50 +0000409 if (!value_regs.empty())
410 {
411 value_regs.push_back(LLDB_INVALID_REGNUM);
412 reg_info.value_regs = value_regs.data();
413 }
414 if (!invalidate_regs.empty())
415 {
416 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
417 reg_info.invalidate_regs = invalidate_regs.data();
418 }
419
Chris Lattner24943d22010-06-08 16:52:24 +0000420 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
421 }
422 }
423 else
424 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000425 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000426 }
427 }
428
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000429 // We didn't get anything if the accumulated reg_num is zero. See if we are
430 // debugging ARM and fill with a hard coded register set until we can get an
431 // updated debugserver down on the devices.
432 // On the other hand, if the accumulated reg_num is positive, see if we can
433 // add composite registers to the existing primordial ones.
434 bool from_scratch = (reg_num == 0);
435
436 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendafe555672012-12-19 02:54:03 +0000437 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
438 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
439
440 // Use the process' architecture instead of the host arch, if available
441 ArchSpec remote_arch;
442 if (remote_process_arch.IsValid ())
443 remote_arch = remote_process_arch;
444 else
445 remote_arch = remote_host_arch;
446
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000447 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000448 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000449 if (remote_arch.IsValid()
450 && remote_arch.GetMachine() == llvm::Triple::arm
451 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
452 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000453 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000454 else if (target_arch.GetMachine() == llvm::Triple::arm)
455 {
456 m_register_info.HardcodeARMRegisters(from_scratch);
457 }
458
459 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000460 m_register_info.Finalize ();
461}
462
463Error
464ProcessGDBRemote::WillLaunch (Module* module)
465{
466 return WillLaunchOrAttach ();
467}
468
469Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000470ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000471{
472 return WillLaunchOrAttach ();
473}
474
475Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000476ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000477{
478 return WillLaunchOrAttach ();
479}
480
481Error
Jason Molendafac2e622012-09-29 04:02:01 +0000482ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +0000483{
484 Error error (WillLaunchOrAttach ());
485
486 if (error.Fail())
487 return error;
488
Greg Clayton180546b2011-04-30 01:09:13 +0000489 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000490
491 if (error.Fail())
492 return error;
493 StartAsyncThread ();
494
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000495 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000496 if (pid == LLDB_INVALID_PROCESS_ID)
497 {
498 // We don't have a valid process ID, so note that we are connected
499 // and could now request to launch or attach, or get remote process
500 // listings...
501 SetPrivateState (eStateConnected);
502 }
503 else
504 {
505 // We have a valid process
506 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000507 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000508 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000509 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000510 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000511 if (state == eStateStopped)
512 {
513 SetPrivateState (state);
514 }
515 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000516 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytone71e2582011-02-04 01:58:07 +0000517 }
518 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000519 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000520 }
Jason Molendacb740b32012-05-03 22:37:30 +0000521
522 if (error.Success()
523 && !GetTarget().GetArchitecture().IsValid()
524 && m_gdb_comm.GetHostArchitecture().IsValid())
525 {
Jason Molendafe555672012-12-19 02:54:03 +0000526 // Prefer the *process'* architecture over that of the *host*, if available.
527 if (m_gdb_comm.GetProcessArchitecture().IsValid())
528 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
529 else
530 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendacb740b32012-05-03 22:37:30 +0000531 }
532
Greg Claytone71e2582011-02-04 01:58:07 +0000533 return error;
534}
535
536Error
Chris Lattner24943d22010-06-08 16:52:24 +0000537ProcessGDBRemote::WillLaunchOrAttach ()
538{
539 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000540 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000541 return error;
542}
543
544//----------------------------------------------------------------------
545// Process Control
546//----------------------------------------------------------------------
547Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000548ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000549{
Greg Clayton4b407112010-09-30 21:49:03 +0000550 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000551
552 uint32_t launch_flags = launch_info.GetFlags().Get();
553 const char *stdin_path = NULL;
554 const char *stdout_path = NULL;
555 const char *stderr_path = NULL;
556 const char *working_dir = launch_info.GetWorkingDirectory();
557
558 const ProcessLaunchInfo::FileAction *file_action;
559 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
560 if (file_action)
561 {
562 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
563 stdin_path = file_action->GetPath();
564 }
565 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
566 if (file_action)
567 {
568 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
569 stdout_path = file_action->GetPath();
570 }
571 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
572 if (file_action)
573 {
574 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
575 stderr_path = file_action->GetPath();
576 }
577
Chris Lattner24943d22010-06-08 16:52:24 +0000578 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
579 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
580 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000581 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000582
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000583 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000584 if (object_file)
585 {
Chris Lattner24943d22010-06-08 16:52:24 +0000586 char host_port[128];
587 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000588 char connect_url[128];
589 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000590
Greg Claytona2f74232011-02-24 22:24:29 +0000591 // Make sure we aren't already connected?
592 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000593 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000594 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000595 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000596 {
Johnny Chenc143d622011-08-09 18:56:45 +0000597 if (log)
598 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000599 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000600 }
Chris Lattner24943d22010-06-08 16:52:24 +0000601
Greg Claytone71e2582011-02-04 01:58:07 +0000602 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000603 }
604
605 if (error.Success())
606 {
607 lldb_utility::PseudoTerminal pty;
608 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000609
610 // If the debugserver is local and we aren't disabling STDIO, lets use
611 // a pseudo terminal to instead of relying on the 'O' packets for stdio
612 // since 'O' packets can really slow down debugging if the inferior
613 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000614 PlatformSP platform_sp (m_target.GetPlatform());
615 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000616 {
617 const char *slave_name = NULL;
618 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000619 {
Greg Claytona2f74232011-02-24 22:24:29 +0000620 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
621 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000622 }
Greg Claytona2f74232011-02-24 22:24:29 +0000623 if (stdin_path == NULL)
624 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000625
Greg Claytona2f74232011-02-24 22:24:29 +0000626 if (stdout_path == NULL)
627 stdout_path = slave_name;
628
629 if (stderr_path == NULL)
630 stderr_path = slave_name;
631 }
632
Greg Claytonafb81862011-03-02 21:34:46 +0000633 // Set STDIN to /dev/null if we want STDIO disabled or if either
634 // STDOUT or STDERR have been set to something and STDIN hasn't
635 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000636 stdin_path = "/dev/null";
637
Greg Claytonafb81862011-03-02 21:34:46 +0000638 // Set STDOUT to /dev/null if we want STDIO disabled or if either
639 // STDIN or STDERR have been set to something and STDOUT hasn't
640 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000641 stdout_path = "/dev/null";
642
Greg Claytonafb81862011-03-02 21:34:46 +0000643 // Set STDERR to /dev/null if we want STDIO disabled or if either
644 // STDIN or STDOUT have been set to something and STDERR hasn't
645 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000646 stderr_path = "/dev/null";
647
648 if (stdin_path)
649 m_gdb_comm.SetSTDIN (stdin_path);
650 if (stdout_path)
651 m_gdb_comm.SetSTDOUT (stdout_path);
652 if (stderr_path)
653 m_gdb_comm.SetSTDERR (stderr_path);
654
655 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
656
Greg Claytona4582402011-05-08 04:53:50 +0000657 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000658
659 if (working_dir && working_dir[0])
660 {
661 m_gdb_comm.SetWorkingDir (working_dir);
662 }
663
664 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000665 const Args &environment = launch_info.GetEnvironmentEntries();
666 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000667 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000668 size_t num_environment_entries = environment.GetArgumentCount();
669 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000670 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000671 const char *env_entry = environment.GetArgumentAtIndex(i);
672 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000673 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000674 }
Greg Claytona2f74232011-02-24 22:24:29 +0000675 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000676
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000677 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000678 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000679 if (arg_packet_err == 0)
680 {
681 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000682 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000683 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000684 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000685 }
686 else
687 {
Greg Claytona2f74232011-02-24 22:24:29 +0000688 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000689 }
Greg Claytona2f74232011-02-24 22:24:29 +0000690 }
691 else
692 {
Greg Clayton9c236732011-10-26 00:56:27 +0000693 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000694 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000695
696 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000697
Greg Claytona2f74232011-02-24 22:24:29 +0000698 if (GetID() == LLDB_INVALID_PROCESS_ID)
699 {
Johnny Chenc143d622011-08-09 18:56:45 +0000700 if (log)
701 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000702 KillDebugserverProcess ();
703 return error;
704 }
705
Greg Clayton261a18b2011-06-02 22:22:38 +0000706 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000707 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000708 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000709
710 if (!disable_stdio)
711 {
712 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000713 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000714 }
Chris Lattner24943d22010-06-08 16:52:24 +0000715 }
716 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000717 else
718 {
Johnny Chenc143d622011-08-09 18:56:45 +0000719 if (log)
720 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000721 }
Chris Lattner24943d22010-06-08 16:52:24 +0000722 }
723 else
724 {
725 // Set our user ID to an invalid process ID.
726 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000727 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
728 exe_module->GetFileSpec().GetFilename().AsCString(),
729 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000730 }
Chris Lattner24943d22010-06-08 16:52:24 +0000731 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000732
Chris Lattner24943d22010-06-08 16:52:24 +0000733}
734
735
736Error
Greg Claytone71e2582011-02-04 01:58:07 +0000737ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000738{
739 Error error;
740 // Sleep and wait a bit for debugserver to start to listen...
741 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
742 if (conn_ap.get())
743 {
Chris Lattner24943d22010-06-08 16:52:24 +0000744 const uint32_t max_retry_count = 50;
745 uint32_t retry_count = 0;
746 while (!m_gdb_comm.IsConnected())
747 {
Greg Claytone71e2582011-02-04 01:58:07 +0000748 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000749 {
750 m_gdb_comm.SetConnection (conn_ap.release());
751 break;
752 }
753 retry_count++;
754
755 if (retry_count >= max_retry_count)
756 break;
757
758 usleep (100000);
759 }
760 }
761
762 if (!m_gdb_comm.IsConnected())
763 {
764 if (error.Success())
765 error.SetErrorString("not connected to remote gdb server");
766 return error;
767 }
768
Greg Clayton24bc5d92011-03-30 18:16:51 +0000769 // We always seem to be able to open a connection to a local port
770 // so we need to make sure we can then send data to it. If we can't
771 // then we aren't actually connected to anything, so try and do the
772 // handshake with the remote GDB server and make sure that goes
773 // alright.
774 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000775 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000776 m_gdb_comm.Disconnect();
777 if (error.Success())
778 error.SetErrorString("not connected to remote gdb server");
779 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000780 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000781 m_gdb_comm.ResetDiscoverableSettings();
782 m_gdb_comm.QueryNoAckModeSupported ();
783 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000784 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000785 m_gdb_comm.GetHostInfo ();
786 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000787 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000788
789 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
790 for (size_t idx = 0; idx < num_cmds; idx++)
791 {
792 StringExtractorGDBRemote response;
Jim Ingham86827fb2012-07-02 05:40:07 +0000793 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
794 }
Chris Lattner24943d22010-06-08 16:52:24 +0000795 return error;
796}
797
798void
799ProcessGDBRemote::DidLaunchOrAttach ()
800{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000801 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
802 if (log)
803 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000804 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000805 {
806 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
807
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000808 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000809
Chris Lattner24943d22010-06-08 16:52:24 +0000810 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000811
Jason Molendafe555672012-12-19 02:54:03 +0000812 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
813
814 // See if the GDB server supports the qProcessInfo packet, if so
815 // prefer that over the Host information as it will be more specific
816 // to our process.
817
818 if (m_gdb_comm.GetProcessArchitecture().IsValid())
819 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
820
Greg Claytoncb8977d2011-03-23 00:09:55 +0000821 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000822 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000823 ArchSpec &target_arch = GetTarget().GetArchitecture();
824
825 if (target_arch.IsValid())
826 {
827 // If the remote host is ARM and we have apple as the vendor, then
828 // ARM executables and shared libraries can have mixed ARM architectures.
829 // You can have an armv6 executable, and if the host is armv7, then the
830 // system will load the best possible architecture for all shared libraries
831 // it has, so we really need to take the remote host architecture as our
832 // defacto architecture in this case.
833
834 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
835 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
836 {
837 target_arch = gdb_remote_arch;
838 }
839 else
840 {
841 // Fill in what is missing in the triple
842 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
843 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000844 if (target_triple.getVendorName().size() == 0)
845 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000846 target_triple.setVendor (remote_triple.getVendor());
847
Greg Clayton2f085c62011-05-15 01:25:55 +0000848 if (target_triple.getOSName().size() == 0)
849 {
850 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000851
Greg Clayton2f085c62011-05-15 01:25:55 +0000852 if (target_triple.getEnvironmentName().size() == 0)
853 target_triple.setEnvironment (remote_triple.getEnvironment());
854 }
855 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000856 }
857 }
858 else
859 {
860 // The target doesn't have a valid architecture yet, set it from
861 // the architecture we got from the remote GDB server
862 target_arch = gdb_remote_arch;
863 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000864 }
Chris Lattner24943d22010-06-08 16:52:24 +0000865 }
866}
867
868void
869ProcessGDBRemote::DidLaunch ()
870{
871 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000872}
873
874Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000875ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000876{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000877 ProcessAttachInfo attach_info;
878 return DoAttachToProcessWithID(attach_pid, attach_info);
879}
880
881Error
882ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
883{
Chris Lattner24943d22010-06-08 16:52:24 +0000884 Error error;
885 // Clear out and clean up from any current state
886 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000887 if (attach_pid != LLDB_INVALID_PROCESS_ID)
888 {
Greg Claytona2f74232011-02-24 22:24:29 +0000889 // Make sure we aren't already connected?
890 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000891 {
Greg Claytona2f74232011-02-24 22:24:29 +0000892 char host_port[128];
893 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
894 char connect_url[128];
895 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000896
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000897 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000898
899 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000900 {
Greg Claytona2f74232011-02-24 22:24:29 +0000901 const char *error_string = error.AsCString();
902 if (error_string == NULL)
903 error_string = "unable to launch " DEBUGSERVER_BASENAME;
904
905 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000906 }
Greg Claytona2f74232011-02-24 22:24:29 +0000907 else
908 {
909 error = ConnectToDebugserver (connect_url);
910 }
911 }
912
913 if (error.Success())
914 {
915 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000916 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000917 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000918 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000919 }
920 }
Chris Lattner24943d22010-06-08 16:52:24 +0000921 return error;
922}
923
924size_t
925ProcessGDBRemote::AttachInputReaderCallback
926(
927 void *baton,
928 InputReader *reader,
929 lldb::InputReaderAction notification,
930 const char *bytes,
931 size_t bytes_len
932)
933{
934 if (notification == eInputReaderGotToken)
935 {
936 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
937 if (gdb_process->m_waiting_for_attach)
938 gdb_process->m_waiting_for_attach = false;
939 reader->SetIsDone(true);
940 return 1;
941 }
942 return 0;
943}
944
945Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000946ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000947{
948 Error error;
949 // Clear out and clean up from any current state
950 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000951
Chris Lattner24943d22010-06-08 16:52:24 +0000952 if (process_name && process_name[0])
953 {
Greg Claytona2f74232011-02-24 22:24:29 +0000954 // Make sure we aren't already connected?
955 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000956 {
Greg Claytona2f74232011-02-24 22:24:29 +0000957 char host_port[128];
958 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
959 char connect_url[128];
960 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
961
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000962 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000963 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000964 {
Greg Claytona2f74232011-02-24 22:24:29 +0000965 const char *error_string = error.AsCString();
966 if (error_string == NULL)
967 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000968
Greg Claytona2f74232011-02-24 22:24:29 +0000969 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000970 }
Greg Claytona2f74232011-02-24 22:24:29 +0000971 else
972 {
973 error = ConnectToDebugserver (connect_url);
974 }
975 }
976
977 if (error.Success())
978 {
979 StreamString packet;
980
981 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +0000982 {
983 if (!m_gdb_comm.GetVAttachOrWaitSupported())
984 {
985 packet.PutCString ("vAttachWait");
986 }
987 else
988 {
989 if (attach_info.GetIgnoreExisting())
990 packet.PutCString("vAttachWait");
991 else
992 packet.PutCString ("vAttachOrWait");
993 }
994 }
Greg Claytona2f74232011-02-24 22:24:29 +0000995 else
996 packet.PutCString("vAttachName");
997 packet.PutChar(';');
998 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
999
1000 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1001
Chris Lattner24943d22010-06-08 16:52:24 +00001002 }
1003 }
Chris Lattner24943d22010-06-08 16:52:24 +00001004 return error;
1005}
1006
Chris Lattner24943d22010-06-08 16:52:24 +00001007
1008void
1009ProcessGDBRemote::DidAttach ()
1010{
Greg Claytone71e2582011-02-04 01:58:07 +00001011 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +00001012}
1013
Greg Clayton0bce9a22012-12-05 00:16:59 +00001014void
1015ProcessGDBRemote::DoDidExec ()
1016{
1017 // The process exec'ed itself, figure out the dynamic loader, etc...
1018 BuildDynamicRegisterInfo (true);
1019 m_gdb_comm.ResetDiscoverableSettings();
1020 DidLaunchOrAttach ();
1021}
1022
1023
1024
Chris Lattner24943d22010-06-08 16:52:24 +00001025Error
1026ProcessGDBRemote::WillResume ()
1027{
Greg Claytonc1f45872011-02-12 06:28:37 +00001028 m_continue_c_tids.clear();
1029 m_continue_C_tids.clear();
1030 m_continue_s_tids.clear();
1031 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001032 return Error();
1033}
1034
1035Error
1036ProcessGDBRemote::DoResume ()
1037{
Jim Ingham3ae449a2010-11-17 02:32:00 +00001038 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001039 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1040 if (log)
1041 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +00001042
1043 Listener listener ("gdb-remote.resume-packet-sent");
1044 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1045 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001046 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1047
Greg Claytonc1f45872011-02-12 06:28:37 +00001048 StreamString continue_packet;
1049 bool continue_packet_error = false;
1050 if (m_gdb_comm.HasAnyVContSupport ())
1051 {
1052 continue_packet.PutCString ("vCont");
1053
1054 if (!m_continue_c_tids.empty())
1055 {
1056 if (m_gdb_comm.GetVContSupported ('c'))
1057 {
1058 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)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001059 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001060 }
1061 else
1062 continue_packet_error = true;
1063 }
1064
1065 if (!continue_packet_error && !m_continue_C_tids.empty())
1066 {
1067 if (m_gdb_comm.GetVContSupported ('C'))
1068 {
1069 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)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001070 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001071 }
1072 else
1073 continue_packet_error = true;
1074 }
Greg Claytonb749a262010-12-03 06:02:24 +00001075
Greg Claytonc1f45872011-02-12 06:28:37 +00001076 if (!continue_packet_error && !m_continue_s_tids.empty())
1077 {
1078 if (m_gdb_comm.GetVContSupported ('s'))
1079 {
1080 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)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001081 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001082 }
1083 else
1084 continue_packet_error = true;
1085 }
1086
1087 if (!continue_packet_error && !m_continue_S_tids.empty())
1088 {
1089 if (m_gdb_comm.GetVContSupported ('S'))
1090 {
1091 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)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001092 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001093 }
1094 else
1095 continue_packet_error = true;
1096 }
1097
1098 if (continue_packet_error)
1099 continue_packet.GetString().clear();
1100 }
1101 else
1102 continue_packet_error = true;
1103
1104 if (continue_packet_error)
1105 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001106 // Either no vCont support, or we tried to use part of the vCont
1107 // packet that wasn't supported by the remote GDB server.
1108 // We need to try and make a simple packet that can do our continue
1109 const size_t num_threads = GetThreadList().GetSize();
1110 const size_t num_continue_c_tids = m_continue_c_tids.size();
1111 const size_t num_continue_C_tids = m_continue_C_tids.size();
1112 const size_t num_continue_s_tids = m_continue_s_tids.size();
1113 const size_t num_continue_S_tids = m_continue_S_tids.size();
1114 if (num_continue_c_tids > 0)
1115 {
1116 if (num_continue_c_tids == num_threads)
1117 {
1118 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001119 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001120 continue_packet.PutChar ('c');
1121 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001122 }
1123 else if (num_continue_c_tids == 1 &&
1124 num_continue_C_tids == 0 &&
1125 num_continue_s_tids == 0 &&
1126 num_continue_S_tids == 0 )
1127 {
1128 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001129 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001130 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001131 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001132 }
1133 }
1134
Greg Claytonde1dd812011-06-24 03:21:43 +00001135 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001136 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001137 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1138 num_continue_C_tids > 0 &&
1139 num_continue_s_tids == 0 &&
1140 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001141 {
1142 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001143 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001144 if (num_continue_C_tids > 1)
1145 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001146 // More that one thread with a signal, yet we don't have
1147 // vCont support and we are being asked to resume each
1148 // thread with a signal, we need to make sure they are
1149 // all the same signal, or we can't issue the continue
1150 // accurately with the current support...
1151 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001152 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001153 continue_packet_error = false;
1154 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1155 {
1156 if (m_continue_C_tids[i].second != continue_signo)
1157 continue_packet_error = true;
1158 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001159 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001160 if (!continue_packet_error)
1161 m_gdb_comm.SetCurrentThreadForRun (-1);
1162 }
1163 else
1164 {
1165 // Set the continue thread ID
1166 continue_packet_error = false;
1167 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001168 }
1169 if (!continue_packet_error)
1170 {
1171 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001172 continue_packet.Printf("C%2.2x", continue_signo);
1173 }
1174 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001175 }
1176
Greg Claytonde1dd812011-06-24 03:21:43 +00001177 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001178 {
1179 if (num_continue_s_tids == num_threads)
1180 {
1181 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001182 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001183 continue_packet.PutChar ('s');
1184 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001185 }
1186 else if (num_continue_c_tids == 0 &&
1187 num_continue_C_tids == 0 &&
1188 num_continue_s_tids == 1 &&
1189 num_continue_S_tids == 0 )
1190 {
1191 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001192 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001193 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001194 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001195 }
1196 }
1197
1198 if (!continue_packet_error && num_continue_S_tids > 0)
1199 {
1200 if (num_continue_S_tids == num_threads)
1201 {
1202 const int step_signo = m_continue_S_tids.front().second;
1203 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001204 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001205 if (num_continue_S_tids > 1)
1206 {
1207 for (size_t i=1; i<num_threads; ++i)
1208 {
1209 if (m_continue_S_tids[i].second != step_signo)
1210 continue_packet_error = true;
1211 }
1212 }
1213 if (!continue_packet_error)
1214 {
1215 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001216 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001217 continue_packet.Printf("S%2.2x", step_signo);
1218 }
1219 }
1220 else if (num_continue_c_tids == 0 &&
1221 num_continue_C_tids == 0 &&
1222 num_continue_s_tids == 0 &&
1223 num_continue_S_tids == 1 )
1224 {
1225 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001226 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001227 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001228 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001229 }
1230 }
1231 }
1232
1233 if (continue_packet_error)
1234 {
1235 error.SetErrorString ("can't make continue packet for this resume");
1236 }
1237 else
1238 {
1239 EventSP event_sp;
1240 TimeValue timeout;
1241 timeout = TimeValue::Now();
1242 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001243 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1244 {
1245 error.SetErrorString ("Trying to resume but the async thread is dead.");
1246 if (log)
1247 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1248 return error;
1249 }
1250
Greg Claytonc1f45872011-02-12 06:28:37 +00001251 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1252
1253 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001254 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001255 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001256 if (log)
1257 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1258 }
1259 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1260 {
1261 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1262 if (log)
1263 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1264 return error;
1265 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001266 }
Greg Claytonb749a262010-12-03 06:02:24 +00001267 }
1268
Jim Ingham3ae449a2010-11-17 02:32:00 +00001269 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001270}
1271
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001272void
1273ProcessGDBRemote::ClearThreadIDList ()
1274{
Greg Claytonff3448e2012-04-13 02:11:32 +00001275 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001276 m_thread_ids.clear();
1277}
1278
1279bool
1280ProcessGDBRemote::UpdateThreadIDList ()
1281{
Greg Claytonff3448e2012-04-13 02:11:32 +00001282 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001283 bool sequence_mutex_unavailable = false;
1284 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1285 if (sequence_mutex_unavailable)
1286 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001287 return false; // We just didn't get the list
1288 }
1289 return true;
1290}
1291
Greg Claytonae932352012-04-10 00:18:59 +00001292bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001293ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001294{
1295 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001296 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001297 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001298 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001299
1300 size_t num_thread_ids = m_thread_ids.size();
1301 // The "m_thread_ids" thread ID list should always be updated after each stop
1302 // reply packet, but in case it isn't, update it here.
1303 if (num_thread_ids == 0)
1304 {
1305 if (!UpdateThreadIDList ())
1306 return false;
1307 num_thread_ids = m_thread_ids.size();
1308 }
Chris Lattner24943d22010-06-08 16:52:24 +00001309
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001310 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton37f962e2011-08-22 02:49:39 +00001311 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001312 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001313 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001314 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001315 tid_t tid = m_thread_ids[i];
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001316 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByID (tid, false));
Greg Clayton37f962e2011-08-22 02:49:39 +00001317 if (!thread_sp)
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001318 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001319 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001320 }
Chris Lattner24943d22010-06-08 16:52:24 +00001321 }
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001322
1323 // Whatever that is left in old_thread_list_copy are not
1324 // present in new_thread_list. Remove non-existent threads from internal id table.
1325 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1326 for (size_t i=0; i<old_num_thread_ids; i++)
1327 {
1328 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1329 if (old_thread_sp)
1330 {
1331 lldb::tid_t old_thread_id = old_thread_sp->GetID();
1332 m_thread_id_to_index_id_map.erase(old_thread_id);
1333 }
1334 }
1335
Greg Claytonae932352012-04-10 00:18:59 +00001336 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001337}
1338
1339
1340StateType
1341ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1342{
Greg Clayton261a18b2011-06-02 22:22:38 +00001343 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001344 const char stop_type = stop_packet.GetChar();
1345 switch (stop_type)
1346 {
1347 case 'T':
1348 case 'S':
1349 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001350 if (GetStopID() == 0)
1351 {
1352 // Our first stop, make sure we have a process ID, and also make
1353 // sure we know about our registers
1354 if (GetID() == LLDB_INVALID_PROCESS_ID)
1355 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001356 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001357 if (pid != LLDB_INVALID_PROCESS_ID)
1358 SetID (pid);
1359 }
1360 BuildDynamicRegisterInfo (true);
1361 }
Chris Lattner24943d22010-06-08 16:52:24 +00001362 // Stop with signal and thread info
1363 const uint8_t signo = stop_packet.GetHexU8();
1364 std::string name;
1365 std::string value;
1366 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001367 std::string reason;
1368 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001369 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001370 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001371 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001372 ThreadSP thread_sp;
1373
Chris Lattner24943d22010-06-08 16:52:24 +00001374 while (stop_packet.GetNameColonValue(name, value))
1375 {
1376 if (name.compare("metype") == 0)
1377 {
1378 // exception type in big endian hex
1379 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1380 }
Chris Lattner24943d22010-06-08 16:52:24 +00001381 else if (name.compare("medata") == 0)
1382 {
1383 // exception data in big endian hex
1384 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1385 }
1386 else if (name.compare("thread") == 0)
1387 {
1388 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001389 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001390 // m_thread_list does have its own mutex, but we need to
1391 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1392 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001393 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001394 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001395 if (!thread_sp)
1396 {
1397 // Create the thread if we need to
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001398 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001399 m_thread_list.AddThread(thread_sp);
1400 }
Chris Lattner24943d22010-06-08 16:52:24 +00001401 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001402 else if (name.compare("threads") == 0)
1403 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001404 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001405 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001406 // A comma separated list of all threads in the current
1407 // process that includes the thread for this stop reply
1408 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001409 size_t comma_pos;
1410 lldb::tid_t tid;
1411 while ((comma_pos = value.find(',')) != std::string::npos)
1412 {
1413 value[comma_pos] = '\0';
1414 // thread in big endian hex
1415 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1416 if (tid != LLDB_INVALID_THREAD_ID)
1417 m_thread_ids.push_back (tid);
1418 value.erase(0, comma_pos + 1);
1419
1420 }
1421 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1422 if (tid != LLDB_INVALID_THREAD_ID)
1423 m_thread_ids.push_back (tid);
1424 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001425 else if (name.compare("hexname") == 0)
1426 {
1427 StringExtractor name_extractor;
1428 // Swap "value" over into "name_extractor"
1429 name_extractor.GetStringRef().swap(value);
1430 // Now convert the HEX bytes into a string value
1431 name_extractor.GetHexByteString (value);
1432 thread_name.swap (value);
1433 }
Chris Lattner24943d22010-06-08 16:52:24 +00001434 else if (name.compare("name") == 0)
1435 {
1436 thread_name.swap (value);
1437 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001438 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001439 {
1440 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1441 }
Greg Clayton65611552011-06-04 01:26:29 +00001442 else if (name.compare("reason") == 0)
1443 {
1444 reason.swap(value);
1445 }
1446 else if (name.compare("description") == 0)
1447 {
1448 StringExtractor desc_extractor;
1449 // Swap "value" over into "name_extractor"
1450 desc_extractor.GetStringRef().swap(value);
1451 // Now convert the HEX bytes into a string value
1452 desc_extractor.GetHexByteString (thread_name);
1453 }
Greg Claytona875b642011-01-09 21:07:35 +00001454 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1455 {
1456 // We have a register number that contains an expedited
1457 // register value. Lets supply this register to our thread
1458 // so it won't have to go and read it.
1459 if (thread_sp)
1460 {
1461 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1462
1463 if (reg != UINT32_MAX)
1464 {
1465 StringExtractor reg_value_extractor;
1466 // Swap "value" over into "reg_value_extractor"
1467 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001468 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1469 {
1470 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1471 name.c_str(),
1472 reg,
1473 reg,
1474 reg_value_extractor.GetStringRef().c_str(),
1475 stop_packet.GetStringRef().c_str());
1476 }
Greg Claytona875b642011-01-09 21:07:35 +00001477 }
1478 }
1479 }
Chris Lattner24943d22010-06-08 16:52:24 +00001480 }
Chris Lattner24943d22010-06-08 16:52:24 +00001481
1482 if (thread_sp)
1483 {
1484 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1485
1486 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001487 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001488 if (exc_type != 0)
1489 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001490 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001491
1492 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1493 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001494 exc_data_size,
1495 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001496 exc_data_size >= 2 ? exc_data[1] : 0,
1497 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001498 }
Greg Clayton65611552011-06-04 01:26:29 +00001499 else
Chris Lattner24943d22010-06-08 16:52:24 +00001500 {
Greg Clayton65611552011-06-04 01:26:29 +00001501 bool handled = false;
1502 if (!reason.empty())
1503 {
1504 if (reason.compare("trace") == 0)
1505 {
1506 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1507 handled = true;
1508 }
1509 else if (reason.compare("breakpoint") == 0)
1510 {
1511 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001512 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001513 if (bp_site_sp)
1514 {
1515 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1516 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1517 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001518 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001519 if (bp_site_sp->ValidForThisThread (gdb_thread))
1520 {
1521 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001522 }
1523 else
1524 {
1525 StopInfoSP invalid_stop_info_sp;
1526 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001527 }
1528 }
1529
Greg Clayton65611552011-06-04 01:26:29 +00001530 }
1531 else if (reason.compare("trap") == 0)
1532 {
1533 // Let the trap just use the standard signal stop reason below...
1534 }
1535 else if (reason.compare("watchpoint") == 0)
1536 {
1537 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1538 // TODO: locate the watchpoint somehow...
1539 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1540 handled = true;
1541 }
1542 else if (reason.compare("exception") == 0)
1543 {
1544 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1545 handled = true;
1546 }
1547 }
1548
1549 if (signo)
1550 {
1551 if (signo == SIGTRAP)
1552 {
1553 // Currently we are going to assume SIGTRAP means we are either
1554 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001555 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001556 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001557 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001558
Greg Clayton65611552011-06-04 01:26:29 +00001559 if (bp_site_sp)
1560 {
1561 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1562 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1563 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1564 if (bp_site_sp->ValidForThisThread (gdb_thread))
1565 {
1566 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001567 }
1568 else
1569 {
1570 StopInfoSP invalid_stop_info_sp;
1571 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001572 }
1573 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001574 else
Greg Clayton65611552011-06-04 01:26:29 +00001575 {
Jim Ingham4fa015b2012-10-27 02:52:04 +00001576 // If we were stepping then assume the stop was the result of the trace. If we were
1577 // not stepping then report the SIGTRAP.
1578 // FIXME: We are still missing the case where we single step over a trap instruction.
1579 if (gdb_thread->GetTemporaryResumeState() == eStateStepping)
1580 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1581 else
1582 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Clayton65611552011-06-04 01:26:29 +00001583 }
1584 }
1585 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001586 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001587 }
1588 else
1589 {
Greg Clayton643ee732010-08-04 01:40:35 +00001590 StopInfoSP invalid_stop_info_sp;
1591 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001592 }
Greg Clayton65611552011-06-04 01:26:29 +00001593
1594 if (!description.empty())
1595 {
1596 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1597 if (stop_info_sp)
1598 {
1599 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001600 }
Greg Clayton65611552011-06-04 01:26:29 +00001601 else
1602 {
1603 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1604 }
1605 }
1606 }
Chris Lattner24943d22010-06-08 16:52:24 +00001607 }
1608 return eStateStopped;
1609 }
1610 break;
1611
1612 case 'W':
1613 // process exited
1614 return eStateExited;
1615
1616 default:
1617 break;
1618 }
1619 return eStateInvalid;
1620}
1621
1622void
1623ProcessGDBRemote::RefreshStateAfterStop ()
1624{
Greg Claytonff3448e2012-04-13 02:11:32 +00001625 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001626 m_thread_ids.clear();
1627 // Set the thread stop info. It might have a "threads" key whose value is
1628 // a list of all thread IDs in the current process, so m_thread_ids might
1629 // get set.
1630 SetThreadStopInfo (m_last_stop_packet);
1631 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1632 if (m_thread_ids.empty())
1633 {
1634 // No, we need to fetch the thread list manually
1635 UpdateThreadIDList();
1636 }
1637
Chris Lattner24943d22010-06-08 16:52:24 +00001638 // Let all threads recover from stopping and do any clean up based
1639 // on the previous thread state (if any).
1640 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001641
Chris Lattner24943d22010-06-08 16:52:24 +00001642}
1643
1644Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001645ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001646{
1647 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001648
Greg Claytona4881d02011-01-22 07:12:45 +00001649 bool timed_out = false;
1650 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001651
1652 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001653 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001654 // We are being asked to halt during an attach. We need to just close
1655 // our file handle and debugserver will go away, and we can be done...
1656 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001657 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001658 else
1659 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001660 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001661 {
1662 if (timed_out)
1663 error.SetErrorString("timed out sending interrupt packet");
1664 else
1665 error.SetErrorString("unknown error sending interrupt packet");
1666 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001667
1668 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001669 }
Chris Lattner24943d22010-06-08 16:52:24 +00001670 return error;
1671}
1672
1673Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001674ProcessGDBRemote::InterruptIfRunning
1675(
1676 bool discard_thread_plans,
1677 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001678 EventSP &stop_event_sp
1679)
Chris Lattner24943d22010-06-08 16:52:24 +00001680{
1681 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001682
Greg Clayton2860ba92011-01-23 19:58:49 +00001683 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1684
Greg Clayton68ca8232011-01-25 02:58:48 +00001685 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001686 const bool is_running = m_gdb_comm.IsRunning();
1687 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001688 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001689 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001690 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001691 is_running);
1692
Greg Clayton2860ba92011-01-23 19:58:49 +00001693 if (discard_thread_plans)
1694 {
1695 if (log)
1696 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1697 m_thread_list.DiscardThreadPlans();
1698 }
1699 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001700 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001701 if (catch_stop_event)
1702 {
1703 if (log)
1704 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1705 PausePrivateStateThread();
1706 paused_private_state_thread = true;
1707 }
1708
Greg Clayton4fb400f2010-09-27 21:07:38 +00001709 bool timed_out = false;
1710 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001711
Greg Clayton05e4d972012-03-29 01:55:41 +00001712 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001713 {
1714 if (timed_out)
1715 error.SetErrorString("timed out sending interrupt packet");
1716 else
1717 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001718 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001719 ResumePrivateStateThread();
1720 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001721 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001722
Greg Clayton72e1c782011-01-22 23:43:18 +00001723 if (catch_stop_event)
1724 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001725 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001726 TimeValue timeout_time;
1727 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001728 timeout_time.OffsetWithSeconds(5);
1729 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001730
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001731 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001732 if (log)
1733 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001734
Greg Clayton2860ba92011-01-23 19:58:49 +00001735 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001736 error.SetErrorString("unable to verify target stopped");
1737 }
1738
Greg Clayton68ca8232011-01-25 02:58:48 +00001739 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001740 {
1741 if (log)
1742 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001743 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001744 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001745 }
Chris Lattner24943d22010-06-08 16:52:24 +00001746 return error;
1747}
1748
Greg Clayton4fb400f2010-09-27 21:07:38 +00001749Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001750ProcessGDBRemote::WillDetach ()
1751{
Greg Clayton2860ba92011-01-23 19:58:49 +00001752 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1753 if (log)
1754 log->Printf ("ProcessGDBRemote::WillDetach()");
1755
Greg Clayton72e1c782011-01-22 23:43:18 +00001756 bool discard_thread_plans = true;
1757 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001758 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001759
1760 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1761 // needed. This shouldn't be a feature of a particular plugin.
1762
Greg Clayton68ca8232011-01-25 02:58:48 +00001763 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001764}
1765
1766Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001767ProcessGDBRemote::DoDetach()
1768{
1769 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001770 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001771 if (log)
1772 log->Printf ("ProcessGDBRemote::DoDetach()");
1773
1774 DisableAllBreakpointSites ();
1775
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001776 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001777
Greg Clayton516f0842012-04-11 00:24:49 +00001778 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001779 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001780 {
Greg Clayton516f0842012-04-11 00:24:49 +00001781 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001782 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1783 else
1784 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001785 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001786 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001787 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001788
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001789 SetPrivateState (eStateDetached);
1790 ResumePrivateStateThread();
1791
1792 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001793 return error;
1794}
Chris Lattner24943d22010-06-08 16:52:24 +00001795
Jim Ingham06b84492012-07-04 00:35:43 +00001796
Chris Lattner24943d22010-06-08 16:52:24 +00001797Error
1798ProcessGDBRemote::DoDestroy ()
1799{
1800 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001801 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001802 if (log)
1803 log->Printf ("ProcessGDBRemote::DoDestroy()");
1804
Jim Ingham06b84492012-07-04 00:35:43 +00001805 // There is a bug in older iOS debugservers where they don't shut down the process
1806 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1807 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1808 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1809 // destroy it again.
1810 //
1811 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1812 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1813 // the debugservers with this bug are equal. There really should be a better way to test this!
1814 //
1815 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1816 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1817 // just do the straight-forward kill.
1818 //
1819 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1820 // necessary (or helpful) to do any of this.
1821
1822 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1823 {
1824 PlatformSP platform_sp = GetTarget().GetPlatform();
1825
1826 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1827 if (platform_sp
1828 && platform_sp->GetName()
1829 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1830 {
1831 if (m_destroy_tried_resuming)
1832 {
1833 if (log)
1834 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1835 }
1836 else
1837 {
1838 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1839 // but we really need it to happen here and it doesn't matter if we do it twice.
1840 m_thread_list.DiscardThreadPlans();
1841 DisableAllBreakpointSites();
1842
1843 bool stop_looks_like_crash = false;
1844 ThreadList &threads = GetThreadList();
1845
1846 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001847 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001848
1849 size_t num_threads = threads.GetSize();
1850 for (size_t i = 0; i < num_threads; i++)
1851 {
1852 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1853 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1854 StopReason reason = eStopReasonInvalid;
1855 if (stop_info_sp)
1856 reason = stop_info_sp->GetStopReason();
1857 if (reason == eStopReasonBreakpoint
1858 || reason == eStopReasonException)
1859 {
1860 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001861 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %" PRId64 " stopped with reason: %s.",
Jim Ingham06b84492012-07-04 00:35:43 +00001862 thread_sp->GetID(),
1863 stop_info_sp->GetDescription());
1864 stop_looks_like_crash = true;
1865 break;
1866 }
1867 }
1868 }
1869
1870 if (stop_looks_like_crash)
1871 {
1872 if (log)
1873 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1874 m_destroy_tried_resuming = true;
1875
1876 // If we are going to run again before killing, it would be good to suspend all the threads
1877 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1878 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1879 // have to run the risk of letting those threads proceed a bit.
1880
1881 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001882 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001883
1884 size_t num_threads = threads.GetSize();
1885 for (size_t i = 0; i < num_threads; i++)
1886 {
1887 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1888 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1889 StopReason reason = eStopReasonInvalid;
1890 if (stop_info_sp)
1891 reason = stop_info_sp->GetStopReason();
1892 if (reason != eStopReasonBreakpoint
1893 && reason != eStopReasonException)
1894 {
1895 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001896 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %" PRId64 " before running.",
Jim Ingham06b84492012-07-04 00:35:43 +00001897 thread_sp->GetID());
1898 thread_sp->SetResumeState(eStateSuspended);
1899 }
1900 }
1901 }
1902 Resume ();
1903 return Destroy();
1904 }
1905 }
1906 }
1907 }
1908
Chris Lattner24943d22010-06-08 16:52:24 +00001909 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001910 int exit_status = SIGABRT;
1911 std::string exit_string;
1912
Greg Claytona4881d02011-01-22 07:12:45 +00001913 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001914 {
Jim Ingham8226e942011-10-28 01:11:35 +00001915 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001916 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001917
1918 StringExtractorGDBRemote response;
1919 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001920 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1921
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001922 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001923 {
1924 char packet_cmd = response.GetChar(0);
1925
1926 if (packet_cmd == 'W' || packet_cmd == 'X')
1927 {
Greg Clayton06709002011-12-06 04:51:14 +00001928 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001929 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001930 exit_status = response.GetHexU8();
1931 }
1932 else
1933 {
1934 if (log)
1935 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1936 exit_string.assign("got unexpected response to k packet: ");
1937 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001938 }
1939 }
1940 else
1941 {
Jim Ingham8247e622012-06-06 00:32:39 +00001942 if (log)
1943 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1944 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001945 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001946
1947 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00001948 }
Jim Ingham8247e622012-06-06 00:32:39 +00001949 else
1950 {
1951 if (log)
1952 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00001953 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00001954 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001955 }
Jim Ingham8247e622012-06-06 00:32:39 +00001956 else
1957 {
1958 // If we missed setting the exit status on the way out, do it here.
1959 // NB set exit status can be called multiple times, the first one sets the status.
1960 exit_string.assign("destroying when not connected to debugserver");
1961 }
1962
1963 SetExitStatus(exit_status, exit_string.c_str());
1964
Chris Lattner24943d22010-06-08 16:52:24 +00001965 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001966 KillDebugserverProcess ();
1967 return error;
1968}
1969
Chris Lattner24943d22010-06-08 16:52:24 +00001970//------------------------------------------------------------------
1971// Process Queries
1972//------------------------------------------------------------------
1973
1974bool
1975ProcessGDBRemote::IsAlive ()
1976{
Greg Clayton58e844b2010-12-08 05:08:21 +00001977 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001978}
1979
1980addr_t
1981ProcessGDBRemote::GetImageInfoAddress()
1982{
Jason Molenda9338dd52013-01-30 04:39:32 +00001983 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001984}
1985
Chris Lattner24943d22010-06-08 16:52:24 +00001986//------------------------------------------------------------------
1987// Process Memory
1988//------------------------------------------------------------------
1989size_t
1990ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1991{
1992 if (size > m_max_memory_size)
1993 {
1994 // Keep memory read sizes down to a sane limit. This function will be
1995 // called multiple times in order to complete the task by
1996 // lldb_private::Process so it is ok to do this.
1997 size = m_max_memory_size;
1998 }
1999
2000 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002001 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00002002 assert (packet_len + 1 < sizeof(packet));
2003 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002004 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002005 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002006 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002007 {
2008 error.Clear();
2009 return response.GetHexBytes(buf, size, '\xdd');
2010 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002011 else if (response.IsErrorResponse())
Greg Clayton49d888d2012-12-06 22:49:16 +00002012 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton61d043b2011-03-22 04:00:09 +00002013 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002014 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002015 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002016 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002017 }
2018 else
2019 {
2020 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
2021 }
2022 return 0;
2023}
2024
2025size_t
2026ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2027{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002028 if (size > m_max_memory_size)
2029 {
2030 // Keep memory read sizes down to a sane limit. This function will be
2031 // called multiple times in order to complete the task by
2032 // lldb_private::Process so it is ok to do this.
2033 size = m_max_memory_size;
2034 }
2035
Chris Lattner24943d22010-06-08 16:52:24 +00002036 StreamString packet;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002037 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00002038 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00002039 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002040 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002041 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002042 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002043 {
2044 error.Clear();
2045 return size;
2046 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002047 else if (response.IsErrorResponse())
Greg Clayton49d888d2012-12-06 22:49:16 +00002048 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton61d043b2011-03-22 04:00:09 +00002049 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002050 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002051 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002052 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002053 }
2054 else
2055 {
2056 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
2057 }
2058 return 0;
2059}
2060
2061lldb::addr_t
2062ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2063{
Greg Clayton989816b2011-05-14 01:50:35 +00002064 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2065
Greg Clayton2f085c62011-05-15 01:25:55 +00002066 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00002067 switch (supported)
2068 {
2069 case eLazyBoolCalculate:
2070 case eLazyBoolYes:
2071 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2072 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2073 return allocated_addr;
2074
2075 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002076 // Call mmap() to create memory in the inferior..
2077 unsigned prot = 0;
2078 if (permissions & lldb::ePermissionsReadable)
2079 prot |= eMmapProtRead;
2080 if (permissions & lldb::ePermissionsWritable)
2081 prot |= eMmapProtWrite;
2082 if (permissions & lldb::ePermissionsExecutable)
2083 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00002084
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002085 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2086 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2087 m_addr_to_mmap_size[allocated_addr] = size;
2088 else
2089 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002090 break;
2091 }
2092
Chris Lattner24943d22010-06-08 16:52:24 +00002093 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002094 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002095 else
2096 error.Clear();
2097 return allocated_addr;
2098}
2099
2100Error
Greg Claytona9385532011-11-18 07:03:08 +00002101ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2102 MemoryRegionInfo &region_info)
2103{
2104
2105 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2106 return error;
2107}
2108
2109Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002110ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2111{
2112
2113 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2114 return error;
2115}
2116
2117Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002118ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2119{
2120 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2121 return error;
2122}
2123
2124Error
Chris Lattner24943d22010-06-08 16:52:24 +00002125ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2126{
2127 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002128 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2129
2130 switch (supported)
2131 {
2132 case eLazyBoolCalculate:
2133 // We should never be deallocating memory without allocating memory
2134 // first so we should never get eLazyBoolCalculate
2135 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2136 break;
2137
2138 case eLazyBoolYes:
2139 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002140 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002141 break;
2142
2143 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002144 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002145 {
2146 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002147 if (pos != m_addr_to_mmap_size.end() &&
2148 InferiorCallMunmap(this, addr, pos->second))
2149 m_addr_to_mmap_size.erase (pos);
2150 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002151 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002152 }
2153 break;
2154 }
2155
Chris Lattner24943d22010-06-08 16:52:24 +00002156 return error;
2157}
2158
2159
2160//------------------------------------------------------------------
2161// Process STDIO
2162//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002163size_t
2164ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2165{
2166 if (m_stdio_communication.IsConnected())
2167 {
2168 ConnectionStatus status;
2169 m_stdio_communication.Write(src, src_len, status, NULL);
2170 }
2171 return 0;
2172}
2173
2174Error
2175ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2176{
2177 Error error;
2178 assert (bp_site != NULL);
2179
Greg Claytone005f2c2010-11-06 01:53:30 +00002180 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002181 user_id_t site_id = bp_site->GetID();
2182 const addr_t addr = bp_site->GetLoadAddress();
2183 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002184 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002185
2186 if (bp_site->IsEnabled())
2187 {
2188 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002189 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002190 return error;
2191 }
2192 else
2193 {
2194 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2195
2196 if (bp_site->HardwarePreferred())
2197 {
2198 // Try and set hardware breakpoint, and if that fails, fall through
2199 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002200 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002201 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002202 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002203 {
2204 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002205 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002206 return error;
2207 }
Chris Lattner24943d22010-06-08 16:52:24 +00002208 }
2209 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002210
2211 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002212 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002213 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2214 {
2215 bp_site->SetEnabled(true);
2216 bp_site->SetType (BreakpointSite::eExternal);
2217 return error;
2218 }
Chris Lattner24943d22010-06-08 16:52:24 +00002219 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002220
2221 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002222 }
2223
2224 if (log)
2225 {
2226 const char *err_string = error.AsCString();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002227 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002228 bp_site->GetLoadAddress(),
2229 err_string ? err_string : "NULL");
2230 }
2231 // We shouldn't reach here on a successful breakpoint enable...
2232 if (error.Success())
2233 error.SetErrorToGenericError();
2234 return error;
2235}
2236
2237Error
2238ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2239{
2240 Error error;
2241 assert (bp_site != NULL);
2242 addr_t addr = bp_site->GetLoadAddress();
2243 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002244 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002245 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002246 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002247
2248 if (bp_site->IsEnabled())
2249 {
2250 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2251
Greg Claytonb72d0f02011-04-12 05:54:46 +00002252 BreakpointSite::Type bp_type = bp_site->GetType();
2253 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002254 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002255 case BreakpointSite::eSoftware:
2256 error = DisableSoftwareBreakpoint (bp_site);
2257 break;
2258
2259 case BreakpointSite::eHardware:
2260 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2261 error.SetErrorToGenericError();
2262 break;
2263
2264 case BreakpointSite::eExternal:
2265 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2266 error.SetErrorToGenericError();
2267 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002268 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002269 if (error.Success())
2270 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002271 }
2272 else
2273 {
2274 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002275 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002276 return error;
2277 }
2278
2279 if (error.Success())
2280 error.SetErrorToGenericError();
2281 return error;
2282}
2283
Johnny Chen21900fb2011-09-06 22:38:36 +00002284// Pre-requisite: wp != NULL.
2285static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002286GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002287{
2288 assert(wp);
2289 bool watch_read = wp->WatchpointRead();
2290 bool watch_write = wp->WatchpointWrite();
2291
2292 // watch_read and watch_write cannot both be false.
2293 assert(watch_read || watch_write);
2294 if (watch_read && watch_write)
2295 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002296 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002297 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002298 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002299 return eWatchpointWrite;
2300}
2301
Chris Lattner24943d22010-06-08 16:52:24 +00002302Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002303ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002304{
2305 Error error;
2306 if (wp)
2307 {
2308 user_id_t watchID = wp->GetID();
2309 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002310 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002311 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002312 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002313 if (wp->IsEnabled())
2314 {
2315 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002316 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002317 return error;
2318 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002319
2320 GDBStoppointType type = GetGDBStoppointType(wp);
2321 // Pass down an appropriate z/Z packet...
2322 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002323 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002324 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2325 {
Jim Ingham9c970a32012-12-18 02:03:49 +00002326 wp->SetEnabled(true, notify);
Johnny Chen21900fb2011-09-06 22:38:36 +00002327 return error;
2328 }
2329 else
2330 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002331 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002332 else
2333 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002334 }
2335 else
2336 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002337 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002338 }
2339 if (error.Success())
2340 error.SetErrorToGenericError();
2341 return error;
2342}
2343
2344Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002345ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002346{
2347 Error error;
2348 if (wp)
2349 {
2350 user_id_t watchID = wp->GetID();
2351
Greg Claytone005f2c2010-11-06 01:53:30 +00002352 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002353
2354 addr_t addr = wp->GetLoadAddress();
Jim Ingham9c970a32012-12-18 02:03:49 +00002355
Chris Lattner24943d22010-06-08 16:52:24 +00002356 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002357 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002358
Johnny Chen21900fb2011-09-06 22:38:36 +00002359 if (!wp->IsEnabled())
2360 {
2361 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002362 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002363 // See also 'class WatchpointSentry' within StopInfo.cpp.
2364 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2365 // the watchpoint object to intelligently process this action.
Jim Ingham9c970a32012-12-18 02:03:49 +00002366 wp->SetEnabled(false, notify);
Johnny Chen21900fb2011-09-06 22:38:36 +00002367 return error;
2368 }
2369
Chris Lattner24943d22010-06-08 16:52:24 +00002370 if (wp->IsHardware())
2371 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002372 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002373 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002374 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2375 {
Jim Ingham9c970a32012-12-18 02:03:49 +00002376 wp->SetEnabled(false, notify);
Johnny Chen21900fb2011-09-06 22:38:36 +00002377 return error;
2378 }
2379 else
2380 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002381 }
2382 // TODO: clear software watchpoints if we implement them
2383 }
2384 else
2385 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002386 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002387 }
2388 if (error.Success())
2389 error.SetErrorToGenericError();
2390 return error;
2391}
2392
2393void
2394ProcessGDBRemote::Clear()
2395{
2396 m_flags = 0;
2397 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002398}
2399
2400Error
2401ProcessGDBRemote::DoSignal (int signo)
2402{
2403 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002404 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002405 if (log)
2406 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2407
2408 if (!m_gdb_comm.SendAsyncSignal (signo))
2409 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2410 return error;
2411}
2412
Chris Lattner24943d22010-06-08 16:52:24 +00002413Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002414ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2415{
2416 ProcessLaunchInfo launch_info;
2417 return StartDebugserverProcess(debugserver_url, launch_info);
2418}
2419
2420Error
2421ProcessGDBRemote::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 +00002422{
2423 Error error;
2424 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2425 {
2426 // If we locate debugserver, keep that located version around
2427 static FileSpec g_debugserver_file_spec;
2428
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002429 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002430 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002431 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002432
2433 // Always check to see if we have an environment override for the path
2434 // to the debugserver to use and use it if we do.
2435 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2436 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002437 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002438 else
2439 debugserver_file_spec = g_debugserver_file_spec;
2440 bool debugserver_exists = debugserver_file_spec.Exists();
2441 if (!debugserver_exists)
2442 {
2443 // The debugserver binary is in the LLDB.framework/Resources
2444 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002445 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002446 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002447 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002448 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002449 if (debugserver_exists)
2450 {
2451 g_debugserver_file_spec = debugserver_file_spec;
2452 }
2453 else
2454 {
2455 g_debugserver_file_spec.Clear();
2456 debugserver_file_spec.Clear();
2457 }
Chris Lattner24943d22010-06-08 16:52:24 +00002458 }
2459 }
2460
2461 if (debugserver_exists)
2462 {
2463 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2464
2465 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002466
Greg Claytone005f2c2010-11-06 01:53:30 +00002467 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002468
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002469 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002470 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002471
Chris Lattner24943d22010-06-08 16:52:24 +00002472 // Start args with "debugserver /file/path -r --"
2473 debugserver_args.AppendArgument(debugserver_path);
2474 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002475 // use native registers, not the GDB registers
2476 debugserver_args.AppendArgument("--native-regs");
2477 // make debugserver run in its own session so signals generated by
2478 // special terminal key sequences (^C) don't affect debugserver
2479 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002480
Chris Lattner24943d22010-06-08 16:52:24 +00002481 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2482 if (env_debugserver_log_file)
2483 {
2484 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2485 debugserver_args.AppendArgument(arg_cstr);
2486 }
2487
2488 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2489 if (env_debugserver_log_flags)
2490 {
2491 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2492 debugserver_args.AppendArgument(arg_cstr);
2493 }
Jim Ingham2b2ac8c2012-10-03 22:31:30 +00002494// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2495// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002496
Greg Claytonb72d0f02011-04-12 05:54:46 +00002497 // We currently send down all arguments, attach pids, or attach
2498 // process names in dedicated GDB server packets, so we don't need
2499 // to pass them as arguments. This is currently because of all the
2500 // things we need to setup prior to launching: the environment,
2501 // current working dir, file actions, etc.
2502#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002503 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002504 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002505 {
Greg Claytona2f74232011-02-24 22:24:29 +00002506 // Terminate the debugserver args so we can now append the inferior args
2507 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002508
Greg Claytona2f74232011-02-24 22:24:29 +00002509 for (int i = 0; inferior_argv[i] != NULL; ++i)
2510 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002511 }
2512 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2513 {
2514 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2515 debugserver_args.AppendArgument (arg_cstr);
2516 }
2517 else if (attach_name && attach_name[0])
2518 {
2519 if (wait_for_launch)
2520 debugserver_args.AppendArgument ("--waitfor");
2521 else
2522 debugserver_args.AppendArgument ("--attach");
2523 debugserver_args.AppendArgument (attach_name);
2524 }
Chris Lattner24943d22010-06-08 16:52:24 +00002525#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002526
2527 ProcessLaunchInfo::FileAction file_action;
2528
2529 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2530 // to "/dev/null" if we run into any problems.
2531 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002532 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002533 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002534 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002535 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002536 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002537
2538 if (log)
2539 {
2540 StreamString strm;
2541 debugserver_args.Dump (&strm);
2542 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2543 }
2544
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002545 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2546 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002547
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002548 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002549
Greg Claytonb72d0f02011-04-12 05:54:46 +00002550 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002551 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002552 else
Chris Lattner24943d22010-06-08 16:52:24 +00002553 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2554
2555 if (error.Fail() || log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002556 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002557 }
2558 else
2559 {
Greg Clayton9c236732011-10-26 00:56:27 +00002560 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002561 }
2562
2563 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2564 StartAsyncThread ();
2565 }
2566 return error;
2567}
2568
2569bool
2570ProcessGDBRemote::MonitorDebugserverProcess
2571(
2572 void *callback_baton,
2573 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002574 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002575 int signo, // Zero for no signal
2576 int exit_status // Exit value of process if signal is zero
2577)
2578{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002579 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2580 // and might not exist anymore, so we need to carefully try to get the
2581 // target for this process first since we have a race condition when
2582 // we are done running between getting the notice that the inferior
2583 // process has died and the debugserver that was debugging this process.
2584 // In our test suite, we are also continually running process after
2585 // process, so we must be very careful to make sure:
2586 // 1 - process object hasn't been deleted already
2587 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002588
2589 // "debugserver_pid" argument passed in is the process ID for
2590 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002591 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002592
Greg Clayton75ccf502010-08-21 02:22:51 +00002593 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002594
Greg Clayton1c4642c2011-11-16 05:37:56 +00002595 // Get a shared pointer to the target that has a matching process pointer.
2596 // This target could be gone, or the target could already have a new process
2597 // object inside of it
2598 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2599
Greg Clayton72e1c782011-01-22 23:43:18 +00002600 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002601 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton72e1c782011-01-22 23:43:18 +00002602
Greg Clayton1c4642c2011-11-16 05:37:56 +00002603 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002604 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002605 // We found a process in a target that matches, but another thread
2606 // might be in the process of launching a new process that will
2607 // soon replace it, so get a shared pointer to the process so we
2608 // can keep it alive.
2609 ProcessSP process_sp (target_sp->GetProcessSP());
2610 // Now we have a shared pointer to the process that can't go away on us
2611 // so we now make sure it was the same as the one passed in, and also make
2612 // sure that our previous "process *" didn't get deleted and have a new
2613 // "process *" created in its place with the same pointer. To verify this
2614 // we make sure the process has our debugserver process ID. If we pass all
2615 // of these tests, then we are sure that this process is the one we were
2616 // looking for.
2617 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002618 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002619 // Sleep for a half a second to make sure our inferior process has
2620 // time to set its exit status before we set it incorrectly when
2621 // both the debugserver and the inferior process shut down.
2622 usleep (500000);
2623 // If our process hasn't yet exited, debugserver might have died.
2624 // If the process did exit, the we are reaping it.
2625 const StateType state = process->GetState();
2626
2627 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2628 state != eStateInvalid &&
2629 state != eStateUnloaded &&
2630 state != eStateExited &&
2631 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002632 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002633 char error_str[1024];
2634 if (signo)
2635 {
2636 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2637 if (signal_cstr)
2638 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2639 else
2640 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2641 }
Chris Lattner24943d22010-06-08 16:52:24 +00002642 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002643 {
2644 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2645 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002646
Greg Clayton1c4642c2011-11-16 05:37:56 +00002647 process->SetExitStatus (-1, error_str);
2648 }
2649 // Debugserver has exited we need to let our ProcessGDBRemote
2650 // know that it no longer has a debugserver instance
2651 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002652 }
Chris Lattner24943d22010-06-08 16:52:24 +00002653 }
2654 return true;
2655}
2656
2657void
2658ProcessGDBRemote::KillDebugserverProcess ()
2659{
2660 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2661 {
2662 ::kill (m_debugserver_pid, SIGINT);
2663 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2664 }
2665}
2666
2667void
2668ProcessGDBRemote::Initialize()
2669{
2670 static bool g_initialized = false;
2671
2672 if (g_initialized == false)
2673 {
2674 g_initialized = true;
2675 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2676 GetPluginDescriptionStatic(),
2677 CreateInstance);
2678
2679 Log::Callbacks log_callbacks = {
2680 ProcessGDBRemoteLog::DisableLog,
2681 ProcessGDBRemoteLog::EnableLog,
2682 ProcessGDBRemoteLog::ListLogCategories
2683 };
2684
2685 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2686 }
2687}
2688
2689bool
Chris Lattner24943d22010-06-08 16:52:24 +00002690ProcessGDBRemote::StartAsyncThread ()
2691{
Greg Claytone005f2c2010-11-06 01:53:30 +00002692 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002693
2694 if (log)
2695 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Inghama9488302012-11-01 01:15:33 +00002696
2697 Mutex::Locker start_locker(m_async_thread_state_mutex);
2698 if (m_async_thread_state == eAsyncThreadNotStarted)
2699 {
2700 // Create a thread that watches our internal state and controls which
2701 // events make it to clients (into the DCProcess event queue).
2702 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2703 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2704 {
2705 m_async_thread_state = eAsyncThreadRunning;
2706 return true;
2707 }
2708 else
2709 return false;
2710 }
2711 else
2712 {
2713 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2714 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2715 if (log)
2716 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2717 if (m_async_thread_state == eAsyncThreadRunning)
2718 return true;
2719 else
2720 return false;
2721 }
Chris Lattner24943d22010-06-08 16:52:24 +00002722}
2723
2724void
2725ProcessGDBRemote::StopAsyncThread ()
2726{
Greg Claytone005f2c2010-11-06 01:53:30 +00002727 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002728
2729 if (log)
2730 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2731
Jim Inghama9488302012-11-01 01:15:33 +00002732 Mutex::Locker start_locker(m_async_thread_state_mutex);
2733 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner24943d22010-06-08 16:52:24 +00002734 {
Jim Inghama9488302012-11-01 01:15:33 +00002735 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2736
2737 // This will shut down the async thread.
2738 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2739
2740 // Stop the stdio thread
2741 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2742 {
2743 Host::ThreadJoin (m_async_thread, NULL, NULL);
2744 }
2745 m_async_thread_state = eAsyncThreadDone;
2746 }
2747 else
2748 {
2749 if (log)
2750 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner24943d22010-06-08 16:52:24 +00002751 }
2752}
2753
2754
2755void *
2756ProcessGDBRemote::AsyncThread (void *arg)
2757{
2758 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2759
Greg Claytone005f2c2010-11-06 01:53:30 +00002760 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002761 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002762 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002763
2764 Listener listener ("ProcessGDBRemote::AsyncThread");
2765 EventSP event_sp;
2766 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2767 eBroadcastBitAsyncThreadShouldExit;
2768
2769 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2770 {
Greg Claytona2f74232011-02-24 22:24:29 +00002771 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2772
Chris Lattner24943d22010-06-08 16:52:24 +00002773 bool done = false;
2774 while (!done)
2775 {
2776 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002777 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002778 if (listener.WaitForEvent (NULL, event_sp))
2779 {
2780 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002781 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002782 {
Greg Claytona2f74232011-02-24 22:24:29 +00002783 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002784 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002785
Greg Claytona2f74232011-02-24 22:24:29 +00002786 switch (event_type)
2787 {
2788 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002789 {
Greg Claytona2f74232011-02-24 22:24:29 +00002790 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002791
Greg Claytona2f74232011-02-24 22:24:29 +00002792 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002793 {
Greg Claytona2f74232011-02-24 22:24:29 +00002794 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2795 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2796 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002797 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002798
Greg Claytona2f74232011-02-24 22:24:29 +00002799 if (::strstr (continue_cstr, "vAttach") == NULL)
2800 process->SetPrivateState(eStateRunning);
2801 StringExtractorGDBRemote response;
2802 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002803
Greg Clayton67b402c2012-05-16 02:48:06 +00002804 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2805 // The thread ID list might be contained within the "response", or the stop reply packet that
2806 // caused the stop. So clear it now before we give the stop reply packet to the process
2807 // using the process->SetLastStopPacket()...
2808 process->ClearThreadIDList ();
2809
Greg Claytona2f74232011-02-24 22:24:29 +00002810 switch (stop_state)
2811 {
2812 case eStateStopped:
2813 case eStateCrashed:
2814 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002815 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002816 process->SetPrivateState (stop_state);
2817 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002818
Greg Claytona2f74232011-02-24 22:24:29 +00002819 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002820 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002821 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002822 response.SetFilePos(1);
2823 process->SetExitStatus(response.GetHexU8(), NULL);
2824 done = true;
2825 break;
2826
2827 case eStateInvalid:
2828 process->SetExitStatus(-1, "lost connection");
2829 break;
2830
2831 default:
2832 process->SetPrivateState (stop_state);
2833 break;
2834 }
Chris Lattner24943d22010-06-08 16:52:24 +00002835 }
2836 }
Greg Claytona2f74232011-02-24 22:24:29 +00002837 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002838
Greg Claytona2f74232011-02-24 22:24:29 +00002839 case eBroadcastBitAsyncThreadShouldExit:
2840 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002841 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002842 done = true;
2843 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002844
Greg Claytona2f74232011-02-24 22:24:29 +00002845 default:
2846 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002847 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Claytona2f74232011-02-24 22:24:29 +00002848 done = true;
2849 break;
2850 }
2851 }
2852 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2853 {
2854 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2855 {
2856 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002857 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002858 }
Chris Lattner24943d22010-06-08 16:52:24 +00002859 }
2860 }
2861 else
2862 {
2863 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002864 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002865 done = true;
2866 }
2867 }
2868 }
2869
2870 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002871 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002872
2873 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2874 return NULL;
2875}
2876
Chris Lattner24943d22010-06-08 16:52:24 +00002877const char *
2878ProcessGDBRemote::GetDispatchQueueNameForThread
2879(
2880 addr_t thread_dispatch_qaddr,
2881 std::string &dispatch_queue_name
2882)
2883{
2884 dispatch_queue_name.clear();
2885 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2886 {
2887 // Cache the dispatch_queue_offsets_addr value so we don't always have
2888 // to look it up
2889 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2890 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002891 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2892 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002893 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2894 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002895 if (module_sp)
2896 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2897
2898 if (dispatch_queue_offsets_symbol == NULL)
2899 {
Greg Clayton444fe992012-02-26 05:51:37 +00002900 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2901 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002902 if (module_sp)
2903 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2904 }
Chris Lattner24943d22010-06-08 16:52:24 +00002905 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002906 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002907
2908 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2909 return NULL;
2910 }
2911
2912 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002913 DataExtractor data (memory_buffer,
2914 sizeof(memory_buffer),
2915 m_target.GetArchitecture().GetByteOrder(),
2916 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002917
2918 // Excerpt from src/queue_private.h
2919 struct dispatch_queue_offsets_s
2920 {
2921 uint16_t dqo_version;
Jason Molenda9704ca22012-11-10 06:54:30 +00002922 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2923 uint16_t dqo_label_size; // in version 1-3, length of string; in version 4+, size of a (void*) in this process
Chris Lattner24943d22010-06-08 16:52:24 +00002924 } dispatch_queue_offsets;
2925
2926
2927 Error error;
2928 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2929 {
Greg Clayton36da2aa2013-01-25 18:06:21 +00002930 lldb::offset_t data_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002931 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2932 {
2933 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2934 {
2935 data_offset = 0;
2936 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molenda9704ca22012-11-10 06:54:30 +00002937 if (dispatch_queue_offsets.dqo_version >= 4)
2938 {
2939 // libdispatch versions 4+, pointer to dispatch name is in the
2940 // queue structure.
2941 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
2942 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2943 {
2944 data_offset = 0;
2945 lldb::addr_t label_addr = data.GetAddress(&data_offset);
2946 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
2947 }
2948 }
2949 else
2950 {
2951 // libdispatch versions 1-3, dispatch name is a fixed width char array
2952 // in the queue structure.
2953 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2954 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2955 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2956 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2957 dispatch_queue_name.erase (bytes_read);
2958 }
Chris Lattner24943d22010-06-08 16:52:24 +00002959 }
2960 }
2961 }
2962 }
2963 if (dispatch_queue_name.empty())
2964 return NULL;
2965 return dispatch_queue_name.c_str();
2966}
2967
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002968//uint32_t
2969//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2970//{
2971// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2972// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2973// if (m_local_debugserver)
2974// {
2975// return Host::ListProcessesMatchingName (name, matches, pids);
2976// }
2977// else
2978// {
2979// // FIXME: Implement talking to the remote debugserver.
2980// return 0;
2981// }
2982//
2983//}
2984//
Jim Ingham55e01d82011-01-22 01:33:44 +00002985bool
2986ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2987 lldb_private::StoppointCallbackContext *context,
2988 lldb::user_id_t break_id,
2989 lldb::user_id_t break_loc_id)
2990{
2991 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2992 // run so I can stop it if that's what I want to do.
2993 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2994 if (log)
2995 log->Printf("Hit New Thread Notification breakpoint.");
2996 return false;
2997}
2998
2999
3000bool
3001ProcessGDBRemote::StartNoticingNewThreads()
3002{
Jim Ingham55e01d82011-01-22 01:33:44 +00003003 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003004 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003005 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003006 if (log && log->GetVerbose())
3007 log->Printf("Enabled noticing new thread breakpoint.");
3008 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003009 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003010 else
Jim Ingham55e01d82011-01-22 01:33:44 +00003011 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003012 PlatformSP platform_sp (m_target.GetPlatform());
3013 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003014 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003015 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3016 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003017 {
Jim Ingham6bb73372011-10-15 00:21:37 +00003018 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003019 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3020 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003021 }
3022 else
3023 {
3024 if (log)
3025 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00003026 }
3027 }
3028 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003029 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00003030}
3031
3032bool
3033ProcessGDBRemote::StopNoticingNewThreads()
3034{
Jim Inghamff276fe2011-02-08 05:19:01 +00003035 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00003036 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00003037 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003038
3039 if (m_thread_create_bp_sp)
3040 m_thread_create_bp_sp->SetEnabled(false);
3041
Jim Ingham55e01d82011-01-22 01:33:44 +00003042 return true;
3043}
3044
Jason Molendab46937c2012-10-03 01:29:34 +00003045lldb_private::DynamicLoader *
3046ProcessGDBRemote::GetDynamicLoader ()
3047{
3048 if (m_dyld_ap.get() == NULL)
3049 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
3050 return m_dyld_ap.get();
3051}
Jim Ingham55e01d82011-01-22 01:33:44 +00003052
Greg Clayton13193d52012-10-13 02:07:45 +00003053
Greg Claytonb8596392012-10-15 22:42:16 +00003054class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton13193d52012-10-13 02:07:45 +00003055{
3056private:
3057
3058public:
Greg Claytonb8596392012-10-15 22:42:16 +00003059 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton13193d52012-10-13 02:07:45 +00003060 CommandObjectParsed (interpreter,
Greg Claytonb8596392012-10-15 22:42:16 +00003061 "process plugin packet history",
3062 "Dumps the packet history buffer. ",
Greg Clayton13193d52012-10-13 02:07:45 +00003063 NULL)
3064 {
3065 }
3066
Greg Claytonb8596392012-10-15 22:42:16 +00003067 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton13193d52012-10-13 02:07:45 +00003068 {
3069 }
3070
3071 bool
3072 DoExecute (Args& command, CommandReturnObject &result)
3073 {
Greg Claytonb8596392012-10-15 22:42:16 +00003074 const size_t argc = command.GetArgumentCount();
3075 if (argc == 0)
3076 {
3077 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3078 if (process)
3079 {
3080 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3081 result.SetStatus (eReturnStatusSuccessFinishResult);
3082 return true;
3083 }
3084 }
3085 else
3086 {
3087 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3088 }
3089 result.SetStatus (eReturnStatusFailed);
3090 return false;
3091 }
3092};
3093
3094class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3095{
3096private:
3097
3098public:
3099 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3100 CommandObjectParsed (interpreter,
3101 "process plugin packet send",
3102 "Send a custom packet through the GDB remote protocol and print the answer. "
3103 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3104 NULL)
3105 {
3106 }
3107
3108 ~CommandObjectProcessGDBRemotePacketSend ()
3109 {
3110 }
3111
3112 bool
3113 DoExecute (Args& command, CommandReturnObject &result)
3114 {
3115 const size_t argc = command.GetArgumentCount();
3116 if (argc == 0)
3117 {
3118 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3119 result.SetStatus (eReturnStatusFailed);
3120 return false;
3121 }
3122
3123 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3124 if (process)
3125 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003126 for (size_t i=0; i<argc; ++ i)
Greg Claytonb8596392012-10-15 22:42:16 +00003127 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003128 const char *packet_cstr = command.GetArgumentAtIndex(0);
3129 bool send_async = true;
3130 StringExtractorGDBRemote response;
3131 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3132 result.SetStatus (eReturnStatusSuccessFinishResult);
3133 Stream &output_strm = result.GetOutputStream();
3134 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong0df19cc2013-01-18 23:11:53 +00003135 std::string &response_str = response.GetStringRef();
3136
3137 if (strcmp(packet_cstr, "qGetProfileData") == 0)
3138 {
3139 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3140 }
3141
Han Ming Ongae9cc552012-11-26 20:42:03 +00003142 if (response_str.empty())
3143 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3144 else
3145 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Claytonb8596392012-10-15 22:42:16 +00003146 }
Greg Claytonb8596392012-10-15 22:42:16 +00003147 }
Greg Clayton13193d52012-10-13 02:07:45 +00003148 return true;
3149 }
3150};
3151
Greg Clayton2fb13ab2013-02-01 23:03:47 +00003152class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3153{
3154private:
3155
3156public:
3157 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3158 CommandObjectRaw (interpreter,
3159 "process plugin packet monitor",
3160 "Send a qCmd packet through the GDB remote protocol and print the response."
3161 "The argument passed to this command will be hex encoded into a valid 'qCmd' packet, sent and the response will be printed.",
3162 NULL)
3163 {
3164 }
3165
3166 ~CommandObjectProcessGDBRemotePacketMonitor ()
3167 {
3168 }
3169
3170 bool
3171 DoExecute (const char *command, CommandReturnObject &result)
3172 {
3173 if (command == NULL || command[0] == '\0')
3174 {
3175 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3176 result.SetStatus (eReturnStatusFailed);
3177 return false;
3178 }
3179
3180 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3181 if (process)
3182 {
3183 StreamString packet;
3184 packet.PutCString("qCmd,");
3185 packet.PutBytesAsRawHex8(command, strlen(command));
3186 const char *packet_cstr = packet.GetString().c_str();
3187
3188 bool send_async = true;
3189 StringExtractorGDBRemote response;
3190 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3191 result.SetStatus (eReturnStatusSuccessFinishResult);
3192 Stream &output_strm = result.GetOutputStream();
3193 output_strm.Printf (" packet: %s\n", packet_cstr);
3194 const std::string &response_str = response.GetStringRef();
3195
3196 if (response_str.empty())
3197 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3198 else
3199 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3200 }
3201 return true;
3202 }
3203};
3204
Greg Claytonb8596392012-10-15 22:42:16 +00003205class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3206{
3207private:
3208
3209public:
3210 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3211 CommandObjectMultiword (interpreter,
3212 "process plugin packet",
3213 "Commands that deal with GDB remote packets.",
3214 NULL)
3215 {
3216 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3217 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Clayton2fb13ab2013-02-01 23:03:47 +00003218 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Claytonb8596392012-10-15 22:42:16 +00003219 }
3220
3221 ~CommandObjectProcessGDBRemotePacket ()
3222 {
3223 }
3224};
Greg Clayton13193d52012-10-13 02:07:45 +00003225
3226class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3227{
3228public:
3229 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3230 CommandObjectMultiword (interpreter,
3231 "process plugin",
3232 "A set of commands for operating on a ProcessGDBRemote process.",
3233 "process plugin <subcommand> [<subcommand-options>]")
3234 {
3235 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3236 }
3237
3238 ~CommandObjectMultiwordProcessGDBRemote ()
3239 {
3240 }
3241};
3242
Greg Clayton13193d52012-10-13 02:07:45 +00003243CommandObject *
3244ProcessGDBRemote::GetPluginCommandObject()
3245{
3246 if (!m_command_sp)
3247 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3248 return m_command_sp.get();
3249}