blob: 2e59bc0d6fa0aad239d33146993431b77cc77a4c [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 (),
Greg Clayton06709002011-12-06 04:51:14 +0000126 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000127 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000128 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
129 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000130 m_continue_c_tids (),
131 m_continue_C_tids (),
132 m_continue_s_tids (),
133 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000134 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000135 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000136 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000137 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000138{
Greg Claytonff39f742011-04-01 00:29:43 +0000139 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
140 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000141}
142
143//----------------------------------------------------------------------
144// Destructor
145//----------------------------------------------------------------------
146ProcessGDBRemote::~ProcessGDBRemote()
147{
148 // m_mach_process.UnregisterNotificationCallbacks (this);
149 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000150 // We need to call finalize on the process before destroying ourselves
151 // to make sure all of the broadcaster cleanup goes as planned. If we
152 // destruct this class, then Process::~Process() might have problems
153 // trying to fully destroy the broadcaster.
154 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000155}
156
157//----------------------------------------------------------------------
158// PluginInterface
159//----------------------------------------------------------------------
160const char *
161ProcessGDBRemote::GetPluginName()
162{
163 return "Process debugging plug-in that uses the GDB remote protocol";
164}
165
166const char *
167ProcessGDBRemote::GetShortPluginName()
168{
169 return GetPluginNameStatic();
170}
171
172uint32_t
173ProcessGDBRemote::GetPluginVersion()
174{
175 return 1;
176}
177
178void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000179ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000180{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000181 if (!force && m_register_info.GetNumRegisters() > 0)
182 return;
183
184 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000185 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000186 uint32_t reg_offset = 0;
187 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000188 StringExtractorGDBRemote::ResponseType response_type;
189 for (response_type = StringExtractorGDBRemote::eResponse;
190 response_type == StringExtractorGDBRemote::eResponse;
191 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000192 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000193 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
194 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000195 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000196 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000197 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000198 response_type = response.GetResponseType();
199 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000200 {
201 std::string name;
202 std::string value;
203 ConstString reg_name;
204 ConstString alt_name;
205 ConstString set_name;
206 RegisterInfo reg_info = { NULL, // Name
207 NULL, // Alt name
208 0, // byte size
209 reg_offset, // offset
210 eEncodingUint, // encoding
211 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000212 {
213 LLDB_INVALID_REGNUM, // GCC reg num
214 LLDB_INVALID_REGNUM, // DWARF reg num
215 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000216 reg_num, // GDB reg num
217 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000218 }
219 };
220
221 while (response.GetNameColonValue(name, value))
222 {
223 if (name.compare("name") == 0)
224 {
225 reg_name.SetCString(value.c_str());
226 }
227 else if (name.compare("alt-name") == 0)
228 {
229 alt_name.SetCString(value.c_str());
230 }
231 else if (name.compare("bitsize") == 0)
232 {
233 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
234 }
235 else if (name.compare("offset") == 0)
236 {
237 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000238 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000239 {
240 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000241 }
242 }
243 else if (name.compare("encoding") == 0)
244 {
245 if (value.compare("uint") == 0)
246 reg_info.encoding = eEncodingUint;
247 else if (value.compare("sint") == 0)
248 reg_info.encoding = eEncodingSint;
249 else if (value.compare("ieee754") == 0)
250 reg_info.encoding = eEncodingIEEE754;
251 else if (value.compare("vector") == 0)
252 reg_info.encoding = eEncodingVector;
253 }
254 else if (name.compare("format") == 0)
255 {
256 if (value.compare("binary") == 0)
257 reg_info.format = eFormatBinary;
258 else if (value.compare("decimal") == 0)
259 reg_info.format = eFormatDecimal;
260 else if (value.compare("hex") == 0)
261 reg_info.format = eFormatHex;
262 else if (value.compare("float") == 0)
263 reg_info.format = eFormatFloat;
264 else if (value.compare("vector-sint8") == 0)
265 reg_info.format = eFormatVectorOfSInt8;
266 else if (value.compare("vector-uint8") == 0)
267 reg_info.format = eFormatVectorOfUInt8;
268 else if (value.compare("vector-sint16") == 0)
269 reg_info.format = eFormatVectorOfSInt16;
270 else if (value.compare("vector-uint16") == 0)
271 reg_info.format = eFormatVectorOfUInt16;
272 else if (value.compare("vector-sint32") == 0)
273 reg_info.format = eFormatVectorOfSInt32;
274 else if (value.compare("vector-uint32") == 0)
275 reg_info.format = eFormatVectorOfUInt32;
276 else if (value.compare("vector-float32") == 0)
277 reg_info.format = eFormatVectorOfFloat32;
278 else if (value.compare("vector-uint128") == 0)
279 reg_info.format = eFormatVectorOfUInt128;
280 }
281 else if (name.compare("set") == 0)
282 {
283 set_name.SetCString(value.c_str());
284 }
285 else if (name.compare("gcc") == 0)
286 {
287 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
288 }
289 else if (name.compare("dwarf") == 0)
290 {
291 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
292 }
293 else if (name.compare("generic") == 0)
294 {
295 if (value.compare("pc") == 0)
296 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
297 else if (value.compare("sp") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
299 else if (value.compare("fp") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
301 else if (value.compare("ra") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
303 else if (value.compare("flags") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000305 else if (value.find("arg") == 0)
306 {
307 if (value.size() == 4)
308 {
309 switch (value[3])
310 {
311 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
312 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
313 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
314 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
315 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
316 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
317 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
318 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
319 }
320 }
321 }
Chris Lattner24943d22010-06-08 16:52:24 +0000322 }
323 }
324
Jason Molenda53d96862010-06-11 23:44:18 +0000325 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000326 assert (reg_info.byte_size != 0);
327 reg_offset += reg_info.byte_size;
328 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
329 }
330 }
331 else
332 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000333 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000334 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000335 }
336 }
337
338 if (reg_num == 0)
339 {
340 // We didn't get anything. See if we are debugging ARM and fill with
341 // a hard coded register set until we can get an updated debugserver
342 // down on the devices.
Jason Molenda428b5502011-10-06 01:45:46 +0000343
344 if (!GetTarget().GetArchitecture().IsValid()
345 && m_gdb_comm.GetHostArchitecture().IsValid()
346 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm
347 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
348 {
Chris Lattner24943d22010-06-08 16:52:24 +0000349 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000350 }
351 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
352 {
353 m_register_info.HardcodeARMRegisters();
354 }
Chris Lattner24943d22010-06-08 16:52:24 +0000355 }
356 m_register_info.Finalize ();
357}
358
359Error
360ProcessGDBRemote::WillLaunch (Module* module)
361{
362 return WillLaunchOrAttach ();
363}
364
365Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000366ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000367{
368 return WillLaunchOrAttach ();
369}
370
371Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000372ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000373{
374 return WillLaunchOrAttach ();
375}
376
377Error
Greg Claytone71e2582011-02-04 01:58:07 +0000378ProcessGDBRemote::DoConnectRemote (const char *remote_url)
379{
380 Error error (WillLaunchOrAttach ());
381
382 if (error.Fail())
383 return error;
384
Greg Clayton180546b2011-04-30 01:09:13 +0000385 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000386
387 if (error.Fail())
388 return error;
389 StartAsyncThread ();
390
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000391 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000392 if (pid == LLDB_INVALID_PROCESS_ID)
393 {
394 // We don't have a valid process ID, so note that we are connected
395 // and could now request to launch or attach, or get remote process
396 // listings...
397 SetPrivateState (eStateConnected);
398 }
399 else
400 {
401 // We have a valid process
402 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000403 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000404 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000405 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000406 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000407 if (state == eStateStopped)
408 {
409 SetPrivateState (state);
410 }
411 else
Greg Claytond9919d32011-12-01 23:28:38 +0000412 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytone71e2582011-02-04 01:58:07 +0000413 }
414 else
Greg Claytond9919d32011-12-01 23:28:38 +0000415 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000416 }
417 return error;
418}
419
420Error
Chris Lattner24943d22010-06-08 16:52:24 +0000421ProcessGDBRemote::WillLaunchOrAttach ()
422{
423 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000424 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000425 return error;
426}
427
428//----------------------------------------------------------------------
429// Process Control
430//----------------------------------------------------------------------
431Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000432ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000433{
Greg Clayton4b407112010-09-30 21:49:03 +0000434 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000435
436 uint32_t launch_flags = launch_info.GetFlags().Get();
437 const char *stdin_path = NULL;
438 const char *stdout_path = NULL;
439 const char *stderr_path = NULL;
440 const char *working_dir = launch_info.GetWorkingDirectory();
441
442 const ProcessLaunchInfo::FileAction *file_action;
443 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
444 if (file_action)
445 {
446 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
447 stdin_path = file_action->GetPath();
448 }
449 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
450 if (file_action)
451 {
452 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
453 stdout_path = file_action->GetPath();
454 }
455 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
456 if (file_action)
457 {
458 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
459 stderr_path = file_action->GetPath();
460 }
461
Chris Lattner24943d22010-06-08 16:52:24 +0000462 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
463 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
464 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000465 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000466
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000467 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000468 if (object_file)
469 {
Chris Lattner24943d22010-06-08 16:52:24 +0000470 char host_port[128];
471 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000472 char connect_url[128];
473 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000474
Greg Claytona2f74232011-02-24 22:24:29 +0000475 // Make sure we aren't already connected?
476 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000477 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000478 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000479 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000480 {
Johnny Chenc143d622011-08-09 18:56:45 +0000481 if (log)
482 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000483 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000484 }
Chris Lattner24943d22010-06-08 16:52:24 +0000485
Greg Claytone71e2582011-02-04 01:58:07 +0000486 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000487 }
488
489 if (error.Success())
490 {
491 lldb_utility::PseudoTerminal pty;
492 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000493
494 // If the debugserver is local and we aren't disabling STDIO, lets use
495 // a pseudo terminal to instead of relying on the 'O' packets for stdio
496 // since 'O' packets can really slow down debugging if the inferior
497 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000498 PlatformSP platform_sp (m_target.GetPlatform());
499 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000500 {
501 const char *slave_name = NULL;
502 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000503 {
Greg Claytona2f74232011-02-24 22:24:29 +0000504 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
505 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000506 }
Greg Claytona2f74232011-02-24 22:24:29 +0000507 if (stdin_path == NULL)
508 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000509
Greg Claytona2f74232011-02-24 22:24:29 +0000510 if (stdout_path == NULL)
511 stdout_path = slave_name;
512
513 if (stderr_path == NULL)
514 stderr_path = slave_name;
515 }
516
Greg Claytonafb81862011-03-02 21:34:46 +0000517 // Set STDIN to /dev/null if we want STDIO disabled or if either
518 // STDOUT or STDERR have been set to something and STDIN hasn't
519 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000520 stdin_path = "/dev/null";
521
Greg Claytonafb81862011-03-02 21:34:46 +0000522 // Set STDOUT to /dev/null if we want STDIO disabled or if either
523 // STDIN or STDERR have been set to something and STDOUT hasn't
524 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000525 stdout_path = "/dev/null";
526
Greg Claytonafb81862011-03-02 21:34:46 +0000527 // Set STDERR to /dev/null if we want STDIO disabled or if either
528 // STDIN or STDOUT have been set to something and STDERR hasn't
529 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000530 stderr_path = "/dev/null";
531
532 if (stdin_path)
533 m_gdb_comm.SetSTDIN (stdin_path);
534 if (stdout_path)
535 m_gdb_comm.SetSTDOUT (stdout_path);
536 if (stderr_path)
537 m_gdb_comm.SetSTDERR (stderr_path);
538
539 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
540
Greg Claytona4582402011-05-08 04:53:50 +0000541 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000542
543 if (working_dir && working_dir[0])
544 {
545 m_gdb_comm.SetWorkingDir (working_dir);
546 }
547
548 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000549 const Args &environment = launch_info.GetEnvironmentEntries();
550 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000551 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000552 size_t num_environment_entries = environment.GetArgumentCount();
553 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000554 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000555 const char *env_entry = environment.GetArgumentAtIndex(i);
556 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000557 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000558 }
Greg Claytona2f74232011-02-24 22:24:29 +0000559 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000560
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000561 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000562 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000563 if (arg_packet_err == 0)
564 {
565 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000566 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000567 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000568 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000569 }
570 else
571 {
Greg Claytona2f74232011-02-24 22:24:29 +0000572 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000573 }
Greg Claytona2f74232011-02-24 22:24:29 +0000574 }
575 else
576 {
Greg Clayton9c236732011-10-26 00:56:27 +0000577 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000578 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000579
580 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000581
Greg Claytona2f74232011-02-24 22:24:29 +0000582 if (GetID() == LLDB_INVALID_PROCESS_ID)
583 {
Johnny Chenc143d622011-08-09 18:56:45 +0000584 if (log)
585 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000586 KillDebugserverProcess ();
587 return error;
588 }
589
Greg Clayton261a18b2011-06-02 22:22:38 +0000590 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000591 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000592 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000593
594 if (!disable_stdio)
595 {
596 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000597 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000598 }
Chris Lattner24943d22010-06-08 16:52:24 +0000599 }
600 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000601 else
602 {
Johnny Chenc143d622011-08-09 18:56:45 +0000603 if (log)
604 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000605 }
Chris Lattner24943d22010-06-08 16:52:24 +0000606 }
607 else
608 {
609 // Set our user ID to an invalid process ID.
610 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000611 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
612 exe_module->GetFileSpec().GetFilename().AsCString(),
613 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000614 }
Chris Lattner24943d22010-06-08 16:52:24 +0000615 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000616
Chris Lattner24943d22010-06-08 16:52:24 +0000617}
618
619
620Error
Greg Claytone71e2582011-02-04 01:58:07 +0000621ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000622{
623 Error error;
624 // Sleep and wait a bit for debugserver to start to listen...
625 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
626 if (conn_ap.get())
627 {
Chris Lattner24943d22010-06-08 16:52:24 +0000628 const uint32_t max_retry_count = 50;
629 uint32_t retry_count = 0;
630 while (!m_gdb_comm.IsConnected())
631 {
Greg Claytone71e2582011-02-04 01:58:07 +0000632 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000633 {
634 m_gdb_comm.SetConnection (conn_ap.release());
635 break;
636 }
637 retry_count++;
638
639 if (retry_count >= max_retry_count)
640 break;
641
642 usleep (100000);
643 }
644 }
645
646 if (!m_gdb_comm.IsConnected())
647 {
648 if (error.Success())
649 error.SetErrorString("not connected to remote gdb server");
650 return error;
651 }
652
Greg Clayton24bc5d92011-03-30 18:16:51 +0000653 // We always seem to be able to open a connection to a local port
654 // so we need to make sure we can then send data to it. If we can't
655 // then we aren't actually connected to anything, so try and do the
656 // handshake with the remote GDB server and make sure that goes
657 // alright.
658 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000659 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000660 m_gdb_comm.Disconnect();
661 if (error.Success())
662 error.SetErrorString("not connected to remote gdb server");
663 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000664 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000665 m_gdb_comm.ResetDiscoverableSettings();
666 m_gdb_comm.QueryNoAckModeSupported ();
667 m_gdb_comm.GetThreadSuffixSupported ();
668 m_gdb_comm.GetHostInfo ();
669 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000670 return error;
671}
672
673void
674ProcessGDBRemote::DidLaunchOrAttach ()
675{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000676 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
677 if (log)
678 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000679 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000680 {
681 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
682
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000683 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000684
Chris Lattner24943d22010-06-08 16:52:24 +0000685 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000686
Greg Claytoncb8977d2011-03-23 00:09:55 +0000687 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
688 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000689 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000690 ArchSpec &target_arch = GetTarget().GetArchitecture();
691
692 if (target_arch.IsValid())
693 {
694 // If the remote host is ARM and we have apple as the vendor, then
695 // ARM executables and shared libraries can have mixed ARM architectures.
696 // You can have an armv6 executable, and if the host is armv7, then the
697 // system will load the best possible architecture for all shared libraries
698 // it has, so we really need to take the remote host architecture as our
699 // defacto architecture in this case.
700
701 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
702 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
703 {
704 target_arch = gdb_remote_arch;
705 }
706 else
707 {
708 // Fill in what is missing in the triple
709 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
710 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000711 if (target_triple.getVendorName().size() == 0)
712 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000713 target_triple.setVendor (remote_triple.getVendor());
714
Greg Clayton2f085c62011-05-15 01:25:55 +0000715 if (target_triple.getOSName().size() == 0)
716 {
717 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000718
Greg Clayton2f085c62011-05-15 01:25:55 +0000719 if (target_triple.getEnvironmentName().size() == 0)
720 target_triple.setEnvironment (remote_triple.getEnvironment());
721 }
722 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000723 }
724 }
725 else
726 {
727 // The target doesn't have a valid architecture yet, set it from
728 // the architecture we got from the remote GDB server
729 target_arch = gdb_remote_arch;
730 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000731 }
Chris Lattner24943d22010-06-08 16:52:24 +0000732 }
733}
734
735void
736ProcessGDBRemote::DidLaunch ()
737{
738 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000739}
740
741Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000742ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000743{
744 Error error;
745 // Clear out and clean up from any current state
746 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000747 if (attach_pid != LLDB_INVALID_PROCESS_ID)
748 {
Greg Claytona2f74232011-02-24 22:24:29 +0000749 // Make sure we aren't already connected?
750 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000751 {
Greg Claytona2f74232011-02-24 22:24:29 +0000752 char host_port[128];
753 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
754 char connect_url[128];
755 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000756
Greg Claytonb72d0f02011-04-12 05:54:46 +0000757 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000758
759 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000760 {
Greg Claytona2f74232011-02-24 22:24:29 +0000761 const char *error_string = error.AsCString();
762 if (error_string == NULL)
763 error_string = "unable to launch " DEBUGSERVER_BASENAME;
764
765 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000766 }
Greg Claytona2f74232011-02-24 22:24:29 +0000767 else
768 {
769 error = ConnectToDebugserver (connect_url);
770 }
771 }
772
773 if (error.Success())
774 {
775 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000776 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000777 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000778 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000779 }
780 }
Chris Lattner24943d22010-06-08 16:52:24 +0000781 return error;
782}
783
784size_t
785ProcessGDBRemote::AttachInputReaderCallback
786(
787 void *baton,
788 InputReader *reader,
789 lldb::InputReaderAction notification,
790 const char *bytes,
791 size_t bytes_len
792)
793{
794 if (notification == eInputReaderGotToken)
795 {
796 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
797 if (gdb_process->m_waiting_for_attach)
798 gdb_process->m_waiting_for_attach = false;
799 reader->SetIsDone(true);
800 return 1;
801 }
802 return 0;
803}
804
805Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000806ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000807{
808 Error error;
809 // Clear out and clean up from any current state
810 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000811
Chris Lattner24943d22010-06-08 16:52:24 +0000812 if (process_name && process_name[0])
813 {
Greg Claytona2f74232011-02-24 22:24:29 +0000814 // Make sure we aren't already connected?
815 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000816 {
Greg Claytona2f74232011-02-24 22:24:29 +0000817 char host_port[128];
818 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
819 char connect_url[128];
820 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
821
Greg Claytonb72d0f02011-04-12 05:54:46 +0000822 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000823 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000824 {
Greg Claytona2f74232011-02-24 22:24:29 +0000825 const char *error_string = error.AsCString();
826 if (error_string == NULL)
827 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000828
Greg Claytona2f74232011-02-24 22:24:29 +0000829 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000830 }
Greg Claytona2f74232011-02-24 22:24:29 +0000831 else
832 {
833 error = ConnectToDebugserver (connect_url);
834 }
835 }
836
837 if (error.Success())
838 {
839 StreamString packet;
840
841 if (wait_for_launch)
842 packet.PutCString("vAttachWait");
843 else
844 packet.PutCString("vAttachName");
845 packet.PutChar(';');
846 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
847
848 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
849
Chris Lattner24943d22010-06-08 16:52:24 +0000850 }
851 }
Chris Lattner24943d22010-06-08 16:52:24 +0000852 return error;
853}
854
Chris Lattner24943d22010-06-08 16:52:24 +0000855
856void
857ProcessGDBRemote::DidAttach ()
858{
Greg Claytone71e2582011-02-04 01:58:07 +0000859 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000860}
861
862Error
863ProcessGDBRemote::WillResume ()
864{
Greg Claytonc1f45872011-02-12 06:28:37 +0000865 m_continue_c_tids.clear();
866 m_continue_C_tids.clear();
867 m_continue_s_tids.clear();
868 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000869 return Error();
870}
871
872Error
873ProcessGDBRemote::DoResume ()
874{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000875 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000876 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
877 if (log)
878 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000879
880 Listener listener ("gdb-remote.resume-packet-sent");
881 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
882 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000883 StreamString continue_packet;
884 bool continue_packet_error = false;
885 if (m_gdb_comm.HasAnyVContSupport ())
886 {
887 continue_packet.PutCString ("vCont");
888
889 if (!m_continue_c_tids.empty())
890 {
891 if (m_gdb_comm.GetVContSupported ('c'))
892 {
893 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos)
Greg Claytond9919d32011-12-01 23:28:38 +0000894 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000895 }
896 else
897 continue_packet_error = true;
898 }
899
900 if (!continue_packet_error && !m_continue_C_tids.empty())
901 {
902 if (m_gdb_comm.GetVContSupported ('C'))
903 {
904 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos)
Greg Claytond9919d32011-12-01 23:28:38 +0000905 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000906 }
907 else
908 continue_packet_error = true;
909 }
Greg Claytonb749a262010-12-03 06:02:24 +0000910
Greg Claytonc1f45872011-02-12 06:28:37 +0000911 if (!continue_packet_error && !m_continue_s_tids.empty())
912 {
913 if (m_gdb_comm.GetVContSupported ('s'))
914 {
915 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos)
Greg Claytond9919d32011-12-01 23:28:38 +0000916 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +0000917 }
918 else
919 continue_packet_error = true;
920 }
921
922 if (!continue_packet_error && !m_continue_S_tids.empty())
923 {
924 if (m_gdb_comm.GetVContSupported ('S'))
925 {
926 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos)
Greg Claytond9919d32011-12-01 23:28:38 +0000927 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000928 }
929 else
930 continue_packet_error = true;
931 }
932
933 if (continue_packet_error)
934 continue_packet.GetString().clear();
935 }
936 else
937 continue_packet_error = true;
938
939 if (continue_packet_error)
940 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000941 // Either no vCont support, or we tried to use part of the vCont
942 // packet that wasn't supported by the remote GDB server.
943 // We need to try and make a simple packet that can do our continue
944 const size_t num_threads = GetThreadList().GetSize();
945 const size_t num_continue_c_tids = m_continue_c_tids.size();
946 const size_t num_continue_C_tids = m_continue_C_tids.size();
947 const size_t num_continue_s_tids = m_continue_s_tids.size();
948 const size_t num_continue_S_tids = m_continue_S_tids.size();
949 if (num_continue_c_tids > 0)
950 {
951 if (num_continue_c_tids == num_threads)
952 {
953 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000954 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000955 continue_packet.PutChar ('c');
956 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000957 }
958 else if (num_continue_c_tids == 1 &&
959 num_continue_C_tids == 0 &&
960 num_continue_s_tids == 0 &&
961 num_continue_S_tids == 0 )
962 {
963 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000964 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000965 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000966 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000967 }
968 }
969
Greg Claytonde1dd812011-06-24 03:21:43 +0000970 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000971 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000972 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
973 num_continue_C_tids > 0 &&
974 num_continue_s_tids == 0 &&
975 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000976 {
977 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000978 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +0000979 if (num_continue_C_tids > 1)
980 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000981 // More that one thread with a signal, yet we don't have
982 // vCont support and we are being asked to resume each
983 // thread with a signal, we need to make sure they are
984 // all the same signal, or we can't issue the continue
985 // accurately with the current support...
986 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +0000987 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000988 continue_packet_error = false;
989 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
990 {
991 if (m_continue_C_tids[i].second != continue_signo)
992 continue_packet_error = true;
993 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000994 }
Greg Claytonde1dd812011-06-24 03:21:43 +0000995 if (!continue_packet_error)
996 m_gdb_comm.SetCurrentThreadForRun (-1);
997 }
998 else
999 {
1000 // Set the continue thread ID
1001 continue_packet_error = false;
1002 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001003 }
1004 if (!continue_packet_error)
1005 {
1006 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001007 continue_packet.Printf("C%2.2x", continue_signo);
1008 }
1009 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001010 }
1011
Greg Claytonde1dd812011-06-24 03:21:43 +00001012 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001013 {
1014 if (num_continue_s_tids == num_threads)
1015 {
1016 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001017 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001018 continue_packet.PutChar ('s');
1019 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001020 }
1021 else if (num_continue_c_tids == 0 &&
1022 num_continue_C_tids == 0 &&
1023 num_continue_s_tids == 1 &&
1024 num_continue_S_tids == 0 )
1025 {
1026 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001027 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001028 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001029 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001030 }
1031 }
1032
1033 if (!continue_packet_error && num_continue_S_tids > 0)
1034 {
1035 if (num_continue_S_tids == num_threads)
1036 {
1037 const int step_signo = m_continue_S_tids.front().second;
1038 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001039 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001040 if (num_continue_S_tids > 1)
1041 {
1042 for (size_t i=1; i<num_threads; ++i)
1043 {
1044 if (m_continue_S_tids[i].second != step_signo)
1045 continue_packet_error = true;
1046 }
1047 }
1048 if (!continue_packet_error)
1049 {
1050 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001051 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001052 continue_packet.Printf("S%2.2x", step_signo);
1053 }
1054 }
1055 else if (num_continue_c_tids == 0 &&
1056 num_continue_C_tids == 0 &&
1057 num_continue_s_tids == 0 &&
1058 num_continue_S_tids == 1 )
1059 {
1060 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001061 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001062 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001063 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001064 }
1065 }
1066 }
1067
1068 if (continue_packet_error)
1069 {
1070 error.SetErrorString ("can't make continue packet for this resume");
1071 }
1072 else
1073 {
1074 EventSP event_sp;
1075 TimeValue timeout;
1076 timeout = TimeValue::Now();
1077 timeout.OffsetWithSeconds (5);
1078 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1079
1080 if (listener.WaitForEvent (&timeout, event_sp) == false)
1081 error.SetErrorString("Resume timed out.");
1082 }
Greg Claytonb749a262010-12-03 06:02:24 +00001083 }
1084
Jim Ingham3ae449a2010-11-17 02:32:00 +00001085 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001086}
1087
Chris Lattner24943d22010-06-08 16:52:24 +00001088uint32_t
Greg Clayton37f962e2011-08-22 02:49:39 +00001089ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001090{
1091 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001092 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001093 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001094 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001095 // Update the thread list's stop id immediately so we don't recurse into this function.
Chris Lattner24943d22010-06-08 16:52:24 +00001096
Greg Clayton37f962e2011-08-22 02:49:39 +00001097 std::vector<lldb::tid_t> thread_ids;
1098 bool sequence_mutex_unavailable = false;
1099 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1100 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001101 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001102 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001103 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001104 tid_t tid = thread_ids[i];
1105 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1106 if (!thread_sp)
1107 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1108 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001109 }
Chris Lattner24943d22010-06-08 16:52:24 +00001110 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001111
1112 if (sequence_mutex_unavailable == false)
1113 SetThreadStopInfo (m_last_stop_packet);
1114 return new_thread_list.GetSize(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001115}
1116
1117
1118StateType
1119ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1120{
Greg Clayton261a18b2011-06-02 22:22:38 +00001121 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001122 const char stop_type = stop_packet.GetChar();
1123 switch (stop_type)
1124 {
1125 case 'T':
1126 case 'S':
1127 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001128 if (GetStopID() == 0)
1129 {
1130 // Our first stop, make sure we have a process ID, and also make
1131 // sure we know about our registers
1132 if (GetID() == LLDB_INVALID_PROCESS_ID)
1133 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001134 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001135 if (pid != LLDB_INVALID_PROCESS_ID)
1136 SetID (pid);
1137 }
1138 BuildDynamicRegisterInfo (true);
1139 }
Chris Lattner24943d22010-06-08 16:52:24 +00001140 // Stop with signal and thread info
1141 const uint8_t signo = stop_packet.GetHexU8();
1142 std::string name;
1143 std::string value;
1144 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001145 std::string reason;
1146 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001147 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001148 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001149 uint32_t tid = LLDB_INVALID_THREAD_ID;
1150 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1151 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001152 ThreadSP thread_sp;
1153
Chris Lattner24943d22010-06-08 16:52:24 +00001154 while (stop_packet.GetNameColonValue(name, value))
1155 {
1156 if (name.compare("metype") == 0)
1157 {
1158 // exception type in big endian hex
1159 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1160 }
1161 else if (name.compare("mecount") == 0)
1162 {
1163 // exception count in big endian hex
1164 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1165 }
1166 else if (name.compare("medata") == 0)
1167 {
1168 // exception data in big endian hex
1169 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1170 }
1171 else if (name.compare("thread") == 0)
1172 {
1173 // thread in big endian hex
1174 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001175 // m_thread_list does have its own mutex, but we need to
1176 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1177 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001178 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001179 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001180 if (!thread_sp)
1181 {
1182 // Create the thread if we need to
1183 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1184 m_thread_list.AddThread(thread_sp);
1185 }
Chris Lattner24943d22010-06-08 16:52:24 +00001186 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001187 else if (name.compare("hexname") == 0)
1188 {
1189 StringExtractor name_extractor;
1190 // Swap "value" over into "name_extractor"
1191 name_extractor.GetStringRef().swap(value);
1192 // Now convert the HEX bytes into a string value
1193 name_extractor.GetHexByteString (value);
1194 thread_name.swap (value);
1195 }
Chris Lattner24943d22010-06-08 16:52:24 +00001196 else if (name.compare("name") == 0)
1197 {
1198 thread_name.swap (value);
1199 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001200 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001201 {
1202 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1203 }
Greg Clayton65611552011-06-04 01:26:29 +00001204 else if (name.compare("reason") == 0)
1205 {
1206 reason.swap(value);
1207 }
1208 else if (name.compare("description") == 0)
1209 {
1210 StringExtractor desc_extractor;
1211 // Swap "value" over into "name_extractor"
1212 desc_extractor.GetStringRef().swap(value);
1213 // Now convert the HEX bytes into a string value
1214 desc_extractor.GetHexByteString (thread_name);
1215 }
Greg Claytona875b642011-01-09 21:07:35 +00001216 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1217 {
1218 // We have a register number that contains an expedited
1219 // register value. Lets supply this register to our thread
1220 // so it won't have to go and read it.
1221 if (thread_sp)
1222 {
1223 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1224
1225 if (reg != UINT32_MAX)
1226 {
1227 StringExtractor reg_value_extractor;
1228 // Swap "value" over into "reg_value_extractor"
1229 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001230 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1231 {
1232 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1233 name.c_str(),
1234 reg,
1235 reg,
1236 reg_value_extractor.GetStringRef().c_str(),
1237 stop_packet.GetStringRef().c_str());
1238 }
Greg Claytona875b642011-01-09 21:07:35 +00001239 }
1240 }
1241 }
Chris Lattner24943d22010-06-08 16:52:24 +00001242 }
Chris Lattner24943d22010-06-08 16:52:24 +00001243
1244 if (thread_sp)
1245 {
1246 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1247
1248 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001249 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001250 if (exc_type != 0)
1251 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001252 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001253
1254 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1255 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001256 exc_data_size,
1257 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001258 exc_data_size >= 2 ? exc_data[1] : 0,
1259 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001260 }
Greg Clayton65611552011-06-04 01:26:29 +00001261 else
Chris Lattner24943d22010-06-08 16:52:24 +00001262 {
Greg Clayton65611552011-06-04 01:26:29 +00001263 bool handled = false;
1264 if (!reason.empty())
1265 {
1266 if (reason.compare("trace") == 0)
1267 {
1268 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1269 handled = true;
1270 }
1271 else if (reason.compare("breakpoint") == 0)
1272 {
1273 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1274 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1275 if (bp_site_sp)
1276 {
1277 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1278 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1279 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1280 if (bp_site_sp->ValidForThisThread (gdb_thread))
1281 {
1282 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1283 handled = true;
1284 }
1285 }
1286
1287 if (!handled)
1288 {
1289 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1290 }
1291 }
1292 else if (reason.compare("trap") == 0)
1293 {
1294 // Let the trap just use the standard signal stop reason below...
1295 }
1296 else if (reason.compare("watchpoint") == 0)
1297 {
1298 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1299 // TODO: locate the watchpoint somehow...
1300 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1301 handled = true;
1302 }
1303 else if (reason.compare("exception") == 0)
1304 {
1305 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1306 handled = true;
1307 }
1308 }
1309
1310 if (signo)
1311 {
1312 if (signo == SIGTRAP)
1313 {
1314 // Currently we are going to assume SIGTRAP means we are either
1315 // hitting a breakpoint or hardware single stepping.
1316 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1317 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1318 if (bp_site_sp)
1319 {
1320 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1321 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1322 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1323 if (bp_site_sp->ValidForThisThread (gdb_thread))
1324 {
1325 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1326 handled = true;
1327 }
1328 }
1329 if (!handled)
1330 {
1331 // TODO: check for breakpoint or trap opcode in case there is a hard
1332 // coded software trap
1333 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1334 handled = true;
1335 }
1336 }
1337 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001338 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001339 }
1340 else
1341 {
Greg Clayton643ee732010-08-04 01:40:35 +00001342 StopInfoSP invalid_stop_info_sp;
1343 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001344 }
Greg Clayton65611552011-06-04 01:26:29 +00001345
1346 if (!description.empty())
1347 {
1348 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1349 if (stop_info_sp)
1350 {
1351 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001352 }
Greg Clayton65611552011-06-04 01:26:29 +00001353 else
1354 {
1355 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1356 }
1357 }
1358 }
Chris Lattner24943d22010-06-08 16:52:24 +00001359 }
1360 return eStateStopped;
1361 }
1362 break;
1363
1364 case 'W':
1365 // process exited
1366 return eStateExited;
1367
1368 default:
1369 break;
1370 }
1371 return eStateInvalid;
1372}
1373
1374void
1375ProcessGDBRemote::RefreshStateAfterStop ()
1376{
Chris Lattner24943d22010-06-08 16:52:24 +00001377 // Let all threads recover from stopping and do any clean up based
1378 // on the previous thread state (if any).
1379 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001380 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001381}
1382
1383Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001384ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001385{
1386 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001387
Greg Claytona4881d02011-01-22 07:12:45 +00001388 bool timed_out = false;
1389 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001390
1391 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001392 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001393 // We are being asked to halt during an attach. We need to just close
1394 // our file handle and debugserver will go away, and we can be done...
1395 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001396 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001397 else
1398 {
1399 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1400 {
1401 if (timed_out)
1402 error.SetErrorString("timed out sending interrupt packet");
1403 else
1404 error.SetErrorString("unknown error sending interrupt packet");
1405 }
1406 }
Chris Lattner24943d22010-06-08 16:52:24 +00001407 return error;
1408}
1409
1410Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001411ProcessGDBRemote::InterruptIfRunning
1412(
1413 bool discard_thread_plans,
1414 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001415 EventSP &stop_event_sp
1416)
Chris Lattner24943d22010-06-08 16:52:24 +00001417{
1418 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001419
Greg Clayton2860ba92011-01-23 19:58:49 +00001420 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1421
Greg Clayton68ca8232011-01-25 02:58:48 +00001422 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001423 const bool is_running = m_gdb_comm.IsRunning();
1424 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001425 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001426 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001427 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001428 is_running);
1429
Greg Clayton2860ba92011-01-23 19:58:49 +00001430 if (discard_thread_plans)
1431 {
1432 if (log)
1433 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1434 m_thread_list.DiscardThreadPlans();
1435 }
1436 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001437 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001438 if (catch_stop_event)
1439 {
1440 if (log)
1441 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1442 PausePrivateStateThread();
1443 paused_private_state_thread = true;
1444 }
1445
Greg Clayton4fb400f2010-09-27 21:07:38 +00001446 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001447 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001448 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001449
Greg Clayton72e1c782011-01-22 23:43:18 +00001450 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001451 {
1452 if (timed_out)
1453 error.SetErrorString("timed out sending interrupt packet");
1454 else
1455 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001456 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001457 ResumePrivateStateThread();
1458 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001459 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001460
Greg Clayton72e1c782011-01-22 23:43:18 +00001461 if (catch_stop_event)
1462 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001463 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001464 TimeValue timeout_time;
1465 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001466 timeout_time.OffsetWithSeconds(5);
1467 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001468
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001469 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001470 if (log)
1471 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001472
Greg Clayton2860ba92011-01-23 19:58:49 +00001473 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001474 error.SetErrorString("unable to verify target stopped");
1475 }
1476
Greg Clayton68ca8232011-01-25 02:58:48 +00001477 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001478 {
1479 if (log)
1480 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001481 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001482 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001483 }
Chris Lattner24943d22010-06-08 16:52:24 +00001484 return error;
1485}
1486
Greg Clayton4fb400f2010-09-27 21:07:38 +00001487Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001488ProcessGDBRemote::WillDetach ()
1489{
Greg Clayton2860ba92011-01-23 19:58:49 +00001490 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1491 if (log)
1492 log->Printf ("ProcessGDBRemote::WillDetach()");
1493
Greg Clayton72e1c782011-01-22 23:43:18 +00001494 bool discard_thread_plans = true;
1495 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001496 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001497 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001498}
1499
1500Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001501ProcessGDBRemote::DoDetach()
1502{
1503 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001504 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001505 if (log)
1506 log->Printf ("ProcessGDBRemote::DoDetach()");
1507
1508 DisableAllBreakpointSites ();
1509
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001510 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001511
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001512 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1513 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001514 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001515 if (response_size)
1516 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1517 else
1518 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001519 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001520 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001521 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001522
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001523 SetPrivateState (eStateDetached);
1524 ResumePrivateStateThread();
1525
1526 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001527 return error;
1528}
Chris Lattner24943d22010-06-08 16:52:24 +00001529
1530Error
1531ProcessGDBRemote::DoDestroy ()
1532{
1533 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001534 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001535 if (log)
1536 log->Printf ("ProcessGDBRemote::DoDestroy()");
1537
1538 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001539 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001540 {
Jim Ingham8226e942011-10-28 01:11:35 +00001541 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001542 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001543
1544 StringExtractorGDBRemote response;
1545 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001546 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001547 {
1548 char packet_cmd = response.GetChar(0);
1549
1550 if (packet_cmd == 'W' || packet_cmd == 'X')
1551 {
Greg Clayton06709002011-12-06 04:51:14 +00001552 SetLastStopPacket (response);
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001553 SetExitStatus(response.GetHexU8(), NULL);
1554 }
1555 }
1556 else
1557 {
1558 SetExitStatus(SIGABRT, NULL);
1559 //error.SetErrorString("kill packet failed");
1560 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001561 }
1562 }
Chris Lattner24943d22010-06-08 16:52:24 +00001563 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001564 KillDebugserverProcess ();
1565 return error;
1566}
1567
Chris Lattner24943d22010-06-08 16:52:24 +00001568//------------------------------------------------------------------
1569// Process Queries
1570//------------------------------------------------------------------
1571
1572bool
1573ProcessGDBRemote::IsAlive ()
1574{
Greg Clayton58e844b2010-12-08 05:08:21 +00001575 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001576}
1577
1578addr_t
1579ProcessGDBRemote::GetImageInfoAddress()
1580{
1581 if (!m_gdb_comm.IsRunning())
1582 {
1583 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001584 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001585 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001586 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001587 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1588 }
1589 }
1590 return LLDB_INVALID_ADDRESS;
1591}
1592
Chris Lattner24943d22010-06-08 16:52:24 +00001593//------------------------------------------------------------------
1594// Process Memory
1595//------------------------------------------------------------------
1596size_t
1597ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1598{
1599 if (size > m_max_memory_size)
1600 {
1601 // Keep memory read sizes down to a sane limit. This function will be
1602 // called multiple times in order to complete the task by
1603 // lldb_private::Process so it is ok to do this.
1604 size = m_max_memory_size;
1605 }
1606
1607 char packet[64];
1608 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1609 assert (packet_len + 1 < sizeof(packet));
1610 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001611 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001612 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001613 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001614 {
1615 error.Clear();
1616 return response.GetHexBytes(buf, size, '\xdd');
1617 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001618 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001619 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001620 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001621 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1622 else
1623 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1624 }
1625 else
1626 {
1627 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1628 }
1629 return 0;
1630}
1631
1632size_t
1633ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1634{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001635 if (size > m_max_memory_size)
1636 {
1637 // Keep memory read sizes down to a sane limit. This function will be
1638 // called multiple times in order to complete the task by
1639 // lldb_private::Process so it is ok to do this.
1640 size = m_max_memory_size;
1641 }
1642
Chris Lattner24943d22010-06-08 16:52:24 +00001643 StreamString packet;
1644 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001645 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001646 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001647 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001648 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001649 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001650 {
1651 error.Clear();
1652 return size;
1653 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001654 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001655 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001656 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001657 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1658 else
1659 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1660 }
1661 else
1662 {
1663 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1664 }
1665 return 0;
1666}
1667
1668lldb::addr_t
1669ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1670{
Greg Clayton989816b2011-05-14 01:50:35 +00001671 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1672
Greg Clayton2f085c62011-05-15 01:25:55 +00001673 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001674 switch (supported)
1675 {
1676 case eLazyBoolCalculate:
1677 case eLazyBoolYes:
1678 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1679 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1680 return allocated_addr;
1681
1682 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001683 // Call mmap() to create memory in the inferior..
1684 unsigned prot = 0;
1685 if (permissions & lldb::ePermissionsReadable)
1686 prot |= eMmapProtRead;
1687 if (permissions & lldb::ePermissionsWritable)
1688 prot |= eMmapProtWrite;
1689 if (permissions & lldb::ePermissionsExecutable)
1690 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001691
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001692 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1693 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1694 m_addr_to_mmap_size[allocated_addr] = size;
1695 else
1696 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001697 break;
1698 }
1699
Chris Lattner24943d22010-06-08 16:52:24 +00001700 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001701 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001702 else
1703 error.Clear();
1704 return allocated_addr;
1705}
1706
1707Error
Greg Claytona9385532011-11-18 07:03:08 +00001708ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
1709 MemoryRegionInfo &region_info)
1710{
1711
1712 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
1713 return error;
1714}
1715
1716Error
Chris Lattner24943d22010-06-08 16:52:24 +00001717ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1718{
1719 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001720 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1721
1722 switch (supported)
1723 {
1724 case eLazyBoolCalculate:
1725 // We should never be deallocating memory without allocating memory
1726 // first so we should never get eLazyBoolCalculate
1727 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1728 break;
1729
1730 case eLazyBoolYes:
1731 if (!m_gdb_comm.DeallocateMemory (addr))
1732 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1733 break;
1734
1735 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001736 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001737 {
1738 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001739 if (pos != m_addr_to_mmap_size.end() &&
1740 InferiorCallMunmap(this, addr, pos->second))
1741 m_addr_to_mmap_size.erase (pos);
1742 else
1743 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001744 }
1745 break;
1746 }
1747
Chris Lattner24943d22010-06-08 16:52:24 +00001748 return error;
1749}
1750
1751
1752//------------------------------------------------------------------
1753// Process STDIO
1754//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001755size_t
1756ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1757{
1758 if (m_stdio_communication.IsConnected())
1759 {
1760 ConnectionStatus status;
1761 m_stdio_communication.Write(src, src_len, status, NULL);
1762 }
1763 return 0;
1764}
1765
1766Error
1767ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1768{
1769 Error error;
1770 assert (bp_site != NULL);
1771
Greg Claytone005f2c2010-11-06 01:53:30 +00001772 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001773 user_id_t site_id = bp_site->GetID();
1774 const addr_t addr = bp_site->GetLoadAddress();
1775 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001776 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001777
1778 if (bp_site->IsEnabled())
1779 {
1780 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001781 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 +00001782 return error;
1783 }
1784 else
1785 {
1786 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1787
1788 if (bp_site->HardwarePreferred())
1789 {
1790 // Try and set hardware breakpoint, and if that fails, fall through
1791 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001792 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001793 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001794 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001795 {
1796 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001797 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001798 return error;
1799 }
Chris Lattner24943d22010-06-08 16:52:24 +00001800 }
1801 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001802
1803 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001804 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001805 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1806 {
1807 bp_site->SetEnabled(true);
1808 bp_site->SetType (BreakpointSite::eExternal);
1809 return error;
1810 }
Chris Lattner24943d22010-06-08 16:52:24 +00001811 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001812
1813 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001814 }
1815
1816 if (log)
1817 {
1818 const char *err_string = error.AsCString();
1819 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1820 bp_site->GetLoadAddress(),
1821 err_string ? err_string : "NULL");
1822 }
1823 // We shouldn't reach here on a successful breakpoint enable...
1824 if (error.Success())
1825 error.SetErrorToGenericError();
1826 return error;
1827}
1828
1829Error
1830ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1831{
1832 Error error;
1833 assert (bp_site != NULL);
1834 addr_t addr = bp_site->GetLoadAddress();
1835 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001836 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001837 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001838 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001839
1840 if (bp_site->IsEnabled())
1841 {
1842 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1843
Greg Claytonb72d0f02011-04-12 05:54:46 +00001844 BreakpointSite::Type bp_type = bp_site->GetType();
1845 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001846 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001847 case BreakpointSite::eSoftware:
1848 error = DisableSoftwareBreakpoint (bp_site);
1849 break;
1850
1851 case BreakpointSite::eHardware:
1852 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1853 error.SetErrorToGenericError();
1854 break;
1855
1856 case BreakpointSite::eExternal:
1857 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1858 error.SetErrorToGenericError();
1859 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001860 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001861 if (error.Success())
1862 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001863 }
1864 else
1865 {
1866 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001867 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 +00001868 return error;
1869 }
1870
1871 if (error.Success())
1872 error.SetErrorToGenericError();
1873 return error;
1874}
1875
Johnny Chen21900fb2011-09-06 22:38:36 +00001876// Pre-requisite: wp != NULL.
1877static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00001878GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00001879{
1880 assert(wp);
1881 bool watch_read = wp->WatchpointRead();
1882 bool watch_write = wp->WatchpointWrite();
1883
1884 // watch_read and watch_write cannot both be false.
1885 assert(watch_read || watch_write);
1886 if (watch_read && watch_write)
1887 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001888 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00001889 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00001890 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00001891 return eWatchpointWrite;
1892}
1893
Chris Lattner24943d22010-06-08 16:52:24 +00001894Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001895ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001896{
1897 Error error;
1898 if (wp)
1899 {
1900 user_id_t watchID = wp->GetID();
1901 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001902 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001903 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001904 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00001905 if (wp->IsEnabled())
1906 {
1907 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001908 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001909 return error;
1910 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001911
1912 GDBStoppointType type = GetGDBStoppointType(wp);
1913 // Pass down an appropriate z/Z packet...
1914 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00001915 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001916 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
1917 {
1918 wp->SetEnabled(true);
1919 return error;
1920 }
1921 else
1922 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001923 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001924 else
1925 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00001926 }
1927 else
1928 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001929 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001930 }
1931 if (error.Success())
1932 error.SetErrorToGenericError();
1933 return error;
1934}
1935
1936Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001937ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001938{
1939 Error error;
1940 if (wp)
1941 {
1942 user_id_t watchID = wp->GetID();
1943
Greg Claytone005f2c2010-11-06 01:53:30 +00001944 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001945
1946 addr_t addr = wp->GetLoadAddress();
1947 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001948 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001949
Johnny Chen21900fb2011-09-06 22:38:36 +00001950 if (!wp->IsEnabled())
1951 {
1952 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001953 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00001954 return error;
1955 }
1956
Chris Lattner24943d22010-06-08 16:52:24 +00001957 if (wp->IsHardware())
1958 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001959 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00001960 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00001961 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
1962 {
1963 wp->SetEnabled(false);
1964 return error;
1965 }
1966 else
1967 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001968 }
1969 // TODO: clear software watchpoints if we implement them
1970 }
1971 else
1972 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001973 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001974 }
1975 if (error.Success())
1976 error.SetErrorToGenericError();
1977 return error;
1978}
1979
1980void
1981ProcessGDBRemote::Clear()
1982{
1983 m_flags = 0;
1984 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001985}
1986
1987Error
1988ProcessGDBRemote::DoSignal (int signo)
1989{
1990 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001991 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001992 if (log)
1993 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
1994
1995 if (!m_gdb_comm.SendAsyncSignal (signo))
1996 error.SetErrorStringWithFormat("failed to send signal %i", signo);
1997 return error;
1998}
1999
Chris Lattner24943d22010-06-08 16:52:24 +00002000Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002001ProcessGDBRemote::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 +00002002{
2003 Error error;
2004 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2005 {
2006 // If we locate debugserver, keep that located version around
2007 static FileSpec g_debugserver_file_spec;
2008
Greg Claytonb72d0f02011-04-12 05:54:46 +00002009 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002010 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002011 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002012
2013 // Always check to see if we have an environment override for the path
2014 // to the debugserver to use and use it if we do.
2015 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2016 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002017 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002018 else
2019 debugserver_file_spec = g_debugserver_file_spec;
2020 bool debugserver_exists = debugserver_file_spec.Exists();
2021 if (!debugserver_exists)
2022 {
2023 // The debugserver binary is in the LLDB.framework/Resources
2024 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002025 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002026 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002027 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002028 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002029 if (debugserver_exists)
2030 {
2031 g_debugserver_file_spec = debugserver_file_spec;
2032 }
2033 else
2034 {
2035 g_debugserver_file_spec.Clear();
2036 debugserver_file_spec.Clear();
2037 }
Chris Lattner24943d22010-06-08 16:52:24 +00002038 }
2039 }
2040
2041 if (debugserver_exists)
2042 {
2043 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2044
2045 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002046
Greg Claytone005f2c2010-11-06 01:53:30 +00002047 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002048
Greg Claytonb72d0f02011-04-12 05:54:46 +00002049 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002050 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002051
Chris Lattner24943d22010-06-08 16:52:24 +00002052 // Start args with "debugserver /file/path -r --"
2053 debugserver_args.AppendArgument(debugserver_path);
2054 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002055 // use native registers, not the GDB registers
2056 debugserver_args.AppendArgument("--native-regs");
2057 // make debugserver run in its own session so signals generated by
2058 // special terminal key sequences (^C) don't affect debugserver
2059 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002060
Chris Lattner24943d22010-06-08 16:52:24 +00002061 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2062 if (env_debugserver_log_file)
2063 {
2064 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2065 debugserver_args.AppendArgument(arg_cstr);
2066 }
2067
2068 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2069 if (env_debugserver_log_flags)
2070 {
2071 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2072 debugserver_args.AppendArgument(arg_cstr);
2073 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002074// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002075// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002076
Greg Claytonb72d0f02011-04-12 05:54:46 +00002077 // We currently send down all arguments, attach pids, or attach
2078 // process names in dedicated GDB server packets, so we don't need
2079 // to pass them as arguments. This is currently because of all the
2080 // things we need to setup prior to launching: the environment,
2081 // current working dir, file actions, etc.
2082#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002083 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002084 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002085 {
Greg Claytona2f74232011-02-24 22:24:29 +00002086 // Terminate the debugserver args so we can now append the inferior args
2087 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002088
Greg Claytona2f74232011-02-24 22:24:29 +00002089 for (int i = 0; inferior_argv[i] != NULL; ++i)
2090 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002091 }
2092 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2093 {
2094 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2095 debugserver_args.AppendArgument (arg_cstr);
2096 }
2097 else if (attach_name && attach_name[0])
2098 {
2099 if (wait_for_launch)
2100 debugserver_args.AppendArgument ("--waitfor");
2101 else
2102 debugserver_args.AppendArgument ("--attach");
2103 debugserver_args.AppendArgument (attach_name);
2104 }
Chris Lattner24943d22010-06-08 16:52:24 +00002105#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002106
2107 ProcessLaunchInfo::FileAction file_action;
2108
2109 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2110 // to "/dev/null" if we run into any problems.
2111 file_action.Close (STDIN_FILENO);
2112 launch_info.AppendFileAction (file_action);
2113 file_action.Close (STDOUT_FILENO);
2114 launch_info.AppendFileAction (file_action);
2115 file_action.Close (STDERR_FILENO);
2116 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002117
2118 if (log)
2119 {
2120 StreamString strm;
2121 debugserver_args.Dump (&strm);
2122 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2123 }
2124
Greg Clayton1c4642c2011-11-16 05:37:56 +00002125 launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2126
Greg Claytonb72d0f02011-04-12 05:54:46 +00002127 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002128
Greg Claytonb72d0f02011-04-12 05:54:46 +00002129 if (error.Success ())
2130 m_debugserver_pid = launch_info.GetProcessID();
2131 else
Chris Lattner24943d22010-06-08 16:52:24 +00002132 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2133
2134 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002135 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002136 }
2137 else
2138 {
Greg Clayton9c236732011-10-26 00:56:27 +00002139 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002140 }
2141
2142 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2143 StartAsyncThread ();
2144 }
2145 return error;
2146}
2147
2148bool
2149ProcessGDBRemote::MonitorDebugserverProcess
2150(
2151 void *callback_baton,
2152 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002153 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002154 int signo, // Zero for no signal
2155 int exit_status // Exit value of process if signal is zero
2156)
2157{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002158 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2159 // and might not exist anymore, so we need to carefully try to get the
2160 // target for this process first since we have a race condition when
2161 // we are done running between getting the notice that the inferior
2162 // process has died and the debugserver that was debugging this process.
2163 // In our test suite, we are also continually running process after
2164 // process, so we must be very careful to make sure:
2165 // 1 - process object hasn't been deleted already
2166 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002167
2168 // "debugserver_pid" argument passed in is the process ID for
2169 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002170 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002171
Greg Clayton75ccf502010-08-21 02:22:51 +00002172 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002173
Greg Clayton1c4642c2011-11-16 05:37:56 +00002174 // Get a shared pointer to the target that has a matching process pointer.
2175 // This target could be gone, or the target could already have a new process
2176 // object inside of it
2177 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2178
Greg Clayton72e1c782011-01-22 23:43:18 +00002179 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002180 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%llu, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton72e1c782011-01-22 23:43:18 +00002181
Greg Clayton1c4642c2011-11-16 05:37:56 +00002182 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002183 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002184 // We found a process in a target that matches, but another thread
2185 // might be in the process of launching a new process that will
2186 // soon replace it, so get a shared pointer to the process so we
2187 // can keep it alive.
2188 ProcessSP process_sp (target_sp->GetProcessSP());
2189 // Now we have a shared pointer to the process that can't go away on us
2190 // so we now make sure it was the same as the one passed in, and also make
2191 // sure that our previous "process *" didn't get deleted and have a new
2192 // "process *" created in its place with the same pointer. To verify this
2193 // we make sure the process has our debugserver process ID. If we pass all
2194 // of these tests, then we are sure that this process is the one we were
2195 // looking for.
2196 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002197 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002198 // Sleep for a half a second to make sure our inferior process has
2199 // time to set its exit status before we set it incorrectly when
2200 // both the debugserver and the inferior process shut down.
2201 usleep (500000);
2202 // If our process hasn't yet exited, debugserver might have died.
2203 // If the process did exit, the we are reaping it.
2204 const StateType state = process->GetState();
2205
2206 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2207 state != eStateInvalid &&
2208 state != eStateUnloaded &&
2209 state != eStateExited &&
2210 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002211 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002212 char error_str[1024];
2213 if (signo)
2214 {
2215 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2216 if (signal_cstr)
2217 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2218 else
2219 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2220 }
Chris Lattner24943d22010-06-08 16:52:24 +00002221 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002222 {
2223 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2224 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002225
Greg Clayton1c4642c2011-11-16 05:37:56 +00002226 process->SetExitStatus (-1, error_str);
2227 }
2228 // Debugserver has exited we need to let our ProcessGDBRemote
2229 // know that it no longer has a debugserver instance
2230 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002231 }
Chris Lattner24943d22010-06-08 16:52:24 +00002232 }
2233 return true;
2234}
2235
2236void
2237ProcessGDBRemote::KillDebugserverProcess ()
2238{
2239 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2240 {
2241 ::kill (m_debugserver_pid, SIGINT);
2242 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2243 }
2244}
2245
2246void
2247ProcessGDBRemote::Initialize()
2248{
2249 static bool g_initialized = false;
2250
2251 if (g_initialized == false)
2252 {
2253 g_initialized = true;
2254 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2255 GetPluginDescriptionStatic(),
2256 CreateInstance);
2257
2258 Log::Callbacks log_callbacks = {
2259 ProcessGDBRemoteLog::DisableLog,
2260 ProcessGDBRemoteLog::EnableLog,
2261 ProcessGDBRemoteLog::ListLogCategories
2262 };
2263
2264 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2265 }
2266}
2267
2268bool
Chris Lattner24943d22010-06-08 16:52:24 +00002269ProcessGDBRemote::StartAsyncThread ()
2270{
Greg Claytone005f2c2010-11-06 01:53:30 +00002271 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002272
2273 if (log)
2274 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2275
2276 // Create a thread that watches our internal state and controls which
2277 // events make it to clients (into the DCProcess event queue).
2278 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002279 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002280}
2281
2282void
2283ProcessGDBRemote::StopAsyncThread ()
2284{
Greg Claytone005f2c2010-11-06 01:53:30 +00002285 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002286
2287 if (log)
2288 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2289
2290 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002291
2292 // This will shut down the async thread.
2293 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002294
2295 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002296 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002297 {
2298 Host::ThreadJoin (m_async_thread, NULL, NULL);
2299 }
2300}
2301
2302
2303void *
2304ProcessGDBRemote::AsyncThread (void *arg)
2305{
2306 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2307
Greg Claytone005f2c2010-11-06 01:53:30 +00002308 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002309 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002310 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002311
2312 Listener listener ("ProcessGDBRemote::AsyncThread");
2313 EventSP event_sp;
2314 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2315 eBroadcastBitAsyncThreadShouldExit;
2316
2317 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2318 {
Greg Claytona2f74232011-02-24 22:24:29 +00002319 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2320
Chris Lattner24943d22010-06-08 16:52:24 +00002321 bool done = false;
2322 while (!done)
2323 {
2324 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002325 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002326 if (listener.WaitForEvent (NULL, event_sp))
2327 {
2328 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002329 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002330 {
Greg Claytona2f74232011-02-24 22:24:29 +00002331 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002332 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 +00002333
Greg Claytona2f74232011-02-24 22:24:29 +00002334 switch (event_type)
2335 {
2336 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002337 {
Greg Claytona2f74232011-02-24 22:24:29 +00002338 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002339
Greg Claytona2f74232011-02-24 22:24:29 +00002340 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002341 {
Greg Claytona2f74232011-02-24 22:24:29 +00002342 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2343 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2344 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002345 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002346
Greg Claytona2f74232011-02-24 22:24:29 +00002347 if (::strstr (continue_cstr, "vAttach") == NULL)
2348 process->SetPrivateState(eStateRunning);
2349 StringExtractorGDBRemote response;
2350 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002351
Greg Claytona2f74232011-02-24 22:24:29 +00002352 switch (stop_state)
2353 {
2354 case eStateStopped:
2355 case eStateCrashed:
2356 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002357 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002358 process->SetPrivateState (stop_state);
2359 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002360
Greg Claytona2f74232011-02-24 22:24:29 +00002361 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002362 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002363 response.SetFilePos(1);
2364 process->SetExitStatus(response.GetHexU8(), NULL);
2365 done = true;
2366 break;
2367
2368 case eStateInvalid:
2369 process->SetExitStatus(-1, "lost connection");
2370 break;
2371
2372 default:
2373 process->SetPrivateState (stop_state);
2374 break;
2375 }
Chris Lattner24943d22010-06-08 16:52:24 +00002376 }
2377 }
Greg Claytona2f74232011-02-24 22:24:29 +00002378 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002379
Greg Claytona2f74232011-02-24 22:24:29 +00002380 case eBroadcastBitAsyncThreadShouldExit:
2381 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002382 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002383 done = true;
2384 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002385
Greg Claytona2f74232011-02-24 22:24:29 +00002386 default:
2387 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002388 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 +00002389 done = true;
2390 break;
2391 }
2392 }
2393 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2394 {
2395 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2396 {
2397 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002398 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002399 }
Chris Lattner24943d22010-06-08 16:52:24 +00002400 }
2401 }
2402 else
2403 {
2404 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002405 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 +00002406 done = true;
2407 }
2408 }
2409 }
2410
2411 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002412 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002413
2414 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2415 return NULL;
2416}
2417
Chris Lattner24943d22010-06-08 16:52:24 +00002418const char *
2419ProcessGDBRemote::GetDispatchQueueNameForThread
2420(
2421 addr_t thread_dispatch_qaddr,
2422 std::string &dispatch_queue_name
2423)
2424{
2425 dispatch_queue_name.clear();
2426 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2427 {
2428 // Cache the dispatch_queue_offsets_addr value so we don't always have
2429 // to look it up
2430 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2431 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002432 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2433 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002434 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002435 if (module_sp)
2436 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2437
2438 if (dispatch_queue_offsets_symbol == NULL)
2439 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002440 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002441 if (module_sp)
2442 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2443 }
Chris Lattner24943d22010-06-08 16:52:24 +00002444 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002445 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002446
2447 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2448 return NULL;
2449 }
2450
2451 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002452 DataExtractor data (memory_buffer,
2453 sizeof(memory_buffer),
2454 m_target.GetArchitecture().GetByteOrder(),
2455 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002456
2457 // Excerpt from src/queue_private.h
2458 struct dispatch_queue_offsets_s
2459 {
2460 uint16_t dqo_version;
2461 uint16_t dqo_label;
2462 uint16_t dqo_label_size;
2463 } dispatch_queue_offsets;
2464
2465
2466 Error error;
2467 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2468 {
2469 uint32_t data_offset = 0;
2470 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2471 {
2472 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2473 {
2474 data_offset = 0;
2475 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2476 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2477 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2478 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2479 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2480 dispatch_queue_name.erase (bytes_read);
2481 }
2482 }
2483 }
2484 }
2485 if (dispatch_queue_name.empty())
2486 return NULL;
2487 return dispatch_queue_name.c_str();
2488}
2489
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002490//uint32_t
2491//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2492//{
2493// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2494// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2495// if (m_local_debugserver)
2496// {
2497// return Host::ListProcessesMatchingName (name, matches, pids);
2498// }
2499// else
2500// {
2501// // FIXME: Implement talking to the remote debugserver.
2502// return 0;
2503// }
2504//
2505//}
2506//
Jim Ingham55e01d82011-01-22 01:33:44 +00002507bool
2508ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2509 lldb_private::StoppointCallbackContext *context,
2510 lldb::user_id_t break_id,
2511 lldb::user_id_t break_loc_id)
2512{
2513 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2514 // run so I can stop it if that's what I want to do.
2515 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2516 if (log)
2517 log->Printf("Hit New Thread Notification breakpoint.");
2518 return false;
2519}
2520
2521
2522bool
2523ProcessGDBRemote::StartNoticingNewThreads()
2524{
2525 static const char *bp_names[] =
2526 {
2527 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002528 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002529 "_pthread_start",
2530 NULL
2531 };
2532
2533 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2534 size_t num_bps = m_thread_observation_bps.size();
2535 if (num_bps != 0)
2536 {
2537 for (int i = 0; i < num_bps; i++)
2538 {
2539 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2540 if (break_sp)
2541 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002542 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002543 log->Printf("Enabled noticing new thread breakpoint.");
2544 break_sp->SetEnabled(true);
2545 }
2546 }
2547 }
2548 else
2549 {
2550 for (int i = 0; bp_names[i] != NULL; i++)
2551 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002552 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002553 if (breakpoint)
2554 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002555 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002556 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2557 m_thread_observation_bps.push_back(breakpoint->GetID());
2558 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2559 }
2560 else
2561 {
2562 if (log)
2563 log->Printf("Failed to create new thread notification breakpoint.");
2564 return false;
2565 }
2566 }
2567 }
2568
2569 return true;
2570}
2571
2572bool
2573ProcessGDBRemote::StopNoticingNewThreads()
2574{
Jim Inghamff276fe2011-02-08 05:19:01 +00002575 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002576 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002577 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002578 size_t num_bps = m_thread_observation_bps.size();
2579 if (num_bps != 0)
2580 {
2581 for (int i = 0; i < num_bps; i++)
2582 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002583
2584 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2585 if (break_sp)
2586 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002587 break_sp->SetEnabled(false);
2588 }
2589 }
2590 }
2591 return true;
2592}
2593
2594