blob: e8e5aac7b019436fe4ab3216ba8338cf102b2edb [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Greg Clayton989816b2011-05-14 01:50:35 +000014#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000016#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000017#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000018
19// C++ Includes
20#include <algorithm>
21#include <map>
22
23// Other libraries and framework includes
24
Johnny Chenecd4feb2011-10-14 00:42:25 +000025#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000026#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Core/ArchSpec.h"
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000030#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Core/InputReader.h"
32#include "lldb/Core/Module.h"
33#include "lldb/Core/PluginManager.h"
34#include "lldb/Core/State.h"
35#include "lldb/Core/StreamString.h"
36#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000037#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Host/TimeValue.h"
39#include "lldb/Symbol/ObjectFile.h"
40#include "lldb/Target/DynamicLoader.h"
41#include "lldb/Target/Target.h"
42#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000043#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000044#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045
46// Project includes
47#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000048#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000049#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000050#include "GDBRemoteRegisterContext.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000054#include "StopInfoMachException.h"
55
Chris Lattner24943d22010-06-08 16:52:24 +000056
Chris Lattner24943d22010-06-08 16:52:24 +000057
58#define DEBUGSERVER_BASENAME "debugserver"
59using namespace lldb;
60using namespace lldb_private;
61
Jim Inghamf9600482011-03-29 21:45:47 +000062static bool rand_initialized = false;
63
Chris Lattner24943d22010-06-08 16:52:24 +000064static inline uint16_t
65get_random_port ()
66{
Jim Inghamf9600482011-03-29 21:45:47 +000067 if (!rand_initialized)
68 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000069 time_t seed = time(NULL);
70
Jim Inghamf9600482011-03-29 21:45:47 +000071 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000072 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000073 }
Stephen Wilson50daf772011-03-25 18:16:28 +000074 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000075}
76
77
78const char *
79ProcessGDBRemote::GetPluginNameStatic()
80{
Greg Claytonb1888f22011-03-19 01:12:21 +000081 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000082}
83
84const char *
85ProcessGDBRemote::GetPluginDescriptionStatic()
86{
87 return "GDB Remote protocol based debugging plug-in.";
88}
89
90void
91ProcessGDBRemote::Terminate()
92{
93 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
94}
95
96
97Process*
98ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
99{
100 return new ProcessGDBRemote (target, listener);
101}
102
103bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000104ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000105{
Greg Clayton61ddf562011-10-21 21:41:45 +0000106 if (plugin_specified_by_name)
107 return true;
108
Chris Lattner24943d22010-06-08 16:52:24 +0000109 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000110 Module *exe_module = target.GetExecutableModulePointer();
111 if (exe_module)
112 return exe_module->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000113 // However, if there is no executable module, we return true since we might be preparing to attach.
114 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000115}
116
117//----------------------------------------------------------------------
118// ProcessGDBRemote constructor
119//----------------------------------------------------------------------
120ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
121 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000123 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000124 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000125 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000126 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000127 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
128 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000129 m_continue_c_tids (),
130 m_continue_C_tids (),
131 m_continue_s_tids (),
132 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000133 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000134 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000135 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000136 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000137{
Greg Claytonff39f742011-04-01 00:29:43 +0000138 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
139 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000140}
141
142//----------------------------------------------------------------------
143// Destructor
144//----------------------------------------------------------------------
145ProcessGDBRemote::~ProcessGDBRemote()
146{
147 // m_mach_process.UnregisterNotificationCallbacks (this);
148 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000149 // We need to call finalize on the process before destroying ourselves
150 // to make sure all of the broadcaster cleanup goes as planned. If we
151 // destruct this class, then Process::~Process() might have problems
152 // trying to fully destroy the broadcaster.
153 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000154}
155
156//----------------------------------------------------------------------
157// PluginInterface
158//----------------------------------------------------------------------
159const char *
160ProcessGDBRemote::GetPluginName()
161{
162 return "Process debugging plug-in that uses the GDB remote protocol";
163}
164
165const char *
166ProcessGDBRemote::GetShortPluginName()
167{
168 return GetPluginNameStatic();
169}
170
171uint32_t
172ProcessGDBRemote::GetPluginVersion()
173{
174 return 1;
175}
176
177void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000178ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000179{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000180 if (!force && m_register_info.GetNumRegisters() > 0)
181 return;
182
183 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000184 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000185 uint32_t reg_offset = 0;
186 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000187 StringExtractorGDBRemote::ResponseType response_type;
188 for (response_type = StringExtractorGDBRemote::eResponse;
189 response_type == StringExtractorGDBRemote::eResponse;
190 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000191 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000192 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
193 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000194 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000195 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000196 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000197 response_type = response.GetResponseType();
198 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000199 {
200 std::string name;
201 std::string value;
202 ConstString reg_name;
203 ConstString alt_name;
204 ConstString set_name;
205 RegisterInfo reg_info = { NULL, // Name
206 NULL, // Alt name
207 0, // byte size
208 reg_offset, // offset
209 eEncodingUint, // encoding
210 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000211 {
212 LLDB_INVALID_REGNUM, // GCC reg num
213 LLDB_INVALID_REGNUM, // DWARF reg num
214 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000215 reg_num, // GDB reg num
216 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000217 }
218 };
219
220 while (response.GetNameColonValue(name, value))
221 {
222 if (name.compare("name") == 0)
223 {
224 reg_name.SetCString(value.c_str());
225 }
226 else if (name.compare("alt-name") == 0)
227 {
228 alt_name.SetCString(value.c_str());
229 }
230 else if (name.compare("bitsize") == 0)
231 {
232 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
233 }
234 else if (name.compare("offset") == 0)
235 {
236 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000237 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000238 {
239 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000240 }
241 }
242 else if (name.compare("encoding") == 0)
243 {
244 if (value.compare("uint") == 0)
245 reg_info.encoding = eEncodingUint;
246 else if (value.compare("sint") == 0)
247 reg_info.encoding = eEncodingSint;
248 else if (value.compare("ieee754") == 0)
249 reg_info.encoding = eEncodingIEEE754;
250 else if (value.compare("vector") == 0)
251 reg_info.encoding = eEncodingVector;
252 }
253 else if (name.compare("format") == 0)
254 {
255 if (value.compare("binary") == 0)
256 reg_info.format = eFormatBinary;
257 else if (value.compare("decimal") == 0)
258 reg_info.format = eFormatDecimal;
259 else if (value.compare("hex") == 0)
260 reg_info.format = eFormatHex;
261 else if (value.compare("float") == 0)
262 reg_info.format = eFormatFloat;
263 else if (value.compare("vector-sint8") == 0)
264 reg_info.format = eFormatVectorOfSInt8;
265 else if (value.compare("vector-uint8") == 0)
266 reg_info.format = eFormatVectorOfUInt8;
267 else if (value.compare("vector-sint16") == 0)
268 reg_info.format = eFormatVectorOfSInt16;
269 else if (value.compare("vector-uint16") == 0)
270 reg_info.format = eFormatVectorOfUInt16;
271 else if (value.compare("vector-sint32") == 0)
272 reg_info.format = eFormatVectorOfSInt32;
273 else if (value.compare("vector-uint32") == 0)
274 reg_info.format = eFormatVectorOfUInt32;
275 else if (value.compare("vector-float32") == 0)
276 reg_info.format = eFormatVectorOfFloat32;
277 else if (value.compare("vector-uint128") == 0)
278 reg_info.format = eFormatVectorOfUInt128;
279 }
280 else if (name.compare("set") == 0)
281 {
282 set_name.SetCString(value.c_str());
283 }
284 else if (name.compare("gcc") == 0)
285 {
286 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
287 }
288 else if (name.compare("dwarf") == 0)
289 {
290 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
291 }
292 else if (name.compare("generic") == 0)
293 {
294 if (value.compare("pc") == 0)
295 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
296 else if (value.compare("sp") == 0)
297 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
298 else if (value.compare("fp") == 0)
299 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
300 else if (value.compare("ra") == 0)
301 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
302 else if (value.compare("flags") == 0)
303 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000304 else if (value.find("arg") == 0)
305 {
306 if (value.size() == 4)
307 {
308 switch (value[3])
309 {
310 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
311 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
312 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
313 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
314 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
315 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
316 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
317 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
318 }
319 }
320 }
Chris Lattner24943d22010-06-08 16:52:24 +0000321 }
322 }
323
Jason Molenda53d96862010-06-11 23:44:18 +0000324 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000325 assert (reg_info.byte_size != 0);
326 reg_offset += reg_info.byte_size;
327 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
328 }
329 }
330 else
331 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000332 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000333 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000334 }
335 }
336
337 if (reg_num == 0)
338 {
339 // We didn't get anything. See if we are debugging ARM and fill with
340 // a hard coded register set until we can get an updated debugserver
341 // down on the devices.
Jason Molenda428b5502011-10-06 01:45:46 +0000342
343 if (!GetTarget().GetArchitecture().IsValid()
344 && m_gdb_comm.GetHostArchitecture().IsValid()
345 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm
346 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
347 {
Chris Lattner24943d22010-06-08 16:52:24 +0000348 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000349 }
350 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
351 {
352 m_register_info.HardcodeARMRegisters();
353 }
Chris Lattner24943d22010-06-08 16:52:24 +0000354 }
355 m_register_info.Finalize ();
356}
357
358Error
359ProcessGDBRemote::WillLaunch (Module* module)
360{
361 return WillLaunchOrAttach ();
362}
363
364Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000365ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000366{
367 return WillLaunchOrAttach ();
368}
369
370Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000371ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000372{
373 return WillLaunchOrAttach ();
374}
375
376Error
Greg Claytone71e2582011-02-04 01:58:07 +0000377ProcessGDBRemote::DoConnectRemote (const char *remote_url)
378{
379 Error error (WillLaunchOrAttach ());
380
381 if (error.Fail())
382 return error;
383
Greg Clayton180546b2011-04-30 01:09:13 +0000384 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000385
386 if (error.Fail())
387 return error;
388 StartAsyncThread ();
389
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000390 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000391 if (pid == LLDB_INVALID_PROCESS_ID)
392 {
393 // We don't have a valid process ID, so note that we are connected
394 // and could now request to launch or attach, or get remote process
395 // listings...
396 SetPrivateState (eStateConnected);
397 }
398 else
399 {
400 // We have a valid process
401 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000402 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000403 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000404 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000405 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000406 if (state == eStateStopped)
407 {
408 SetPrivateState (state);
409 }
410 else
411 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
412 }
413 else
414 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
415 }
416 return error;
417}
418
419Error
Chris Lattner24943d22010-06-08 16:52:24 +0000420ProcessGDBRemote::WillLaunchOrAttach ()
421{
422 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000423 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000424 return error;
425}
426
427//----------------------------------------------------------------------
428// Process Control
429//----------------------------------------------------------------------
430Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000431ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000432{
Greg Clayton4b407112010-09-30 21:49:03 +0000433 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000434
435 uint32_t launch_flags = launch_info.GetFlags().Get();
436 const char *stdin_path = NULL;
437 const char *stdout_path = NULL;
438 const char *stderr_path = NULL;
439 const char *working_dir = launch_info.GetWorkingDirectory();
440
441 const ProcessLaunchInfo::FileAction *file_action;
442 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
443 if (file_action)
444 {
445 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
446 stdin_path = file_action->GetPath();
447 }
448 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
449 if (file_action)
450 {
451 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
452 stdout_path = file_action->GetPath();
453 }
454 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
455 if (file_action)
456 {
457 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
458 stderr_path = file_action->GetPath();
459 }
460
Chris Lattner24943d22010-06-08 16:52:24 +0000461 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
462 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
463 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000464 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000465
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000466 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000467 if (object_file)
468 {
Chris Lattner24943d22010-06-08 16:52:24 +0000469 char host_port[128];
470 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000471 char connect_url[128];
472 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000473
Greg Claytona2f74232011-02-24 22:24:29 +0000474 // Make sure we aren't already connected?
475 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000476 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000477 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000478 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000479 {
Johnny Chenc143d622011-08-09 18:56:45 +0000480 if (log)
481 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000482 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000483 }
Chris Lattner24943d22010-06-08 16:52:24 +0000484
Greg Claytone71e2582011-02-04 01:58:07 +0000485 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000486 }
487
488 if (error.Success())
489 {
490 lldb_utility::PseudoTerminal pty;
491 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000492
493 // If the debugserver is local and we aren't disabling STDIO, lets use
494 // a pseudo terminal to instead of relying on the 'O' packets for stdio
495 // since 'O' packets can really slow down debugging if the inferior
496 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000497 PlatformSP platform_sp (m_target.GetPlatform());
498 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000499 {
500 const char *slave_name = NULL;
501 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000502 {
Greg Claytona2f74232011-02-24 22:24:29 +0000503 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
504 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000505 }
Greg Claytona2f74232011-02-24 22:24:29 +0000506 if (stdin_path == NULL)
507 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000508
Greg Claytona2f74232011-02-24 22:24:29 +0000509 if (stdout_path == NULL)
510 stdout_path = slave_name;
511
512 if (stderr_path == NULL)
513 stderr_path = slave_name;
514 }
515
Greg Claytonafb81862011-03-02 21:34:46 +0000516 // Set STDIN to /dev/null if we want STDIO disabled or if either
517 // STDOUT or STDERR have been set to something and STDIN hasn't
518 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000519 stdin_path = "/dev/null";
520
Greg Claytonafb81862011-03-02 21:34:46 +0000521 // Set STDOUT to /dev/null if we want STDIO disabled or if either
522 // STDIN or STDERR have been set to something and STDOUT hasn't
523 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000524 stdout_path = "/dev/null";
525
Greg Claytonafb81862011-03-02 21:34:46 +0000526 // Set STDERR to /dev/null if we want STDIO disabled or if either
527 // STDIN or STDOUT have been set to something and STDERR hasn't
528 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000529 stderr_path = "/dev/null";
530
531 if (stdin_path)
532 m_gdb_comm.SetSTDIN (stdin_path);
533 if (stdout_path)
534 m_gdb_comm.SetSTDOUT (stdout_path);
535 if (stderr_path)
536 m_gdb_comm.SetSTDERR (stderr_path);
537
538 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
539
Greg Claytona4582402011-05-08 04:53:50 +0000540 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000541
542 if (working_dir && working_dir[0])
543 {
544 m_gdb_comm.SetWorkingDir (working_dir);
545 }
546
547 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000548 const Args &environment = launch_info.GetEnvironmentEntries();
549 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000550 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000551 size_t num_environment_entries = environment.GetArgumentCount();
552 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000553 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000554 const char *env_entry = environment.GetArgumentAtIndex(i);
555 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000556 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000557 }
Greg Claytona2f74232011-02-24 22:24:29 +0000558 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000559
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000560 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000561 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000562 if (arg_packet_err == 0)
563 {
564 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000565 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000566 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000567 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000568 }
569 else
570 {
Greg Claytona2f74232011-02-24 22:24:29 +0000571 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000572 }
Greg Claytona2f74232011-02-24 22:24:29 +0000573 }
574 else
575 {
Greg Clayton9c236732011-10-26 00:56:27 +0000576 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000577 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000578
579 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000580
Greg Claytona2f74232011-02-24 22:24:29 +0000581 if (GetID() == LLDB_INVALID_PROCESS_ID)
582 {
Johnny Chenc143d622011-08-09 18:56:45 +0000583 if (log)
584 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000585 KillDebugserverProcess ();
586 return error;
587 }
588
Greg Clayton261a18b2011-06-02 22:22:38 +0000589 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000590 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000591 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000592
593 if (!disable_stdio)
594 {
595 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000596 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000597 }
Chris Lattner24943d22010-06-08 16:52:24 +0000598 }
599 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000600 else
601 {
Johnny Chenc143d622011-08-09 18:56:45 +0000602 if (log)
603 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000604 }
Chris Lattner24943d22010-06-08 16:52:24 +0000605 }
606 else
607 {
608 // Set our user ID to an invalid process ID.
609 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000610 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
611 exe_module->GetFileSpec().GetFilename().AsCString(),
612 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000613 }
Chris Lattner24943d22010-06-08 16:52:24 +0000614 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000615
Chris Lattner24943d22010-06-08 16:52:24 +0000616}
617
618
619Error
Greg Claytone71e2582011-02-04 01:58:07 +0000620ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000621{
622 Error error;
623 // Sleep and wait a bit for debugserver to start to listen...
624 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
625 if (conn_ap.get())
626 {
Chris Lattner24943d22010-06-08 16:52:24 +0000627 const uint32_t max_retry_count = 50;
628 uint32_t retry_count = 0;
629 while (!m_gdb_comm.IsConnected())
630 {
Greg Claytone71e2582011-02-04 01:58:07 +0000631 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000632 {
633 m_gdb_comm.SetConnection (conn_ap.release());
634 break;
635 }
636 retry_count++;
637
638 if (retry_count >= max_retry_count)
639 break;
640
641 usleep (100000);
642 }
643 }
644
645 if (!m_gdb_comm.IsConnected())
646 {
647 if (error.Success())
648 error.SetErrorString("not connected to remote gdb server");
649 return error;
650 }
651
Greg Clayton24bc5d92011-03-30 18:16:51 +0000652 // We always seem to be able to open a connection to a local port
653 // so we need to make sure we can then send data to it. If we can't
654 // then we aren't actually connected to anything, so try and do the
655 // handshake with the remote GDB server and make sure that goes
656 // alright.
657 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000658 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000659 m_gdb_comm.Disconnect();
660 if (error.Success())
661 error.SetErrorString("not connected to remote gdb server");
662 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000663 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000664 m_gdb_comm.ResetDiscoverableSettings();
665 m_gdb_comm.QueryNoAckModeSupported ();
666 m_gdb_comm.GetThreadSuffixSupported ();
667 m_gdb_comm.GetHostInfo ();
668 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000669 return error;
670}
671
672void
673ProcessGDBRemote::DidLaunchOrAttach ()
674{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000675 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
676 if (log)
677 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000678 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000679 {
680 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
681
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000682 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000683
Chris Lattner24943d22010-06-08 16:52:24 +0000684 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000685
Greg Claytoncb8977d2011-03-23 00:09:55 +0000686 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
687 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000688 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000689 ArchSpec &target_arch = GetTarget().GetArchitecture();
690
691 if (target_arch.IsValid())
692 {
693 // If the remote host is ARM and we have apple as the vendor, then
694 // ARM executables and shared libraries can have mixed ARM architectures.
695 // You can have an armv6 executable, and if the host is armv7, then the
696 // system will load the best possible architecture for all shared libraries
697 // it has, so we really need to take the remote host architecture as our
698 // defacto architecture in this case.
699
700 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
701 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
702 {
703 target_arch = gdb_remote_arch;
704 }
705 else
706 {
707 // Fill in what is missing in the triple
708 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
709 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000710 if (target_triple.getVendorName().size() == 0)
711 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000712 target_triple.setVendor (remote_triple.getVendor());
713
Greg Clayton2f085c62011-05-15 01:25:55 +0000714 if (target_triple.getOSName().size() == 0)
715 {
716 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000717
Greg Clayton2f085c62011-05-15 01:25:55 +0000718 if (target_triple.getEnvironmentName().size() == 0)
719 target_triple.setEnvironment (remote_triple.getEnvironment());
720 }
721 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000722 }
723 }
724 else
725 {
726 // The target doesn't have a valid architecture yet, set it from
727 // the architecture we got from the remote GDB server
728 target_arch = gdb_remote_arch;
729 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000730 }
Chris Lattner24943d22010-06-08 16:52:24 +0000731 }
732}
733
734void
735ProcessGDBRemote::DidLaunch ()
736{
737 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000738}
739
740Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000741ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000742{
743 Error error;
744 // Clear out and clean up from any current state
745 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000746 if (attach_pid != LLDB_INVALID_PROCESS_ID)
747 {
Greg Claytona2f74232011-02-24 22:24:29 +0000748 // Make sure we aren't already connected?
749 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000750 {
Greg Claytona2f74232011-02-24 22:24:29 +0000751 char host_port[128];
752 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
753 char connect_url[128];
754 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000755
Greg Claytonb72d0f02011-04-12 05:54:46 +0000756 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000757
758 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000759 {
Greg Claytona2f74232011-02-24 22:24:29 +0000760 const char *error_string = error.AsCString();
761 if (error_string == NULL)
762 error_string = "unable to launch " DEBUGSERVER_BASENAME;
763
764 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000765 }
Greg Claytona2f74232011-02-24 22:24:29 +0000766 else
767 {
768 error = ConnectToDebugserver (connect_url);
769 }
770 }
771
772 if (error.Success())
773 {
774 char packet[64];
775 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000776 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000777 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000778 }
779 }
Chris Lattner24943d22010-06-08 16:52:24 +0000780 return error;
781}
782
783size_t
784ProcessGDBRemote::AttachInputReaderCallback
785(
786 void *baton,
787 InputReader *reader,
788 lldb::InputReaderAction notification,
789 const char *bytes,
790 size_t bytes_len
791)
792{
793 if (notification == eInputReaderGotToken)
794 {
795 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
796 if (gdb_process->m_waiting_for_attach)
797 gdb_process->m_waiting_for_attach = false;
798 reader->SetIsDone(true);
799 return 1;
800 }
801 return 0;
802}
803
804Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000805ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000806{
807 Error error;
808 // Clear out and clean up from any current state
809 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000810
Chris Lattner24943d22010-06-08 16:52:24 +0000811 if (process_name && process_name[0])
812 {
Greg Claytona2f74232011-02-24 22:24:29 +0000813 // Make sure we aren't already connected?
814 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000815 {
Greg Claytona2f74232011-02-24 22:24:29 +0000816 char host_port[128];
817 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
818 char connect_url[128];
819 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
820
Greg Claytonb72d0f02011-04-12 05:54:46 +0000821 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000822 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000823 {
Greg Claytona2f74232011-02-24 22:24:29 +0000824 const char *error_string = error.AsCString();
825 if (error_string == NULL)
826 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000827
Greg Claytona2f74232011-02-24 22:24:29 +0000828 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000829 }
Greg Claytona2f74232011-02-24 22:24:29 +0000830 else
831 {
832 error = ConnectToDebugserver (connect_url);
833 }
834 }
835
836 if (error.Success())
837 {
838 StreamString packet;
839
840 if (wait_for_launch)
841 packet.PutCString("vAttachWait");
842 else
843 packet.PutCString("vAttachName");
844 packet.PutChar(';');
845 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
846
847 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
848
Chris Lattner24943d22010-06-08 16:52:24 +0000849 }
850 }
Chris Lattner24943d22010-06-08 16:52:24 +0000851 return error;
852}
853
Chris Lattner24943d22010-06-08 16:52:24 +0000854
855void
856ProcessGDBRemote::DidAttach ()
857{
Greg Claytone71e2582011-02-04 01:58:07 +0000858 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000859}
860
861Error
862ProcessGDBRemote::WillResume ()
863{
Greg Claytonc1f45872011-02-12 06:28:37 +0000864 m_continue_c_tids.clear();
865 m_continue_C_tids.clear();
866 m_continue_s_tids.clear();
867 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000868 return Error();
869}
870
871Error
872ProcessGDBRemote::DoResume ()
873{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000874 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000875 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
876 if (log)
877 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000878
879 Listener listener ("gdb-remote.resume-packet-sent");
880 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
881 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000882 StreamString continue_packet;
883 bool continue_packet_error = false;
884 if (m_gdb_comm.HasAnyVContSupport ())
885 {
886 continue_packet.PutCString ("vCont");
887
888 if (!m_continue_c_tids.empty())
889 {
890 if (m_gdb_comm.GetVContSupported ('c'))
891 {
892 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)
893 continue_packet.Printf(";c:%4.4x", *t_pos);
894 }
895 else
896 continue_packet_error = true;
897 }
898
899 if (!continue_packet_error && !m_continue_C_tids.empty())
900 {
901 if (m_gdb_comm.GetVContSupported ('C'))
902 {
903 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)
904 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
905 }
906 else
907 continue_packet_error = true;
908 }
Greg Claytonb749a262010-12-03 06:02:24 +0000909
Greg Claytonc1f45872011-02-12 06:28:37 +0000910 if (!continue_packet_error && !m_continue_s_tids.empty())
911 {
912 if (m_gdb_comm.GetVContSupported ('s'))
913 {
914 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)
915 continue_packet.Printf(";s:%4.4x", *t_pos);
916 }
917 else
918 continue_packet_error = true;
919 }
920
921 if (!continue_packet_error && !m_continue_S_tids.empty())
922 {
923 if (m_gdb_comm.GetVContSupported ('S'))
924 {
925 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)
926 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
927 }
928 else
929 continue_packet_error = true;
930 }
931
932 if (continue_packet_error)
933 continue_packet.GetString().clear();
934 }
935 else
936 continue_packet_error = true;
937
938 if (continue_packet_error)
939 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000940 // Either no vCont support, or we tried to use part of the vCont
941 // packet that wasn't supported by the remote GDB server.
942 // We need to try and make a simple packet that can do our continue
943 const size_t num_threads = GetThreadList().GetSize();
944 const size_t num_continue_c_tids = m_continue_c_tids.size();
945 const size_t num_continue_C_tids = m_continue_C_tids.size();
946 const size_t num_continue_s_tids = m_continue_s_tids.size();
947 const size_t num_continue_S_tids = m_continue_S_tids.size();
948 if (num_continue_c_tids > 0)
949 {
950 if (num_continue_c_tids == num_threads)
951 {
952 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000953 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000954 continue_packet.PutChar ('c');
955 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000956 }
957 else if (num_continue_c_tids == 1 &&
958 num_continue_C_tids == 0 &&
959 num_continue_s_tids == 0 &&
960 num_continue_S_tids == 0 )
961 {
962 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000963 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000964 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000965 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000966 }
967 }
968
Greg Claytonde1dd812011-06-24 03:21:43 +0000969 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000970 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000971 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
972 num_continue_C_tids > 0 &&
973 num_continue_s_tids == 0 &&
974 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000975 {
976 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000977 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +0000978 if (num_continue_C_tids > 1)
979 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000980 // More that one thread with a signal, yet we don't have
981 // vCont support and we are being asked to resume each
982 // thread with a signal, we need to make sure they are
983 // all the same signal, or we can't issue the continue
984 // accurately with the current support...
985 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +0000986 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000987 continue_packet_error = false;
988 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
989 {
990 if (m_continue_C_tids[i].second != continue_signo)
991 continue_packet_error = true;
992 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000993 }
Greg Claytonde1dd812011-06-24 03:21:43 +0000994 if (!continue_packet_error)
995 m_gdb_comm.SetCurrentThreadForRun (-1);
996 }
997 else
998 {
999 // Set the continue thread ID
1000 continue_packet_error = false;
1001 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001002 }
1003 if (!continue_packet_error)
1004 {
1005 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001006 continue_packet.Printf("C%2.2x", continue_signo);
1007 }
1008 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001009 }
1010
Greg Claytonde1dd812011-06-24 03:21:43 +00001011 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001012 {
1013 if (num_continue_s_tids == num_threads)
1014 {
1015 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001016 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001017 continue_packet.PutChar ('s');
1018 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001019 }
1020 else if (num_continue_c_tids == 0 &&
1021 num_continue_C_tids == 0 &&
1022 num_continue_s_tids == 1 &&
1023 num_continue_S_tids == 0 )
1024 {
1025 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001026 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001027 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001028 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001029 }
1030 }
1031
1032 if (!continue_packet_error && num_continue_S_tids > 0)
1033 {
1034 if (num_continue_S_tids == num_threads)
1035 {
1036 const int step_signo = m_continue_S_tids.front().second;
1037 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001038 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001039 if (num_continue_S_tids > 1)
1040 {
1041 for (size_t i=1; i<num_threads; ++i)
1042 {
1043 if (m_continue_S_tids[i].second != step_signo)
1044 continue_packet_error = true;
1045 }
1046 }
1047 if (!continue_packet_error)
1048 {
1049 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001050 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001051 continue_packet.Printf("S%2.2x", step_signo);
1052 }
1053 }
1054 else if (num_continue_c_tids == 0 &&
1055 num_continue_C_tids == 0 &&
1056 num_continue_s_tids == 0 &&
1057 num_continue_S_tids == 1 )
1058 {
1059 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001060 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001061 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001062 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001063 }
1064 }
1065 }
1066
1067 if (continue_packet_error)
1068 {
1069 error.SetErrorString ("can't make continue packet for this resume");
1070 }
1071 else
1072 {
1073 EventSP event_sp;
1074 TimeValue timeout;
1075 timeout = TimeValue::Now();
1076 timeout.OffsetWithSeconds (5);
1077 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1078
1079 if (listener.WaitForEvent (&timeout, event_sp) == false)
1080 error.SetErrorString("Resume timed out.");
1081 }
Greg Claytonb749a262010-12-03 06:02:24 +00001082 }
1083
Jim Ingham3ae449a2010-11-17 02:32:00 +00001084 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001085}
1086
Chris Lattner24943d22010-06-08 16:52:24 +00001087uint32_t
Greg Clayton37f962e2011-08-22 02:49:39 +00001088ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001089{
1090 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001091 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001092 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001093 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001094 // Update the thread list's stop id immediately so we don't recurse into this function.
Chris Lattner24943d22010-06-08 16:52:24 +00001095
Greg Clayton37f962e2011-08-22 02:49:39 +00001096 std::vector<lldb::tid_t> thread_ids;
1097 bool sequence_mutex_unavailable = false;
1098 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1099 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001100 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001101 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001102 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001103 tid_t tid = thread_ids[i];
1104 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1105 if (!thread_sp)
1106 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1107 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001108 }
Chris Lattner24943d22010-06-08 16:52:24 +00001109 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001110
1111 if (sequence_mutex_unavailable == false)
1112 SetThreadStopInfo (m_last_stop_packet);
1113 return new_thread_list.GetSize(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001114}
1115
1116
1117StateType
1118ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1119{
Greg Clayton261a18b2011-06-02 22:22:38 +00001120 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001121 const char stop_type = stop_packet.GetChar();
1122 switch (stop_type)
1123 {
1124 case 'T':
1125 case 'S':
1126 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001127 if (GetStopID() == 0)
1128 {
1129 // Our first stop, make sure we have a process ID, and also make
1130 // sure we know about our registers
1131 if (GetID() == LLDB_INVALID_PROCESS_ID)
1132 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001133 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001134 if (pid != LLDB_INVALID_PROCESS_ID)
1135 SetID (pid);
1136 }
1137 BuildDynamicRegisterInfo (true);
1138 }
Chris Lattner24943d22010-06-08 16:52:24 +00001139 // Stop with signal and thread info
1140 const uint8_t signo = stop_packet.GetHexU8();
1141 std::string name;
1142 std::string value;
1143 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001144 std::string reason;
1145 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001146 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001147 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001148 uint32_t tid = LLDB_INVALID_THREAD_ID;
1149 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1150 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001151 ThreadSP thread_sp;
1152
Chris Lattner24943d22010-06-08 16:52:24 +00001153 while (stop_packet.GetNameColonValue(name, value))
1154 {
1155 if (name.compare("metype") == 0)
1156 {
1157 // exception type in big endian hex
1158 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1159 }
1160 else if (name.compare("mecount") == 0)
1161 {
1162 // exception count in big endian hex
1163 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1164 }
1165 else if (name.compare("medata") == 0)
1166 {
1167 // exception data in big endian hex
1168 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1169 }
1170 else if (name.compare("thread") == 0)
1171 {
1172 // thread in big endian hex
1173 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001174 // m_thread_list does have its own mutex, but we need to
1175 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1176 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001177 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001178 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001179 if (!thread_sp)
1180 {
1181 // Create the thread if we need to
1182 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1183 m_thread_list.AddThread(thread_sp);
1184 }
Chris Lattner24943d22010-06-08 16:52:24 +00001185 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001186 else if (name.compare("hexname") == 0)
1187 {
1188 StringExtractor name_extractor;
1189 // Swap "value" over into "name_extractor"
1190 name_extractor.GetStringRef().swap(value);
1191 // Now convert the HEX bytes into a string value
1192 name_extractor.GetHexByteString (value);
1193 thread_name.swap (value);
1194 }
Chris Lattner24943d22010-06-08 16:52:24 +00001195 else if (name.compare("name") == 0)
1196 {
1197 thread_name.swap (value);
1198 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001199 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001200 {
1201 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1202 }
Greg Clayton65611552011-06-04 01:26:29 +00001203 else if (name.compare("reason") == 0)
1204 {
1205 reason.swap(value);
1206 }
1207 else if (name.compare("description") == 0)
1208 {
1209 StringExtractor desc_extractor;
1210 // Swap "value" over into "name_extractor"
1211 desc_extractor.GetStringRef().swap(value);
1212 // Now convert the HEX bytes into a string value
1213 desc_extractor.GetHexByteString (thread_name);
1214 }
Greg Claytona875b642011-01-09 21:07:35 +00001215 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1216 {
1217 // We have a register number that contains an expedited
1218 // register value. Lets supply this register to our thread
1219 // so it won't have to go and read it.
1220 if (thread_sp)
1221 {
1222 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1223
1224 if (reg != UINT32_MAX)
1225 {
1226 StringExtractor reg_value_extractor;
1227 // Swap "value" over into "reg_value_extractor"
1228 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001229 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1230 {
1231 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1232 name.c_str(),
1233 reg,
1234 reg,
1235 reg_value_extractor.GetStringRef().c_str(),
1236 stop_packet.GetStringRef().c_str());
1237 }
Greg Claytona875b642011-01-09 21:07:35 +00001238 }
1239 }
1240 }
Chris Lattner24943d22010-06-08 16:52:24 +00001241 }
Chris Lattner24943d22010-06-08 16:52:24 +00001242
1243 if (thread_sp)
1244 {
1245 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1246
1247 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001248 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001249 if (exc_type != 0)
1250 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001251 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001252
1253 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1254 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001255 exc_data_size,
1256 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001257 exc_data_size >= 2 ? exc_data[1] : 0,
1258 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001259 }
Greg Clayton65611552011-06-04 01:26:29 +00001260 else
Chris Lattner24943d22010-06-08 16:52:24 +00001261 {
Greg Clayton65611552011-06-04 01:26:29 +00001262 bool handled = false;
1263 if (!reason.empty())
1264 {
1265 if (reason.compare("trace") == 0)
1266 {
1267 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1268 handled = true;
1269 }
1270 else if (reason.compare("breakpoint") == 0)
1271 {
1272 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1273 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1274 if (bp_site_sp)
1275 {
1276 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1277 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1278 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1279 if (bp_site_sp->ValidForThisThread (gdb_thread))
1280 {
1281 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1282 handled = true;
1283 }
1284 }
1285
1286 if (!handled)
1287 {
1288 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1289 }
1290 }
1291 else if (reason.compare("trap") == 0)
1292 {
1293 // Let the trap just use the standard signal stop reason below...
1294 }
1295 else if (reason.compare("watchpoint") == 0)
1296 {
1297 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1298 // TODO: locate the watchpoint somehow...
1299 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1300 handled = true;
1301 }
1302 else if (reason.compare("exception") == 0)
1303 {
1304 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1305 handled = true;
1306 }
1307 }
1308
1309 if (signo)
1310 {
1311 if (signo == SIGTRAP)
1312 {
1313 // Currently we are going to assume SIGTRAP means we are either
1314 // hitting a breakpoint or hardware single stepping.
1315 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1316 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1317 if (bp_site_sp)
1318 {
1319 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1320 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1321 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1322 if (bp_site_sp->ValidForThisThread (gdb_thread))
1323 {
1324 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1325 handled = true;
1326 }
1327 }
1328 if (!handled)
1329 {
1330 // TODO: check for breakpoint or trap opcode in case there is a hard
1331 // coded software trap
1332 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1333 handled = true;
1334 }
1335 }
1336 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001337 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001338 }
1339 else
1340 {
Greg Clayton643ee732010-08-04 01:40:35 +00001341 StopInfoSP invalid_stop_info_sp;
1342 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001343 }
Greg Clayton65611552011-06-04 01:26:29 +00001344
1345 if (!description.empty())
1346 {
1347 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1348 if (stop_info_sp)
1349 {
1350 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001351 }
Greg Clayton65611552011-06-04 01:26:29 +00001352 else
1353 {
1354 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1355 }
1356 }
1357 }
Chris Lattner24943d22010-06-08 16:52:24 +00001358 }
1359 return eStateStopped;
1360 }
1361 break;
1362
1363 case 'W':
1364 // process exited
1365 return eStateExited;
1366
1367 default:
1368 break;
1369 }
1370 return eStateInvalid;
1371}
1372
1373void
1374ProcessGDBRemote::RefreshStateAfterStop ()
1375{
Chris Lattner24943d22010-06-08 16:52:24 +00001376 // Let all threads recover from stopping and do any clean up based
1377 // on the previous thread state (if any).
1378 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001379 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001380}
1381
1382Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001383ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001384{
1385 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001386
Greg Claytona4881d02011-01-22 07:12:45 +00001387 bool timed_out = false;
1388 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001389
1390 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001391 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001392 // We are being asked to halt during an attach. We need to just close
1393 // our file handle and debugserver will go away, and we can be done...
1394 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001395 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001396 else
1397 {
1398 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1399 {
1400 if (timed_out)
1401 error.SetErrorString("timed out sending interrupt packet");
1402 else
1403 error.SetErrorString("unknown error sending interrupt packet");
1404 }
1405 }
Chris Lattner24943d22010-06-08 16:52:24 +00001406 return error;
1407}
1408
1409Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001410ProcessGDBRemote::InterruptIfRunning
1411(
1412 bool discard_thread_plans,
1413 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001414 EventSP &stop_event_sp
1415)
Chris Lattner24943d22010-06-08 16:52:24 +00001416{
1417 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001418
Greg Clayton2860ba92011-01-23 19:58:49 +00001419 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1420
Greg Clayton68ca8232011-01-25 02:58:48 +00001421 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001422 const bool is_running = m_gdb_comm.IsRunning();
1423 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001424 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001425 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001426 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001427 is_running);
1428
Greg Clayton2860ba92011-01-23 19:58:49 +00001429 if (discard_thread_plans)
1430 {
1431 if (log)
1432 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1433 m_thread_list.DiscardThreadPlans();
1434 }
1435 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001436 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001437 if (catch_stop_event)
1438 {
1439 if (log)
1440 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1441 PausePrivateStateThread();
1442 paused_private_state_thread = true;
1443 }
1444
Greg Clayton4fb400f2010-09-27 21:07:38 +00001445 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001446 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001447 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001448
Greg Clayton72e1c782011-01-22 23:43:18 +00001449 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001450 {
1451 if (timed_out)
1452 error.SetErrorString("timed out sending interrupt packet");
1453 else
1454 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001455 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001456 ResumePrivateStateThread();
1457 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001458 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001459
Greg Clayton72e1c782011-01-22 23:43:18 +00001460 if (catch_stop_event)
1461 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001462 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001463 TimeValue timeout_time;
1464 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001465 timeout_time.OffsetWithSeconds(5);
1466 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001467
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001468 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001469 if (log)
1470 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001471
Greg Clayton2860ba92011-01-23 19:58:49 +00001472 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001473 error.SetErrorString("unable to verify target stopped");
1474 }
1475
Greg Clayton68ca8232011-01-25 02:58:48 +00001476 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001477 {
1478 if (log)
1479 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001480 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001481 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001482 }
Chris Lattner24943d22010-06-08 16:52:24 +00001483 return error;
1484}
1485
Greg Clayton4fb400f2010-09-27 21:07:38 +00001486Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001487ProcessGDBRemote::WillDetach ()
1488{
Greg Clayton2860ba92011-01-23 19:58:49 +00001489 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1490 if (log)
1491 log->Printf ("ProcessGDBRemote::WillDetach()");
1492
Greg Clayton72e1c782011-01-22 23:43:18 +00001493 bool discard_thread_plans = true;
1494 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001495 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001496 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001497}
1498
1499Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001500ProcessGDBRemote::DoDetach()
1501{
1502 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001503 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001504 if (log)
1505 log->Printf ("ProcessGDBRemote::DoDetach()");
1506
1507 DisableAllBreakpointSites ();
1508
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001509 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001510
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001511 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1512 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001513 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001514 if (response_size)
1515 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1516 else
1517 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001518 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001519 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001520 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001521
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001522 SetPrivateState (eStateDetached);
1523 ResumePrivateStateThread();
1524
1525 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001526 return error;
1527}
Chris Lattner24943d22010-06-08 16:52:24 +00001528
1529Error
1530ProcessGDBRemote::DoDestroy ()
1531{
1532 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001533 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001534 if (log)
1535 log->Printf ("ProcessGDBRemote::DoDestroy()");
1536
1537 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001538 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001539 {
Jim Ingham8226e942011-10-28 01:11:35 +00001540 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001541 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001542
1543 StringExtractorGDBRemote response;
1544 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001545 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001546 {
1547 char packet_cmd = response.GetChar(0);
1548
1549 if (packet_cmd == 'W' || packet_cmd == 'X')
1550 {
1551 m_last_stop_packet = response;
1552 SetExitStatus(response.GetHexU8(), NULL);
1553 }
1554 }
1555 else
1556 {
1557 SetExitStatus(SIGABRT, NULL);
1558 //error.SetErrorString("kill packet failed");
1559 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001560 }
1561 }
Chris Lattner24943d22010-06-08 16:52:24 +00001562 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001563 KillDebugserverProcess ();
1564 return error;
1565}
1566
Chris Lattner24943d22010-06-08 16:52:24 +00001567//------------------------------------------------------------------
1568// Process Queries
1569//------------------------------------------------------------------
1570
1571bool
1572ProcessGDBRemote::IsAlive ()
1573{
Greg Clayton58e844b2010-12-08 05:08:21 +00001574 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001575}
1576
1577addr_t
1578ProcessGDBRemote::GetImageInfoAddress()
1579{
1580 if (!m_gdb_comm.IsRunning())
1581 {
1582 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001583 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001584 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001585 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001586 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1587 }
1588 }
1589 return LLDB_INVALID_ADDRESS;
1590}
1591
Chris Lattner24943d22010-06-08 16:52:24 +00001592//------------------------------------------------------------------
1593// Process Memory
1594//------------------------------------------------------------------
1595size_t
1596ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1597{
1598 if (size > m_max_memory_size)
1599 {
1600 // Keep memory read sizes down to a sane limit. This function will be
1601 // called multiple times in order to complete the task by
1602 // lldb_private::Process so it is ok to do this.
1603 size = m_max_memory_size;
1604 }
1605
1606 char packet[64];
1607 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1608 assert (packet_len + 1 < sizeof(packet));
1609 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001610 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001611 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001612 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001613 {
1614 error.Clear();
1615 return response.GetHexBytes(buf, size, '\xdd');
1616 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001617 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001618 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001619 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001620 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1621 else
1622 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1623 }
1624 else
1625 {
1626 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1627 }
1628 return 0;
1629}
1630
1631size_t
1632ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1633{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001634 if (size > m_max_memory_size)
1635 {
1636 // Keep memory read sizes down to a sane limit. This function will be
1637 // called multiple times in order to complete the task by
1638 // lldb_private::Process so it is ok to do this.
1639 size = m_max_memory_size;
1640 }
1641
Chris Lattner24943d22010-06-08 16:52:24 +00001642 StreamString packet;
1643 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001644 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001645 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001646 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001647 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001648 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001649 {
1650 error.Clear();
1651 return size;
1652 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001653 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001654 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001655 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001656 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1657 else
1658 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1659 }
1660 else
1661 {
1662 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1663 }
1664 return 0;
1665}
1666
1667lldb::addr_t
1668ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1669{
Greg Clayton989816b2011-05-14 01:50:35 +00001670 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1671
Greg Clayton2f085c62011-05-15 01:25:55 +00001672 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001673 switch (supported)
1674 {
1675 case eLazyBoolCalculate:
1676 case eLazyBoolYes:
1677 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1678 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1679 return allocated_addr;
1680
1681 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001682 // Call mmap() to create memory in the inferior..
1683 unsigned prot = 0;
1684 if (permissions & lldb::ePermissionsReadable)
1685 prot |= eMmapProtRead;
1686 if (permissions & lldb::ePermissionsWritable)
1687 prot |= eMmapProtWrite;
1688 if (permissions & lldb::ePermissionsExecutable)
1689 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001690
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001691 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1692 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1693 m_addr_to_mmap_size[allocated_addr] = size;
1694 else
1695 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001696 break;
1697 }
1698
Chris Lattner24943d22010-06-08 16:52:24 +00001699 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001700 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001701 else
1702 error.Clear();
1703 return allocated_addr;
1704}
1705
1706Error
Greg Claytona9385532011-11-18 07:03:08 +00001707ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1708 MemoryRegionInfo &region_info)
1709{
1710
1711 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1712 return error;
1713}
1714
1715Error
Chris Lattner24943d22010-06-08 16:52:24 +00001716ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1717{
1718 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001719 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1720
1721 switch (supported)
1722 {
1723 case eLazyBoolCalculate:
1724 // We should never be deallocating memory without allocating memory
1725 // first so we should never get eLazyBoolCalculate
1726 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1727 break;
1728
1729 case eLazyBoolYes:
1730 if (!m_gdb_comm.DeallocateMemory (addr))
1731 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1732 break;
1733
1734 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001735 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001736 {
1737 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001738 if (pos != m_addr_to_mmap_size.end() &&
1739 InferiorCallMunmap(this, addr, pos->second))
1740 m_addr_to_mmap_size.erase (pos);
1741 else
1742 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001743 }
1744 break;
1745 }
1746
Chris Lattner24943d22010-06-08 16:52:24 +00001747 return error;
1748}
1749
1750
1751//------------------------------------------------------------------
1752// Process STDIO
1753//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001754size_t
1755ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1756{
1757 if (m_stdio_communication.IsConnected())
1758 {
1759 ConnectionStatus status;
1760 m_stdio_communication.Write(src, src_len, status, NULL);
1761 }
1762 return 0;
1763}
1764
1765Error
1766ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1767{
1768 Error error;
1769 assert (bp_site != NULL);
1770
Greg Claytone005f2c2010-11-06 01:53:30 +00001771 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001772 user_id_t site_id = bp_site->GetID();
1773 const addr_t addr = bp_site->GetLoadAddress();
1774 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001775 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001776
1777 if (bp_site->IsEnabled())
1778 {
1779 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001780 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001781 return error;
1782 }
1783 else
1784 {
1785 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1786
1787 if (bp_site->HardwarePreferred())
1788 {
1789 // Try and set hardware breakpoint, and if that fails, fall through
1790 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001791 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001792 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001793 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001794 {
1795 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001796 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001797 return error;
1798 }
Chris Lattner24943d22010-06-08 16:52:24 +00001799 }
1800 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001801
1802 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001803 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001804 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1805 {
1806 bp_site->SetEnabled(true);
1807 bp_site->SetType (BreakpointSite::eExternal);
1808 return error;
1809 }
Chris Lattner24943d22010-06-08 16:52:24 +00001810 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001811
1812 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001813 }
1814
1815 if (log)
1816 {
1817 const char *err_string = error.AsCString();
1818 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1819 bp_site->GetLoadAddress(),
1820 err_string ? err_string : "NULL");
1821 }
1822 // We shouldn't reach here on a successful breakpoint enable...
1823 if (error.Success())
1824 error.SetErrorToGenericError();
1825 return error;
1826}
1827
1828Error
1829ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1830{
1831 Error error;
1832 assert (bp_site != NULL);
1833 addr_t addr = bp_site->GetLoadAddress();
1834 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001835 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001836 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001837 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001838
1839 if (bp_site->IsEnabled())
1840 {
1841 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1842
Greg Claytonb72d0f02011-04-12 05:54:46 +00001843 BreakpointSite::Type bp_type = bp_site->GetType();
1844 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001845 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001846 case BreakpointSite::eSoftware:
1847 error = DisableSoftwareBreakpoint (bp_site);
1848 break;
1849
1850 case BreakpointSite::eHardware:
1851 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1852 error.SetErrorToGenericError();
1853 break;
1854
1855 case BreakpointSite::eExternal:
1856 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1857 error.SetErrorToGenericError();
1858 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001859 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001860 if (error.Success())
1861 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001862 }
1863 else
1864 {
1865 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001866 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001867 return error;
1868 }
1869
1870 if (error.Success())
1871 error.SetErrorToGenericError();
1872 return error;
1873}
1874
Johnny Chen21900fb2011-09-06 22:38:36 +00001875// Pre-requisite: wp != NULL.
1876static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00001877GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00001878{
1879 assert(wp);
1880 bool watch_read = wp->WatchpointRead();
1881 bool watch_write = wp->WatchpointWrite();
1882
1883 // watch_read and watch_write cannot both be false.
1884 assert(watch_read || watch_write);
1885 if (watch_read && watch_write)
1886 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001887 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00001888 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00001889 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00001890 return eWatchpointWrite;
1891}
1892
Chris Lattner24943d22010-06-08 16:52:24 +00001893Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001894ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001895{
1896 Error error;
1897 if (wp)
1898 {
1899 user_id_t watchID = wp->GetID();
1900 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001901 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001902 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001903 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00001904 if (wp->IsEnabled())
1905 {
1906 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001907 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001908 return error;
1909 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001910
1911 GDBStoppointType type = GetGDBStoppointType(wp);
1912 // Pass down an appropriate z/Z packet...
1913 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00001914 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001915 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
1916 {
1917 wp->SetEnabled(true);
1918 return error;
1919 }
1920 else
1921 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001922 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001923 else
1924 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00001925 }
1926 else
1927 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001928 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001929 }
1930 if (error.Success())
1931 error.SetErrorToGenericError();
1932 return error;
1933}
1934
1935Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001936ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001937{
1938 Error error;
1939 if (wp)
1940 {
1941 user_id_t watchID = wp->GetID();
1942
Greg Claytone005f2c2010-11-06 01:53:30 +00001943 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001944
1945 addr_t addr = wp->GetLoadAddress();
1946 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001947 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001948
Johnny Chen21900fb2011-09-06 22:38:36 +00001949 if (!wp->IsEnabled())
1950 {
1951 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001952 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00001953 return error;
1954 }
1955
Chris Lattner24943d22010-06-08 16:52:24 +00001956 if (wp->IsHardware())
1957 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001958 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00001959 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00001960 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
1961 {
1962 wp->SetEnabled(false);
1963 return error;
1964 }
1965 else
1966 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001967 }
1968 // TODO: clear software watchpoints if we implement them
1969 }
1970 else
1971 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001972 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001973 }
1974 if (error.Success())
1975 error.SetErrorToGenericError();
1976 return error;
1977}
1978
1979void
1980ProcessGDBRemote::Clear()
1981{
1982 m_flags = 0;
1983 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001984}
1985
1986Error
1987ProcessGDBRemote::DoSignal (int signo)
1988{
1989 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001990 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001991 if (log)
1992 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1993
1994 if (!m_gdb_comm.SendAsyncSignal (signo))
1995 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1996 return error;
1997}
1998
Chris Lattner24943d22010-06-08 16:52:24 +00001999Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002000ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner24943d22010-06-08 16:52:24 +00002001{
2002 Error error;
2003 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2004 {
2005 // If we locate debugserver, keep that located version around
2006 static FileSpec g_debugserver_file_spec;
2007
Greg Claytonb72d0f02011-04-12 05:54:46 +00002008 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002009 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002010 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002011
2012 // Always check to see if we have an environment override for the path
2013 // to the debugserver to use and use it if we do.
2014 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2015 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002016 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002017 else
2018 debugserver_file_spec = g_debugserver_file_spec;
2019 bool debugserver_exists = debugserver_file_spec.Exists();
2020 if (!debugserver_exists)
2021 {
2022 // The debugserver binary is in the LLDB.framework/Resources
2023 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002024 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002025 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002026 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002027 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002028 if (debugserver_exists)
2029 {
2030 g_debugserver_file_spec = debugserver_file_spec;
2031 }
2032 else
2033 {
2034 g_debugserver_file_spec.Clear();
2035 debugserver_file_spec.Clear();
2036 }
Chris Lattner24943d22010-06-08 16:52:24 +00002037 }
2038 }
2039
2040 if (debugserver_exists)
2041 {
2042 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2043
2044 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002045
Greg Claytone005f2c2010-11-06 01:53:30 +00002046 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002047
Greg Claytonb72d0f02011-04-12 05:54:46 +00002048 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002049 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002050
Chris Lattner24943d22010-06-08 16:52:24 +00002051 // Start args with "debugserver /file/path -r --"
2052 debugserver_args.AppendArgument(debugserver_path);
2053 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002054 // use native registers, not the GDB registers
2055 debugserver_args.AppendArgument("--native-regs");
2056 // make debugserver run in its own session so signals generated by
2057 // special terminal key sequences (^C) don't affect debugserver
2058 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002059
Chris Lattner24943d22010-06-08 16:52:24 +00002060 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2061 if (env_debugserver_log_file)
2062 {
2063 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2064 debugserver_args.AppendArgument(arg_cstr);
2065 }
2066
2067 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2068 if (env_debugserver_log_flags)
2069 {
2070 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2071 debugserver_args.AppendArgument(arg_cstr);
2072 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002073// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002074// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002075
Greg Claytonb72d0f02011-04-12 05:54:46 +00002076 // We currently send down all arguments, attach pids, or attach
2077 // process names in dedicated GDB server packets, so we don't need
2078 // to pass them as arguments. This is currently because of all the
2079 // things we need to setup prior to launching: the environment,
2080 // current working dir, file actions, etc.
2081#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002082 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002083 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002084 {
Greg Claytona2f74232011-02-24 22:24:29 +00002085 // Terminate the debugserver args so we can now append the inferior args
2086 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002087
Greg Claytona2f74232011-02-24 22:24:29 +00002088 for (int i = 0; inferior_argv[i] != NULL; ++i)
2089 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002090 }
2091 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2092 {
2093 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2094 debugserver_args.AppendArgument (arg_cstr);
2095 }
2096 else if (attach_name && attach_name[0])
2097 {
2098 if (wait_for_launch)
2099 debugserver_args.AppendArgument ("--waitfor");
2100 else
2101 debugserver_args.AppendArgument ("--attach");
2102 debugserver_args.AppendArgument (attach_name);
2103 }
Chris Lattner24943d22010-06-08 16:52:24 +00002104#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002105
2106 ProcessLaunchInfo::FileAction file_action;
2107
2108 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2109 // to "/dev/null" if we run into any problems.
2110 file_action.Close (STDIN_FILENO);
2111 launch_info.AppendFileAction (file_action);
2112 file_action.Close (STDOUT_FILENO);
2113 launch_info.AppendFileAction (file_action);
2114 file_action.Close (STDERR_FILENO);
2115 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002116
2117 if (log)
2118 {
2119 StreamString strm;
2120 debugserver_args.Dump (&strm);
2121 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2122 }
2123
Greg Clayton1c4642c2011-11-16 05:37:56 +00002124 launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2125
Greg Claytonb72d0f02011-04-12 05:54:46 +00002126 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002127
Greg Claytonb72d0f02011-04-12 05:54:46 +00002128 if (error.Success ())
2129 m_debugserver_pid = launch_info.GetProcessID();
2130 else
Chris Lattner24943d22010-06-08 16:52:24 +00002131 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2132
2133 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002134 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002135 }
2136 else
2137 {
Greg Clayton9c236732011-10-26 00:56:27 +00002138 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002139 }
2140
2141 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2142 StartAsyncThread ();
2143 }
2144 return error;
2145}
2146
2147bool
2148ProcessGDBRemote::MonitorDebugserverProcess
2149(
2150 void *callback_baton,
2151 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002152 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002153 int signo, // Zero for no signal
2154 int exit_status // Exit value of process if signal is zero
2155)
2156{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002157 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2158 // and might not exist anymore, so we need to carefully try to get the
2159 // target for this process first since we have a race condition when
2160 // we are done running between getting the notice that the inferior
2161 // process has died and the debugserver that was debugging this process.
2162 // In our test suite, we are also continually running process after
2163 // process, so we must be very careful to make sure:
2164 // 1 - process object hasn't been deleted already
2165 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002166
2167 // "debugserver_pid" argument passed in is the process ID for
2168 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002169 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002170
Greg Clayton75ccf502010-08-21 02:22:51 +00002171 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002172
Greg Clayton1c4642c2011-11-16 05:37:56 +00002173 // Get a shared pointer to the target that has a matching process pointer.
2174 // This target could be gone, or the target could already have a new process
2175 // object inside of it
2176 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2177
Greg Clayton72e1c782011-01-22 23:43:18 +00002178 if (log)
2179 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2180
Greg Clayton1c4642c2011-11-16 05:37:56 +00002181 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002182 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002183 // We found a process in a target that matches, but another thread
2184 // might be in the process of launching a new process that will
2185 // soon replace it, so get a shared pointer to the process so we
2186 // can keep it alive.
2187 ProcessSP process_sp (target_sp->GetProcessSP());
2188 // Now we have a shared pointer to the process that can't go away on us
2189 // so we now make sure it was the same as the one passed in, and also make
2190 // sure that our previous "process *" didn't get deleted and have a new
2191 // "process *" created in its place with the same pointer. To verify this
2192 // we make sure the process has our debugserver process ID. If we pass all
2193 // of these tests, then we are sure that this process is the one we were
2194 // looking for.
2195 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002196 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002197 // Sleep for a half a second to make sure our inferior process has
2198 // time to set its exit status before we set it incorrectly when
2199 // both the debugserver and the inferior process shut down.
2200 usleep (500000);
2201 // If our process hasn't yet exited, debugserver might have died.
2202 // If the process did exit, the we are reaping it.
2203 const StateType state = process->GetState();
2204
2205 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2206 state != eStateInvalid &&
2207 state != eStateUnloaded &&
2208 state != eStateExited &&
2209 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002210 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002211 char error_str[1024];
2212 if (signo)
2213 {
2214 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2215 if (signal_cstr)
2216 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2217 else
2218 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2219 }
Chris Lattner24943d22010-06-08 16:52:24 +00002220 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002221 {
2222 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2223 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002224
Greg Clayton1c4642c2011-11-16 05:37:56 +00002225 process->SetExitStatus (-1, error_str);
2226 }
2227 // Debugserver has exited we need to let our ProcessGDBRemote
2228 // know that it no longer has a debugserver instance
2229 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002230 }
Chris Lattner24943d22010-06-08 16:52:24 +00002231 }
2232 return true;
2233}
2234
2235void
2236ProcessGDBRemote::KillDebugserverProcess ()
2237{
2238 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2239 {
2240 ::kill (m_debugserver_pid, SIGINT);
2241 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2242 }
2243}
2244
2245void
2246ProcessGDBRemote::Initialize()
2247{
2248 static bool g_initialized = false;
2249
2250 if (g_initialized == false)
2251 {
2252 g_initialized = true;
2253 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2254 GetPluginDescriptionStatic(),
2255 CreateInstance);
2256
2257 Log::Callbacks log_callbacks = {
2258 ProcessGDBRemoteLog::DisableLog,
2259 ProcessGDBRemoteLog::EnableLog,
2260 ProcessGDBRemoteLog::ListLogCategories
2261 };
2262
2263 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2264 }
2265}
2266
2267bool
Chris Lattner24943d22010-06-08 16:52:24 +00002268ProcessGDBRemote::StartAsyncThread ()
2269{
Greg Claytone005f2c2010-11-06 01:53:30 +00002270 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002271
2272 if (log)
2273 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2274
2275 // Create a thread that watches our internal state and controls which
2276 // events make it to clients (into the DCProcess event queue).
2277 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002278 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002279}
2280
2281void
2282ProcessGDBRemote::StopAsyncThread ()
2283{
Greg Claytone005f2c2010-11-06 01:53:30 +00002284 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002285
2286 if (log)
2287 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2288
2289 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002290
2291 // This will shut down the async thread.
2292 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002293
2294 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002295 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002296 {
2297 Host::ThreadJoin (m_async_thread, NULL, NULL);
2298 }
2299}
2300
2301
2302void *
2303ProcessGDBRemote::AsyncThread (void *arg)
2304{
2305 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2306
Greg Claytone005f2c2010-11-06 01:53:30 +00002307 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002308 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002309 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002310
2311 Listener listener ("ProcessGDBRemote::AsyncThread");
2312 EventSP event_sp;
2313 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2314 eBroadcastBitAsyncThreadShouldExit;
2315
2316 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2317 {
Greg Claytona2f74232011-02-24 22:24:29 +00002318 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2319
Chris Lattner24943d22010-06-08 16:52:24 +00002320 bool done = false;
2321 while (!done)
2322 {
2323 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002324 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002325 if (listener.WaitForEvent (NULL, event_sp))
2326 {
2327 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002328 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002329 {
Greg Claytona2f74232011-02-24 22:24:29 +00002330 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002331 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002332
Greg Claytona2f74232011-02-24 22:24:29 +00002333 switch (event_type)
2334 {
2335 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002336 {
Greg Claytona2f74232011-02-24 22:24:29 +00002337 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002338
Greg Claytona2f74232011-02-24 22:24:29 +00002339 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002340 {
Greg Claytona2f74232011-02-24 22:24:29 +00002341 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2342 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2343 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002344 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002345
Greg Claytona2f74232011-02-24 22:24:29 +00002346 if (::strstr (continue_cstr, "vAttach") == NULL)
2347 process->SetPrivateState(eStateRunning);
2348 StringExtractorGDBRemote response;
2349 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002350
Greg Claytona2f74232011-02-24 22:24:29 +00002351 switch (stop_state)
2352 {
2353 case eStateStopped:
2354 case eStateCrashed:
2355 case eStateSuspended:
2356 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002357 process->SetPrivateState (stop_state);
2358 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002359
Greg Claytona2f74232011-02-24 22:24:29 +00002360 case eStateExited:
2361 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002362 response.SetFilePos(1);
2363 process->SetExitStatus(response.GetHexU8(), NULL);
2364 done = true;
2365 break;
2366
2367 case eStateInvalid:
2368 process->SetExitStatus(-1, "lost connection");
2369 break;
2370
2371 default:
2372 process->SetPrivateState (stop_state);
2373 break;
2374 }
Chris Lattner24943d22010-06-08 16:52:24 +00002375 }
2376 }
Greg Claytona2f74232011-02-24 22:24:29 +00002377 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002378
Greg Claytona2f74232011-02-24 22:24:29 +00002379 case eBroadcastBitAsyncThreadShouldExit:
2380 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002381 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002382 done = true;
2383 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002384
Greg Claytona2f74232011-02-24 22:24:29 +00002385 default:
2386 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002387 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Claytona2f74232011-02-24 22:24:29 +00002388 done = true;
2389 break;
2390 }
2391 }
2392 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2393 {
2394 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2395 {
2396 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002397 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002398 }
Chris Lattner24943d22010-06-08 16:52:24 +00002399 }
2400 }
2401 else
2402 {
2403 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002404 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002405 done = true;
2406 }
2407 }
2408 }
2409
2410 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002411 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002412
2413 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2414 return NULL;
2415}
2416
Chris Lattner24943d22010-06-08 16:52:24 +00002417const char *
2418ProcessGDBRemote::GetDispatchQueueNameForThread
2419(
2420 addr_t thread_dispatch_qaddr,
2421 std::string &dispatch_queue_name
2422)
2423{
2424 dispatch_queue_name.clear();
2425 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2426 {
2427 // Cache the dispatch_queue_offsets_addr value so we don't always have
2428 // to look it up
2429 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2430 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002431 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2432 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002433 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002434 if (module_sp)
2435 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2436
2437 if (dispatch_queue_offsets_symbol == NULL)
2438 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002439 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002440 if (module_sp)
2441 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2442 }
Chris Lattner24943d22010-06-08 16:52:24 +00002443 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002444 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002445
2446 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2447 return NULL;
2448 }
2449
2450 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002451 DataExtractor data (memory_buffer,
2452 sizeof(memory_buffer),
2453 m_target.GetArchitecture().GetByteOrder(),
2454 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002455
2456 // Excerpt from src/queue_private.h
2457 struct dispatch_queue_offsets_s
2458 {
2459 uint16_t dqo_version;
2460 uint16_t dqo_label;
2461 uint16_t dqo_label_size;
2462 } dispatch_queue_offsets;
2463
2464
2465 Error error;
2466 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2467 {
2468 uint32_t data_offset = 0;
2469 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2470 {
2471 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2472 {
2473 data_offset = 0;
2474 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2475 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2476 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2477 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2478 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2479 dispatch_queue_name.erase (bytes_read);
2480 }
2481 }
2482 }
2483 }
2484 if (dispatch_queue_name.empty())
2485 return NULL;
2486 return dispatch_queue_name.c_str();
2487}
2488
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002489//uint32_t
2490//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2491//{
2492// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2493// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2494// if (m_local_debugserver)
2495// {
2496// return Host::ListProcessesMatchingName (name, matches, pids);
2497// }
2498// else
2499// {
2500// // FIXME: Implement talking to the remote debugserver.
2501// return 0;
2502// }
2503//
2504//}
2505//
Jim Ingham55e01d82011-01-22 01:33:44 +00002506bool
2507ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2508 lldb_private::StoppointCallbackContext *context,
2509 lldb::user_id_t break_id,
2510 lldb::user_id_t break_loc_id)
2511{
2512 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2513 // run so I can stop it if that's what I want to do.
2514 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2515 if (log)
2516 log->Printf("Hit New Thread Notification breakpoint.");
2517 return false;
2518}
2519
2520
2521bool
2522ProcessGDBRemote::StartNoticingNewThreads()
2523{
2524 static const char *bp_names[] =
2525 {
2526 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002527 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002528 "_pthread_start",
2529 NULL
2530 };
2531
2532 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2533 size_t num_bps = m_thread_observation_bps.size();
2534 if (num_bps != 0)
2535 {
2536 for (int i = 0; i < num_bps; i++)
2537 {
2538 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2539 if (break_sp)
2540 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002541 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002542 log->Printf("Enabled noticing new thread breakpoint.");
2543 break_sp->SetEnabled(true);
2544 }
2545 }
2546 }
2547 else
2548 {
2549 for (int i = 0; bp_names[i] != NULL; i++)
2550 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002551 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002552 if (breakpoint)
2553 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002554 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002555 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2556 m_thread_observation_bps.push_back(breakpoint->GetID());
2557 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2558 }
2559 else
2560 {
2561 if (log)
2562 log->Printf("Failed to create new thread notification breakpoint.");
2563 return false;
2564 }
2565 }
2566 }
2567
2568 return true;
2569}
2570
2571bool
2572ProcessGDBRemote::StopNoticingNewThreads()
2573{
Jim Inghamff276fe2011-02-08 05:19:01 +00002574 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002575 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002576 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002577 size_t num_bps = m_thread_observation_bps.size();
2578 if (num_bps != 0)
2579 {
2580 for (int i = 0; i < num_bps; i++)
2581 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002582
2583 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2584 if (break_sp)
2585 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002586 break_sp->SetEnabled(false);
2587 }
2588 }
2589 }
2590 return true;
2591}
2592
2593