blob: 4f77d92456424d898fc7d6e28df6ad3469a57b85 [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 Clayton75ccf502010-08-21 02:22:51 +0000125 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000126 m_last_stop_packet (),
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{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000148 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000149 {
150 Host::ThreadCancel (m_debugserver_thread, NULL);
151 thread_result_t thread_result;
152 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
153 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
154 }
Chris Lattner24943d22010-06-08 16:52:24 +0000155 // m_mach_process.UnregisterNotificationCallbacks (this);
156 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000157 // We need to call finalize on the process before destroying ourselves
158 // to make sure all of the broadcaster cleanup goes as planned. If we
159 // destruct this class, then Process::~Process() might have problems
160 // trying to fully destroy the broadcaster.
161 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000162}
163
164//----------------------------------------------------------------------
165// PluginInterface
166//----------------------------------------------------------------------
167const char *
168ProcessGDBRemote::GetPluginName()
169{
170 return "Process debugging plug-in that uses the GDB remote protocol";
171}
172
173const char *
174ProcessGDBRemote::GetShortPluginName()
175{
176 return GetPluginNameStatic();
177}
178
179uint32_t
180ProcessGDBRemote::GetPluginVersion()
181{
182 return 1;
183}
184
185void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000186ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000187{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000188 if (!force && m_register_info.GetNumRegisters() > 0)
189 return;
190
191 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000192 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000193 uint32_t reg_offset = 0;
194 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000195 StringExtractorGDBRemote::ResponseType response_type;
196 for (response_type = StringExtractorGDBRemote::eResponse;
197 response_type == StringExtractorGDBRemote::eResponse;
198 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000199 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000200 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
201 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000202 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000203 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000204 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000205 response_type = response.GetResponseType();
206 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000207 {
208 std::string name;
209 std::string value;
210 ConstString reg_name;
211 ConstString alt_name;
212 ConstString set_name;
213 RegisterInfo reg_info = { NULL, // Name
214 NULL, // Alt name
215 0, // byte size
216 reg_offset, // offset
217 eEncodingUint, // encoding
218 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000219 {
220 LLDB_INVALID_REGNUM, // GCC reg num
221 LLDB_INVALID_REGNUM, // DWARF reg num
222 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000223 reg_num, // GDB reg num
224 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000225 }
226 };
227
228 while (response.GetNameColonValue(name, value))
229 {
230 if (name.compare("name") == 0)
231 {
232 reg_name.SetCString(value.c_str());
233 }
234 else if (name.compare("alt-name") == 0)
235 {
236 alt_name.SetCString(value.c_str());
237 }
238 else if (name.compare("bitsize") == 0)
239 {
240 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
241 }
242 else if (name.compare("offset") == 0)
243 {
244 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000245 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000246 {
247 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000248 }
249 }
250 else if (name.compare("encoding") == 0)
251 {
252 if (value.compare("uint") == 0)
253 reg_info.encoding = eEncodingUint;
254 else if (value.compare("sint") == 0)
255 reg_info.encoding = eEncodingSint;
256 else if (value.compare("ieee754") == 0)
257 reg_info.encoding = eEncodingIEEE754;
258 else if (value.compare("vector") == 0)
259 reg_info.encoding = eEncodingVector;
260 }
261 else if (name.compare("format") == 0)
262 {
263 if (value.compare("binary") == 0)
264 reg_info.format = eFormatBinary;
265 else if (value.compare("decimal") == 0)
266 reg_info.format = eFormatDecimal;
267 else if (value.compare("hex") == 0)
268 reg_info.format = eFormatHex;
269 else if (value.compare("float") == 0)
270 reg_info.format = eFormatFloat;
271 else if (value.compare("vector-sint8") == 0)
272 reg_info.format = eFormatVectorOfSInt8;
273 else if (value.compare("vector-uint8") == 0)
274 reg_info.format = eFormatVectorOfUInt8;
275 else if (value.compare("vector-sint16") == 0)
276 reg_info.format = eFormatVectorOfSInt16;
277 else if (value.compare("vector-uint16") == 0)
278 reg_info.format = eFormatVectorOfUInt16;
279 else if (value.compare("vector-sint32") == 0)
280 reg_info.format = eFormatVectorOfSInt32;
281 else if (value.compare("vector-uint32") == 0)
282 reg_info.format = eFormatVectorOfUInt32;
283 else if (value.compare("vector-float32") == 0)
284 reg_info.format = eFormatVectorOfFloat32;
285 else if (value.compare("vector-uint128") == 0)
286 reg_info.format = eFormatVectorOfUInt128;
287 }
288 else if (name.compare("set") == 0)
289 {
290 set_name.SetCString(value.c_str());
291 }
292 else if (name.compare("gcc") == 0)
293 {
294 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
295 }
296 else if (name.compare("dwarf") == 0)
297 {
298 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
299 }
300 else if (name.compare("generic") == 0)
301 {
302 if (value.compare("pc") == 0)
303 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
304 else if (value.compare("sp") == 0)
305 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
306 else if (value.compare("fp") == 0)
307 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
308 else if (value.compare("ra") == 0)
309 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
310 else if (value.compare("flags") == 0)
311 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000312 else if (value.find("arg") == 0)
313 {
314 if (value.size() == 4)
315 {
316 switch (value[3])
317 {
318 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
319 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
320 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
321 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
322 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
323 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
324 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
325 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
326 }
327 }
328 }
Chris Lattner24943d22010-06-08 16:52:24 +0000329 }
330 }
331
Jason Molenda53d96862010-06-11 23:44:18 +0000332 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000333 assert (reg_info.byte_size != 0);
334 reg_offset += reg_info.byte_size;
335 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
336 }
337 }
338 else
339 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000340 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000341 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000342 }
343 }
344
345 if (reg_num == 0)
346 {
347 // We didn't get anything. See if we are debugging ARM and fill with
348 // a hard coded register set until we can get an updated debugserver
349 // down on the devices.
Jason Molenda428b5502011-10-06 01:45:46 +0000350
351 if (!GetTarget().GetArchitecture().IsValid()
352 && m_gdb_comm.GetHostArchitecture().IsValid()
353 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm
354 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
355 {
Chris Lattner24943d22010-06-08 16:52:24 +0000356 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000357 }
358 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
359 {
360 m_register_info.HardcodeARMRegisters();
361 }
Chris Lattner24943d22010-06-08 16:52:24 +0000362 }
363 m_register_info.Finalize ();
364}
365
366Error
367ProcessGDBRemote::WillLaunch (Module* module)
368{
369 return WillLaunchOrAttach ();
370}
371
372Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000373ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000374{
375 return WillLaunchOrAttach ();
376}
377
378Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000379ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000380{
381 return WillLaunchOrAttach ();
382}
383
384Error
Greg Claytone71e2582011-02-04 01:58:07 +0000385ProcessGDBRemote::DoConnectRemote (const char *remote_url)
386{
387 Error error (WillLaunchOrAttach ());
388
389 if (error.Fail())
390 return error;
391
Greg Clayton180546b2011-04-30 01:09:13 +0000392 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000393
394 if (error.Fail())
395 return error;
396 StartAsyncThread ();
397
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000398 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000399 if (pid == LLDB_INVALID_PROCESS_ID)
400 {
401 // We don't have a valid process ID, so note that we are connected
402 // and could now request to launch or attach, or get remote process
403 // listings...
404 SetPrivateState (eStateConnected);
405 }
406 else
407 {
408 // We have a valid process
409 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000410 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000411 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000412 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000413 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000414 if (state == eStateStopped)
415 {
416 SetPrivateState (state);
417 }
418 else
419 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
420 }
421 else
422 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
423 }
424 return error;
425}
426
427Error
Chris Lattner24943d22010-06-08 16:52:24 +0000428ProcessGDBRemote::WillLaunchOrAttach ()
429{
430 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000431 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000432 return error;
433}
434
435//----------------------------------------------------------------------
436// Process Control
437//----------------------------------------------------------------------
438Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000439ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000440{
Greg Clayton4b407112010-09-30 21:49:03 +0000441 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000442
443 uint32_t launch_flags = launch_info.GetFlags().Get();
444 const char *stdin_path = NULL;
445 const char *stdout_path = NULL;
446 const char *stderr_path = NULL;
447 const char *working_dir = launch_info.GetWorkingDirectory();
448
449 const ProcessLaunchInfo::FileAction *file_action;
450 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
451 if (file_action)
452 {
453 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
454 stdin_path = file_action->GetPath();
455 }
456 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
457 if (file_action)
458 {
459 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
460 stdout_path = file_action->GetPath();
461 }
462 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
463 if (file_action)
464 {
465 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
466 stderr_path = file_action->GetPath();
467 }
468
Chris Lattner24943d22010-06-08 16:52:24 +0000469 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
470 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
471 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000472 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000473
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000474 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000475 if (object_file)
476 {
Chris Lattner24943d22010-06-08 16:52:24 +0000477 char host_port[128];
478 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000479 char connect_url[128];
480 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000481
Greg Claytona2f74232011-02-24 22:24:29 +0000482 // Make sure we aren't already connected?
483 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000484 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000485 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000486 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000487 {
Johnny Chenc143d622011-08-09 18:56:45 +0000488 if (log)
489 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000490 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000491 }
Chris Lattner24943d22010-06-08 16:52:24 +0000492
Greg Claytone71e2582011-02-04 01:58:07 +0000493 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000494 }
495
496 if (error.Success())
497 {
498 lldb_utility::PseudoTerminal pty;
499 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000500
501 // If the debugserver is local and we aren't disabling STDIO, lets use
502 // a pseudo terminal to instead of relying on the 'O' packets for stdio
503 // since 'O' packets can really slow down debugging if the inferior
504 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000505 PlatformSP platform_sp (m_target.GetPlatform());
506 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000507 {
508 const char *slave_name = NULL;
509 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000510 {
Greg Claytona2f74232011-02-24 22:24:29 +0000511 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
512 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000513 }
Greg Claytona2f74232011-02-24 22:24:29 +0000514 if (stdin_path == NULL)
515 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000516
Greg Claytona2f74232011-02-24 22:24:29 +0000517 if (stdout_path == NULL)
518 stdout_path = slave_name;
519
520 if (stderr_path == NULL)
521 stderr_path = slave_name;
522 }
523
Greg Claytonafb81862011-03-02 21:34:46 +0000524 // Set STDIN to /dev/null if we want STDIO disabled or if either
525 // STDOUT or STDERR have been set to something and STDIN hasn't
526 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000527 stdin_path = "/dev/null";
528
Greg Claytonafb81862011-03-02 21:34:46 +0000529 // Set STDOUT to /dev/null if we want STDIO disabled or if either
530 // STDIN or STDERR have been set to something and STDOUT hasn't
531 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000532 stdout_path = "/dev/null";
533
Greg Claytonafb81862011-03-02 21:34:46 +0000534 // Set STDERR to /dev/null if we want STDIO disabled or if either
535 // STDIN or STDOUT have been set to something and STDERR hasn't
536 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000537 stderr_path = "/dev/null";
538
539 if (stdin_path)
540 m_gdb_comm.SetSTDIN (stdin_path);
541 if (stdout_path)
542 m_gdb_comm.SetSTDOUT (stdout_path);
543 if (stderr_path)
544 m_gdb_comm.SetSTDERR (stderr_path);
545
546 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
547
Greg Claytona4582402011-05-08 04:53:50 +0000548 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000549
550 if (working_dir && working_dir[0])
551 {
552 m_gdb_comm.SetWorkingDir (working_dir);
553 }
554
555 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000556 const Args &environment = launch_info.GetEnvironmentEntries();
557 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000558 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000559 size_t num_environment_entries = environment.GetArgumentCount();
560 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000561 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000562 const char *env_entry = environment.GetArgumentAtIndex(i);
563 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000564 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000565 }
Greg Claytona2f74232011-02-24 22:24:29 +0000566 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000567
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000568 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000569 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000570 if (arg_packet_err == 0)
571 {
572 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000573 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000574 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000575 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000576 }
577 else
578 {
Greg Claytona2f74232011-02-24 22:24:29 +0000579 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000580 }
Greg Claytona2f74232011-02-24 22:24:29 +0000581 }
582 else
583 {
Greg Clayton9c236732011-10-26 00:56:27 +0000584 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000585 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000586
587 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000588
Greg Claytona2f74232011-02-24 22:24:29 +0000589 if (GetID() == LLDB_INVALID_PROCESS_ID)
590 {
Johnny Chenc143d622011-08-09 18:56:45 +0000591 if (log)
592 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000593 KillDebugserverProcess ();
594 return error;
595 }
596
Greg Clayton261a18b2011-06-02 22:22:38 +0000597 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000598 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000599 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000600
601 if (!disable_stdio)
602 {
603 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
604 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
605 }
Chris Lattner24943d22010-06-08 16:52:24 +0000606 }
607 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000608 else
609 {
Johnny Chenc143d622011-08-09 18:56:45 +0000610 if (log)
611 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000612 }
Chris Lattner24943d22010-06-08 16:52:24 +0000613 }
614 else
615 {
616 // Set our user ID to an invalid process ID.
617 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000618 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
619 exe_module->GetFileSpec().GetFilename().AsCString(),
620 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000621 }
Chris Lattner24943d22010-06-08 16:52:24 +0000622 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000623
Chris Lattner24943d22010-06-08 16:52:24 +0000624}
625
626
627Error
Greg Claytone71e2582011-02-04 01:58:07 +0000628ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000629{
630 Error error;
631 // Sleep and wait a bit for debugserver to start to listen...
632 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
633 if (conn_ap.get())
634 {
Chris Lattner24943d22010-06-08 16:52:24 +0000635 const uint32_t max_retry_count = 50;
636 uint32_t retry_count = 0;
637 while (!m_gdb_comm.IsConnected())
638 {
Greg Claytone71e2582011-02-04 01:58:07 +0000639 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000640 {
641 m_gdb_comm.SetConnection (conn_ap.release());
642 break;
643 }
644 retry_count++;
645
646 if (retry_count >= max_retry_count)
647 break;
648
649 usleep (100000);
650 }
651 }
652
653 if (!m_gdb_comm.IsConnected())
654 {
655 if (error.Success())
656 error.SetErrorString("not connected to remote gdb server");
657 return error;
658 }
659
Greg Clayton24bc5d92011-03-30 18:16:51 +0000660 // We always seem to be able to open a connection to a local port
661 // so we need to make sure we can then send data to it. If we can't
662 // then we aren't actually connected to anything, so try and do the
663 // handshake with the remote GDB server and make sure that goes
664 // alright.
665 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000666 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000667 m_gdb_comm.Disconnect();
668 if (error.Success())
669 error.SetErrorString("not connected to remote gdb server");
670 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000671 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000672 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
673 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
674 this,
675 m_debugserver_pid,
676 false);
677 m_gdb_comm.ResetDiscoverableSettings();
678 m_gdb_comm.QueryNoAckModeSupported ();
679 m_gdb_comm.GetThreadSuffixSupported ();
680 m_gdb_comm.GetHostInfo ();
681 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000682 return error;
683}
684
685void
686ProcessGDBRemote::DidLaunchOrAttach ()
687{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000688 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
689 if (log)
690 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000691 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000692 {
693 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
694
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000695 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000696
Chris Lattner24943d22010-06-08 16:52:24 +0000697 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000698
Greg Claytoncb8977d2011-03-23 00:09:55 +0000699 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
700 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000701 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000702 ArchSpec &target_arch = GetTarget().GetArchitecture();
703
704 if (target_arch.IsValid())
705 {
706 // If the remote host is ARM and we have apple as the vendor, then
707 // ARM executables and shared libraries can have mixed ARM architectures.
708 // You can have an armv6 executable, and if the host is armv7, then the
709 // system will load the best possible architecture for all shared libraries
710 // it has, so we really need to take the remote host architecture as our
711 // defacto architecture in this case.
712
713 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
714 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
715 {
716 target_arch = gdb_remote_arch;
717 }
718 else
719 {
720 // Fill in what is missing in the triple
721 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
722 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000723 if (target_triple.getVendorName().size() == 0)
724 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000725 target_triple.setVendor (remote_triple.getVendor());
726
Greg Clayton2f085c62011-05-15 01:25:55 +0000727 if (target_triple.getOSName().size() == 0)
728 {
729 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000730
Greg Clayton2f085c62011-05-15 01:25:55 +0000731 if (target_triple.getEnvironmentName().size() == 0)
732 target_triple.setEnvironment (remote_triple.getEnvironment());
733 }
734 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000735 }
736 }
737 else
738 {
739 // The target doesn't have a valid architecture yet, set it from
740 // the architecture we got from the remote GDB server
741 target_arch = gdb_remote_arch;
742 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000743 }
Chris Lattner24943d22010-06-08 16:52:24 +0000744 }
745}
746
747void
748ProcessGDBRemote::DidLaunch ()
749{
750 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000751}
752
753Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000754ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000755{
756 Error error;
757 // Clear out and clean up from any current state
758 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000759 if (attach_pid != LLDB_INVALID_PROCESS_ID)
760 {
Greg Claytona2f74232011-02-24 22:24:29 +0000761 // Make sure we aren't already connected?
762 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000763 {
Greg Claytona2f74232011-02-24 22:24:29 +0000764 char host_port[128];
765 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
766 char connect_url[128];
767 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000768
Greg Claytonb72d0f02011-04-12 05:54:46 +0000769 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000770
771 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000772 {
Greg Claytona2f74232011-02-24 22:24:29 +0000773 const char *error_string = error.AsCString();
774 if (error_string == NULL)
775 error_string = "unable to launch " DEBUGSERVER_BASENAME;
776
777 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000778 }
Greg Claytona2f74232011-02-24 22:24:29 +0000779 else
780 {
781 error = ConnectToDebugserver (connect_url);
782 }
783 }
784
785 if (error.Success())
786 {
787 char packet[64];
788 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
789
790 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000791 }
792 }
Chris Lattner24943d22010-06-08 16:52:24 +0000793 return error;
794}
795
796size_t
797ProcessGDBRemote::AttachInputReaderCallback
798(
799 void *baton,
800 InputReader *reader,
801 lldb::InputReaderAction notification,
802 const char *bytes,
803 size_t bytes_len
804)
805{
806 if (notification == eInputReaderGotToken)
807 {
808 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
809 if (gdb_process->m_waiting_for_attach)
810 gdb_process->m_waiting_for_attach = false;
811 reader->SetIsDone(true);
812 return 1;
813 }
814 return 0;
815}
816
817Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000818ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000819{
820 Error error;
821 // Clear out and clean up from any current state
822 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000823
Chris Lattner24943d22010-06-08 16:52:24 +0000824 if (process_name && process_name[0])
825 {
Greg Claytona2f74232011-02-24 22:24:29 +0000826 // Make sure we aren't already connected?
827 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000828 {
Greg Claytona2f74232011-02-24 22:24:29 +0000829 char host_port[128];
830 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
831 char connect_url[128];
832 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
833
Greg Claytonb72d0f02011-04-12 05:54:46 +0000834 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000835 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000836 {
Greg Claytona2f74232011-02-24 22:24:29 +0000837 const char *error_string = error.AsCString();
838 if (error_string == NULL)
839 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000840
Greg Claytona2f74232011-02-24 22:24:29 +0000841 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000842 }
Greg Claytona2f74232011-02-24 22:24:29 +0000843 else
844 {
845 error = ConnectToDebugserver (connect_url);
846 }
847 }
848
849 if (error.Success())
850 {
851 StreamString packet;
852
853 if (wait_for_launch)
854 packet.PutCString("vAttachWait");
855 else
856 packet.PutCString("vAttachName");
857 packet.PutChar(';');
858 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
859
860 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
861
Chris Lattner24943d22010-06-08 16:52:24 +0000862 }
863 }
Chris Lattner24943d22010-06-08 16:52:24 +0000864 return error;
865}
866
Chris Lattner24943d22010-06-08 16:52:24 +0000867
868void
869ProcessGDBRemote::DidAttach ()
870{
Greg Claytone71e2582011-02-04 01:58:07 +0000871 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000872}
873
874Error
875ProcessGDBRemote::WillResume ()
876{
Greg Claytonc1f45872011-02-12 06:28:37 +0000877 m_continue_c_tids.clear();
878 m_continue_C_tids.clear();
879 m_continue_s_tids.clear();
880 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000881 return Error();
882}
883
884Error
885ProcessGDBRemote::DoResume ()
886{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000887 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000888 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
889 if (log)
890 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000891
892 Listener listener ("gdb-remote.resume-packet-sent");
893 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
894 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000895 StreamString continue_packet;
896 bool continue_packet_error = false;
897 if (m_gdb_comm.HasAnyVContSupport ())
898 {
899 continue_packet.PutCString ("vCont");
900
901 if (!m_continue_c_tids.empty())
902 {
903 if (m_gdb_comm.GetVContSupported ('c'))
904 {
905 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)
906 continue_packet.Printf(";c:%4.4x", *t_pos);
907 }
908 else
909 continue_packet_error = true;
910 }
911
912 if (!continue_packet_error && !m_continue_C_tids.empty())
913 {
914 if (m_gdb_comm.GetVContSupported ('C'))
915 {
916 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)
917 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
918 }
919 else
920 continue_packet_error = true;
921 }
Greg Claytonb749a262010-12-03 06:02:24 +0000922
Greg Claytonc1f45872011-02-12 06:28:37 +0000923 if (!continue_packet_error && !m_continue_s_tids.empty())
924 {
925 if (m_gdb_comm.GetVContSupported ('s'))
926 {
927 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)
928 continue_packet.Printf(";s:%4.4x", *t_pos);
929 }
930 else
931 continue_packet_error = true;
932 }
933
934 if (!continue_packet_error && !m_continue_S_tids.empty())
935 {
936 if (m_gdb_comm.GetVContSupported ('S'))
937 {
938 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)
939 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
940 }
941 else
942 continue_packet_error = true;
943 }
944
945 if (continue_packet_error)
946 continue_packet.GetString().clear();
947 }
948 else
949 continue_packet_error = true;
950
951 if (continue_packet_error)
952 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000953 // Either no vCont support, or we tried to use part of the vCont
954 // packet that wasn't supported by the remote GDB server.
955 // We need to try and make a simple packet that can do our continue
956 const size_t num_threads = GetThreadList().GetSize();
957 const size_t num_continue_c_tids = m_continue_c_tids.size();
958 const size_t num_continue_C_tids = m_continue_C_tids.size();
959 const size_t num_continue_s_tids = m_continue_s_tids.size();
960 const size_t num_continue_S_tids = m_continue_S_tids.size();
961 if (num_continue_c_tids > 0)
962 {
963 if (num_continue_c_tids == num_threads)
964 {
965 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000966 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000967 continue_packet.PutChar ('c');
968 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000969 }
970 else if (num_continue_c_tids == 1 &&
971 num_continue_C_tids == 0 &&
972 num_continue_s_tids == 0 &&
973 num_continue_S_tids == 0 )
974 {
975 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000976 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000977 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000978 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000979 }
980 }
981
Greg Claytonde1dd812011-06-24 03:21:43 +0000982 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000983 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000984 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
985 num_continue_C_tids > 0 &&
986 num_continue_s_tids == 0 &&
987 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000988 {
989 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000990 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +0000991 if (num_continue_C_tids > 1)
992 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000993 // More that one thread with a signal, yet we don't have
994 // vCont support and we are being asked to resume each
995 // thread with a signal, we need to make sure they are
996 // all the same signal, or we can't issue the continue
997 // accurately with the current support...
998 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +0000999 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001000 continue_packet_error = false;
1001 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1002 {
1003 if (m_continue_C_tids[i].second != continue_signo)
1004 continue_packet_error = true;
1005 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001006 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001007 if (!continue_packet_error)
1008 m_gdb_comm.SetCurrentThreadForRun (-1);
1009 }
1010 else
1011 {
1012 // Set the continue thread ID
1013 continue_packet_error = false;
1014 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001015 }
1016 if (!continue_packet_error)
1017 {
1018 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001019 continue_packet.Printf("C%2.2x", continue_signo);
1020 }
1021 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001022 }
1023
Greg Claytonde1dd812011-06-24 03:21:43 +00001024 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001025 {
1026 if (num_continue_s_tids == num_threads)
1027 {
1028 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001029 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001030 continue_packet.PutChar ('s');
1031 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001032 }
1033 else if (num_continue_c_tids == 0 &&
1034 num_continue_C_tids == 0 &&
1035 num_continue_s_tids == 1 &&
1036 num_continue_S_tids == 0 )
1037 {
1038 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001039 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001040 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001041 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001042 }
1043 }
1044
1045 if (!continue_packet_error && num_continue_S_tids > 0)
1046 {
1047 if (num_continue_S_tids == num_threads)
1048 {
1049 const int step_signo = m_continue_S_tids.front().second;
1050 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001051 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001052 if (num_continue_S_tids > 1)
1053 {
1054 for (size_t i=1; i<num_threads; ++i)
1055 {
1056 if (m_continue_S_tids[i].second != step_signo)
1057 continue_packet_error = true;
1058 }
1059 }
1060 if (!continue_packet_error)
1061 {
1062 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001063 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001064 continue_packet.Printf("S%2.2x", step_signo);
1065 }
1066 }
1067 else if (num_continue_c_tids == 0 &&
1068 num_continue_C_tids == 0 &&
1069 num_continue_s_tids == 0 &&
1070 num_continue_S_tids == 1 )
1071 {
1072 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001073 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001074 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001075 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001076 }
1077 }
1078 }
1079
1080 if (continue_packet_error)
1081 {
1082 error.SetErrorString ("can't make continue packet for this resume");
1083 }
1084 else
1085 {
1086 EventSP event_sp;
1087 TimeValue timeout;
1088 timeout = TimeValue::Now();
1089 timeout.OffsetWithSeconds (5);
1090 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1091
1092 if (listener.WaitForEvent (&timeout, event_sp) == false)
1093 error.SetErrorString("Resume timed out.");
1094 }
Greg Claytonb749a262010-12-03 06:02:24 +00001095 }
1096
Jim Ingham3ae449a2010-11-17 02:32:00 +00001097 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001098}
1099
Chris Lattner24943d22010-06-08 16:52:24 +00001100uint32_t
Greg Clayton37f962e2011-08-22 02:49:39 +00001101ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001102{
1103 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001104 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001105 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001106 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001107 // Update the thread list's stop id immediately so we don't recurse into this function.
Chris Lattner24943d22010-06-08 16:52:24 +00001108
Greg Clayton37f962e2011-08-22 02:49:39 +00001109 std::vector<lldb::tid_t> thread_ids;
1110 bool sequence_mutex_unavailable = false;
1111 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1112 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001113 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001114 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001115 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001116 tid_t tid = thread_ids[i];
1117 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1118 if (!thread_sp)
1119 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1120 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001121 }
Chris Lattner24943d22010-06-08 16:52:24 +00001122 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001123
1124 if (sequence_mutex_unavailable == false)
1125 SetThreadStopInfo (m_last_stop_packet);
1126 return new_thread_list.GetSize(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001127}
1128
1129
1130StateType
1131ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1132{
Greg Clayton261a18b2011-06-02 22:22:38 +00001133 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001134 const char stop_type = stop_packet.GetChar();
1135 switch (stop_type)
1136 {
1137 case 'T':
1138 case 'S':
1139 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001140 if (GetStopID() == 0)
1141 {
1142 // Our first stop, make sure we have a process ID, and also make
1143 // sure we know about our registers
1144 if (GetID() == LLDB_INVALID_PROCESS_ID)
1145 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001146 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001147 if (pid != LLDB_INVALID_PROCESS_ID)
1148 SetID (pid);
1149 }
1150 BuildDynamicRegisterInfo (true);
1151 }
Chris Lattner24943d22010-06-08 16:52:24 +00001152 // Stop with signal and thread info
1153 const uint8_t signo = stop_packet.GetHexU8();
1154 std::string name;
1155 std::string value;
1156 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001157 std::string reason;
1158 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001159 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001160 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001161 uint32_t tid = LLDB_INVALID_THREAD_ID;
1162 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1163 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001164 ThreadSP thread_sp;
1165
Chris Lattner24943d22010-06-08 16:52:24 +00001166 while (stop_packet.GetNameColonValue(name, value))
1167 {
1168 if (name.compare("metype") == 0)
1169 {
1170 // exception type in big endian hex
1171 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1172 }
1173 else if (name.compare("mecount") == 0)
1174 {
1175 // exception count in big endian hex
1176 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1177 }
1178 else if (name.compare("medata") == 0)
1179 {
1180 // exception data in big endian hex
1181 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1182 }
1183 else if (name.compare("thread") == 0)
1184 {
1185 // thread in big endian hex
1186 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001187 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001188 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001189 if (!thread_sp)
1190 {
1191 // Create the thread if we need to
1192 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1193 m_thread_list.AddThread(thread_sp);
1194 }
Chris Lattner24943d22010-06-08 16:52:24 +00001195 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001196 else if (name.compare("hexname") == 0)
1197 {
1198 StringExtractor name_extractor;
1199 // Swap "value" over into "name_extractor"
1200 name_extractor.GetStringRef().swap(value);
1201 // Now convert the HEX bytes into a string value
1202 name_extractor.GetHexByteString (value);
1203 thread_name.swap (value);
1204 }
Chris Lattner24943d22010-06-08 16:52:24 +00001205 else if (name.compare("name") == 0)
1206 {
1207 thread_name.swap (value);
1208 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001209 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001210 {
1211 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1212 }
Greg Clayton65611552011-06-04 01:26:29 +00001213 else if (name.compare("reason") == 0)
1214 {
1215 reason.swap(value);
1216 }
1217 else if (name.compare("description") == 0)
1218 {
1219 StringExtractor desc_extractor;
1220 // Swap "value" over into "name_extractor"
1221 desc_extractor.GetStringRef().swap(value);
1222 // Now convert the HEX bytes into a string value
1223 desc_extractor.GetHexByteString (thread_name);
1224 }
Greg Claytona875b642011-01-09 21:07:35 +00001225 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1226 {
1227 // We have a register number that contains an expedited
1228 // register value. Lets supply this register to our thread
1229 // so it won't have to go and read it.
1230 if (thread_sp)
1231 {
1232 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1233
1234 if (reg != UINT32_MAX)
1235 {
1236 StringExtractor reg_value_extractor;
1237 // Swap "value" over into "reg_value_extractor"
1238 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001239 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1240 {
1241 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1242 name.c_str(),
1243 reg,
1244 reg,
1245 reg_value_extractor.GetStringRef().c_str(),
1246 stop_packet.GetStringRef().c_str());
1247 }
Greg Claytona875b642011-01-09 21:07:35 +00001248 }
1249 }
1250 }
Chris Lattner24943d22010-06-08 16:52:24 +00001251 }
Chris Lattner24943d22010-06-08 16:52:24 +00001252
1253 if (thread_sp)
1254 {
1255 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1256
1257 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001258 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001259 if (exc_type != 0)
1260 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001261 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001262
1263 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1264 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001265 exc_data_size,
1266 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001267 exc_data_size >= 2 ? exc_data[1] : 0,
1268 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001269 }
Greg Clayton65611552011-06-04 01:26:29 +00001270 else
Chris Lattner24943d22010-06-08 16:52:24 +00001271 {
Greg Clayton65611552011-06-04 01:26:29 +00001272 bool handled = false;
1273 if (!reason.empty())
1274 {
1275 if (reason.compare("trace") == 0)
1276 {
1277 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1278 handled = true;
1279 }
1280 else if (reason.compare("breakpoint") == 0)
1281 {
1282 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1283 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1284 if (bp_site_sp)
1285 {
1286 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1287 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1288 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1289 if (bp_site_sp->ValidForThisThread (gdb_thread))
1290 {
1291 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1292 handled = true;
1293 }
1294 }
1295
1296 if (!handled)
1297 {
1298 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1299 }
1300 }
1301 else if (reason.compare("trap") == 0)
1302 {
1303 // Let the trap just use the standard signal stop reason below...
1304 }
1305 else if (reason.compare("watchpoint") == 0)
1306 {
1307 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1308 // TODO: locate the watchpoint somehow...
1309 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1310 handled = true;
1311 }
1312 else if (reason.compare("exception") == 0)
1313 {
1314 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1315 handled = true;
1316 }
1317 }
1318
1319 if (signo)
1320 {
1321 if (signo == SIGTRAP)
1322 {
1323 // Currently we are going to assume SIGTRAP means we are either
1324 // hitting a breakpoint or hardware single stepping.
1325 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1326 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1327 if (bp_site_sp)
1328 {
1329 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1330 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1331 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1332 if (bp_site_sp->ValidForThisThread (gdb_thread))
1333 {
1334 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1335 handled = true;
1336 }
1337 }
1338 if (!handled)
1339 {
1340 // TODO: check for breakpoint or trap opcode in case there is a hard
1341 // coded software trap
1342 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1343 handled = true;
1344 }
1345 }
1346 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001347 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001348 }
1349 else
1350 {
Greg Clayton643ee732010-08-04 01:40:35 +00001351 StopInfoSP invalid_stop_info_sp;
1352 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001353 }
Greg Clayton65611552011-06-04 01:26:29 +00001354
1355 if (!description.empty())
1356 {
1357 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1358 if (stop_info_sp)
1359 {
1360 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001361 }
Greg Clayton65611552011-06-04 01:26:29 +00001362 else
1363 {
1364 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1365 }
1366 }
1367 }
Chris Lattner24943d22010-06-08 16:52:24 +00001368 }
1369 return eStateStopped;
1370 }
1371 break;
1372
1373 case 'W':
1374 // process exited
1375 return eStateExited;
1376
1377 default:
1378 break;
1379 }
1380 return eStateInvalid;
1381}
1382
1383void
1384ProcessGDBRemote::RefreshStateAfterStop ()
1385{
Chris Lattner24943d22010-06-08 16:52:24 +00001386 // Let all threads recover from stopping and do any clean up based
1387 // on the previous thread state (if any).
1388 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001389 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001390}
1391
1392Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001393ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001394{
1395 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001396
Greg Claytona4881d02011-01-22 07:12:45 +00001397 bool timed_out = false;
1398 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001399
1400 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001401 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001402 // We are being asked to halt during an attach. We need to just close
1403 // our file handle and debugserver will go away, and we can be done...
1404 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001405 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001406 else
1407 {
1408 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1409 {
1410 if (timed_out)
1411 error.SetErrorString("timed out sending interrupt packet");
1412 else
1413 error.SetErrorString("unknown error sending interrupt packet");
1414 }
1415 }
Chris Lattner24943d22010-06-08 16:52:24 +00001416 return error;
1417}
1418
1419Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001420ProcessGDBRemote::InterruptIfRunning
1421(
1422 bool discard_thread_plans,
1423 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001424 EventSP &stop_event_sp
1425)
Chris Lattner24943d22010-06-08 16:52:24 +00001426{
1427 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001428
Greg Clayton2860ba92011-01-23 19:58:49 +00001429 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1430
Greg Clayton68ca8232011-01-25 02:58:48 +00001431 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001432 const bool is_running = m_gdb_comm.IsRunning();
1433 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001434 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001435 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001436 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001437 is_running);
1438
Greg Clayton2860ba92011-01-23 19:58:49 +00001439 if (discard_thread_plans)
1440 {
1441 if (log)
1442 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1443 m_thread_list.DiscardThreadPlans();
1444 }
1445 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001446 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001447 if (catch_stop_event)
1448 {
1449 if (log)
1450 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1451 PausePrivateStateThread();
1452 paused_private_state_thread = true;
1453 }
1454
Greg Clayton4fb400f2010-09-27 21:07:38 +00001455 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001456 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001457 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001458
Greg Clayton72e1c782011-01-22 23:43:18 +00001459 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001460 {
1461 if (timed_out)
1462 error.SetErrorString("timed out sending interrupt packet");
1463 else
1464 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001465 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001466 ResumePrivateStateThread();
1467 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001468 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001469
Greg Clayton72e1c782011-01-22 23:43:18 +00001470 if (catch_stop_event)
1471 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001472 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001473 TimeValue timeout_time;
1474 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001475 timeout_time.OffsetWithSeconds(5);
1476 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001477
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001478 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001479 if (log)
1480 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001481
Greg Clayton2860ba92011-01-23 19:58:49 +00001482 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001483 error.SetErrorString("unable to verify target stopped");
1484 }
1485
Greg Clayton68ca8232011-01-25 02:58:48 +00001486 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001487 {
1488 if (log)
1489 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001490 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001491 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001492 }
Chris Lattner24943d22010-06-08 16:52:24 +00001493 return error;
1494}
1495
Greg Clayton4fb400f2010-09-27 21:07:38 +00001496Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001497ProcessGDBRemote::WillDetach ()
1498{
Greg Clayton2860ba92011-01-23 19:58:49 +00001499 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1500 if (log)
1501 log->Printf ("ProcessGDBRemote::WillDetach()");
1502
Greg Clayton72e1c782011-01-22 23:43:18 +00001503 bool discard_thread_plans = true;
1504 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001505 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001506 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001507}
1508
1509Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001510ProcessGDBRemote::DoDetach()
1511{
1512 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001513 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001514 if (log)
1515 log->Printf ("ProcessGDBRemote::DoDetach()");
1516
1517 DisableAllBreakpointSites ();
1518
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001519 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001520
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001521 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1522 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001523 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001524 if (response_size)
1525 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1526 else
1527 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001528 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001529 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001530 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001531
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001532 SetPrivateState (eStateDetached);
1533 ResumePrivateStateThread();
1534
1535 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001536 return error;
1537}
Chris Lattner24943d22010-06-08 16:52:24 +00001538
1539Error
1540ProcessGDBRemote::DoDestroy ()
1541{
1542 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001543 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001544 if (log)
1545 log->Printf ("ProcessGDBRemote::DoDestroy()");
1546
1547 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001548 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001549 {
Jim Ingham8226e942011-10-28 01:11:35 +00001550 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001551 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001552
1553 StringExtractorGDBRemote response;
1554 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001555 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001556 {
1557 char packet_cmd = response.GetChar(0);
1558
1559 if (packet_cmd == 'W' || packet_cmd == 'X')
1560 {
1561 m_last_stop_packet = response;
1562 SetExitStatus(response.GetHexU8(), NULL);
1563 }
1564 }
1565 else
1566 {
1567 SetExitStatus(SIGABRT, NULL);
1568 //error.SetErrorString("kill packet failed");
1569 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001570 }
1571 }
Chris Lattner24943d22010-06-08 16:52:24 +00001572 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001573 KillDebugserverProcess ();
1574 return error;
1575}
1576
Chris Lattner24943d22010-06-08 16:52:24 +00001577//------------------------------------------------------------------
1578// Process Queries
1579//------------------------------------------------------------------
1580
1581bool
1582ProcessGDBRemote::IsAlive ()
1583{
Greg Clayton58e844b2010-12-08 05:08:21 +00001584 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001585}
1586
1587addr_t
1588ProcessGDBRemote::GetImageInfoAddress()
1589{
1590 if (!m_gdb_comm.IsRunning())
1591 {
1592 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001593 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001594 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001595 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001596 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1597 }
1598 }
1599 return LLDB_INVALID_ADDRESS;
1600}
1601
Chris Lattner24943d22010-06-08 16:52:24 +00001602//------------------------------------------------------------------
1603// Process Memory
1604//------------------------------------------------------------------
1605size_t
1606ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1607{
1608 if (size > m_max_memory_size)
1609 {
1610 // Keep memory read sizes down to a sane limit. This function will be
1611 // called multiple times in order to complete the task by
1612 // lldb_private::Process so it is ok to do this.
1613 size = m_max_memory_size;
1614 }
1615
1616 char packet[64];
1617 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1618 assert (packet_len + 1 < sizeof(packet));
1619 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001620 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001621 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001622 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001623 {
1624 error.Clear();
1625 return response.GetHexBytes(buf, size, '\xdd');
1626 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001627 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001628 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001629 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001630 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1631 else
1632 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1633 }
1634 else
1635 {
1636 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1637 }
1638 return 0;
1639}
1640
1641size_t
1642ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1643{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001644 if (size > m_max_memory_size)
1645 {
1646 // Keep memory read sizes down to a sane limit. This function will be
1647 // called multiple times in order to complete the task by
1648 // lldb_private::Process so it is ok to do this.
1649 size = m_max_memory_size;
1650 }
1651
Chris Lattner24943d22010-06-08 16:52:24 +00001652 StreamString packet;
1653 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001654 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001655 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001656 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001657 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001658 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001659 {
1660 error.Clear();
1661 return size;
1662 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001663 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001664 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001665 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001666 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1667 else
1668 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1669 }
1670 else
1671 {
1672 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1673 }
1674 return 0;
1675}
1676
1677lldb::addr_t
1678ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1679{
Greg Clayton989816b2011-05-14 01:50:35 +00001680 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1681
Greg Clayton2f085c62011-05-15 01:25:55 +00001682 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001683 switch (supported)
1684 {
1685 case eLazyBoolCalculate:
1686 case eLazyBoolYes:
1687 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1688 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1689 return allocated_addr;
1690
1691 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001692 // Call mmap() to create memory in the inferior..
1693 unsigned prot = 0;
1694 if (permissions & lldb::ePermissionsReadable)
1695 prot |= eMmapProtRead;
1696 if (permissions & lldb::ePermissionsWritable)
1697 prot |= eMmapProtWrite;
1698 if (permissions & lldb::ePermissionsExecutable)
1699 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001700
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001701 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1702 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1703 m_addr_to_mmap_size[allocated_addr] = size;
1704 else
1705 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001706 break;
1707 }
1708
Chris Lattner24943d22010-06-08 16:52:24 +00001709 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001710 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001711 else
1712 error.Clear();
1713 return allocated_addr;
1714}
1715
1716Error
1717ProcessGDBRemote::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 Claytonb72d0f02011-04-12 05:54:46 +00002125 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002126
Greg Claytonb72d0f02011-04-12 05:54:46 +00002127 if (error.Success ())
2128 m_debugserver_pid = launch_info.GetProcessID();
2129 else
Chris Lattner24943d22010-06-08 16:52:24 +00002130 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2131
2132 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002133 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002134 }
2135 else
2136 {
Greg Clayton9c236732011-10-26 00:56:27 +00002137 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002138 }
2139
2140 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2141 StartAsyncThread ();
2142 }
2143 return error;
2144}
2145
2146bool
2147ProcessGDBRemote::MonitorDebugserverProcess
2148(
2149 void *callback_baton,
2150 lldb::pid_t debugserver_pid,
2151 int signo, // Zero for no signal
2152 int exit_status // Exit value of process if signal is zero
2153)
2154{
2155 // We pass in the ProcessGDBRemote inferior process it and name it
2156 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2157 // pointer value itself, thus we need the double cast...
2158
2159 // "debugserver_pid" argument passed in is the process ID for
2160 // debugserver that we are tracking...
2161
Greg Clayton75ccf502010-08-21 02:22:51 +00002162 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002163
2164 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2165 if (log)
2166 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2167
Greg Clayton75ccf502010-08-21 02:22:51 +00002168 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002169 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002170 // Sleep for a half a second to make sure our inferior process has
2171 // time to set its exit status before we set it incorrectly when
2172 // both the debugserver and the inferior process shut down.
2173 usleep (500000);
2174 // If our process hasn't yet exited, debugserver might have died.
2175 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002176 const StateType state = process->GetState();
2177
2178 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2179 state != eStateInvalid &&
2180 state != eStateUnloaded &&
2181 state != eStateExited &&
2182 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002183 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002184 char error_str[1024];
2185 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002186 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002187 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2188 if (signal_cstr)
2189 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002190 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002191 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002192 }
2193 else
2194 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002195 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
Chris Lattner24943d22010-06-08 16:52:24 +00002196 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002197
2198 process->SetExitStatus (-1, error_str);
2199 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002200 // Debugserver has exited we need to let our ProcessGDBRemote
2201 // know that it no longer has a debugserver instance
2202 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2203 // We are returning true to this function below, so we can
2204 // forget about the monitor handle.
2205 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002206 }
2207 return true;
2208}
2209
2210void
2211ProcessGDBRemote::KillDebugserverProcess ()
2212{
2213 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2214 {
2215 ::kill (m_debugserver_pid, SIGINT);
2216 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2217 }
2218}
2219
2220void
2221ProcessGDBRemote::Initialize()
2222{
2223 static bool g_initialized = false;
2224
2225 if (g_initialized == false)
2226 {
2227 g_initialized = true;
2228 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2229 GetPluginDescriptionStatic(),
2230 CreateInstance);
2231
2232 Log::Callbacks log_callbacks = {
2233 ProcessGDBRemoteLog::DisableLog,
2234 ProcessGDBRemoteLog::EnableLog,
2235 ProcessGDBRemoteLog::ListLogCategories
2236 };
2237
2238 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2239 }
2240}
2241
2242bool
Chris Lattner24943d22010-06-08 16:52:24 +00002243ProcessGDBRemote::StartAsyncThread ()
2244{
Greg Claytone005f2c2010-11-06 01:53:30 +00002245 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002246
2247 if (log)
2248 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2249
2250 // Create a thread that watches our internal state and controls which
2251 // events make it to clients (into the DCProcess event queue).
2252 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002253 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002254}
2255
2256void
2257ProcessGDBRemote::StopAsyncThread ()
2258{
Greg Claytone005f2c2010-11-06 01:53:30 +00002259 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002260
2261 if (log)
2262 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2263
2264 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002265
2266 // This will shut down the async thread.
2267 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002268
2269 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002270 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002271 {
2272 Host::ThreadJoin (m_async_thread, NULL, NULL);
2273 }
2274}
2275
2276
2277void *
2278ProcessGDBRemote::AsyncThread (void *arg)
2279{
2280 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2281
Greg Claytone005f2c2010-11-06 01:53:30 +00002282 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002283 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002284 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002285
2286 Listener listener ("ProcessGDBRemote::AsyncThread");
2287 EventSP event_sp;
2288 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2289 eBroadcastBitAsyncThreadShouldExit;
2290
2291 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2292 {
Greg Claytona2f74232011-02-24 22:24:29 +00002293 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2294
Chris Lattner24943d22010-06-08 16:52:24 +00002295 bool done = false;
2296 while (!done)
2297 {
2298 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002299 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002300 if (listener.WaitForEvent (NULL, event_sp))
2301 {
2302 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002303 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002304 {
Greg Claytona2f74232011-02-24 22:24:29 +00002305 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002306 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 +00002307
Greg Claytona2f74232011-02-24 22:24:29 +00002308 switch (event_type)
2309 {
2310 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002311 {
Greg Claytona2f74232011-02-24 22:24:29 +00002312 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002313
Greg Claytona2f74232011-02-24 22:24:29 +00002314 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002315 {
Greg Claytona2f74232011-02-24 22:24:29 +00002316 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2317 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2318 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002319 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002320
Greg Claytona2f74232011-02-24 22:24:29 +00002321 if (::strstr (continue_cstr, "vAttach") == NULL)
2322 process->SetPrivateState(eStateRunning);
2323 StringExtractorGDBRemote response;
2324 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002325
Greg Claytona2f74232011-02-24 22:24:29 +00002326 switch (stop_state)
2327 {
2328 case eStateStopped:
2329 case eStateCrashed:
2330 case eStateSuspended:
2331 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002332 process->SetPrivateState (stop_state);
2333 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002334
Greg Claytona2f74232011-02-24 22:24:29 +00002335 case eStateExited:
2336 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002337 response.SetFilePos(1);
2338 process->SetExitStatus(response.GetHexU8(), NULL);
2339 done = true;
2340 break;
2341
2342 case eStateInvalid:
2343 process->SetExitStatus(-1, "lost connection");
2344 break;
2345
2346 default:
2347 process->SetPrivateState (stop_state);
2348 break;
2349 }
Chris Lattner24943d22010-06-08 16:52:24 +00002350 }
2351 }
Greg Claytona2f74232011-02-24 22:24:29 +00002352 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002353
Greg Claytona2f74232011-02-24 22:24:29 +00002354 case eBroadcastBitAsyncThreadShouldExit:
2355 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002356 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002357 done = true;
2358 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002359
Greg Claytona2f74232011-02-24 22:24:29 +00002360 default:
2361 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002362 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 +00002363 done = true;
2364 break;
2365 }
2366 }
2367 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2368 {
2369 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2370 {
2371 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002372 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002373 }
Chris Lattner24943d22010-06-08 16:52:24 +00002374 }
2375 }
2376 else
2377 {
2378 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002379 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 +00002380 done = true;
2381 }
2382 }
2383 }
2384
2385 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002386 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002387
2388 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2389 return NULL;
2390}
2391
Chris Lattner24943d22010-06-08 16:52:24 +00002392const char *
2393ProcessGDBRemote::GetDispatchQueueNameForThread
2394(
2395 addr_t thread_dispatch_qaddr,
2396 std::string &dispatch_queue_name
2397)
2398{
2399 dispatch_queue_name.clear();
2400 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2401 {
2402 // Cache the dispatch_queue_offsets_addr value so we don't always have
2403 // to look it up
2404 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2405 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002406 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2407 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002408 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002409 if (module_sp)
2410 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2411
2412 if (dispatch_queue_offsets_symbol == NULL)
2413 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002414 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002415 if (module_sp)
2416 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2417 }
Chris Lattner24943d22010-06-08 16:52:24 +00002418 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002419 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002420
2421 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2422 return NULL;
2423 }
2424
2425 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002426 DataExtractor data (memory_buffer,
2427 sizeof(memory_buffer),
2428 m_target.GetArchitecture().GetByteOrder(),
2429 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002430
2431 // Excerpt from src/queue_private.h
2432 struct dispatch_queue_offsets_s
2433 {
2434 uint16_t dqo_version;
2435 uint16_t dqo_label;
2436 uint16_t dqo_label_size;
2437 } dispatch_queue_offsets;
2438
2439
2440 Error error;
2441 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2442 {
2443 uint32_t data_offset = 0;
2444 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2445 {
2446 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2447 {
2448 data_offset = 0;
2449 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2450 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2451 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2452 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2453 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2454 dispatch_queue_name.erase (bytes_read);
2455 }
2456 }
2457 }
2458 }
2459 if (dispatch_queue_name.empty())
2460 return NULL;
2461 return dispatch_queue_name.c_str();
2462}
2463
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002464//uint32_t
2465//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2466//{
2467// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2468// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2469// if (m_local_debugserver)
2470// {
2471// return Host::ListProcessesMatchingName (name, matches, pids);
2472// }
2473// else
2474// {
2475// // FIXME: Implement talking to the remote debugserver.
2476// return 0;
2477// }
2478//
2479//}
2480//
Jim Ingham55e01d82011-01-22 01:33:44 +00002481bool
2482ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2483 lldb_private::StoppointCallbackContext *context,
2484 lldb::user_id_t break_id,
2485 lldb::user_id_t break_loc_id)
2486{
2487 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2488 // run so I can stop it if that's what I want to do.
2489 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2490 if (log)
2491 log->Printf("Hit New Thread Notification breakpoint.");
2492 return false;
2493}
2494
2495
2496bool
2497ProcessGDBRemote::StartNoticingNewThreads()
2498{
2499 static const char *bp_names[] =
2500 {
2501 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002502 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002503 "_pthread_start",
2504 NULL
2505 };
2506
2507 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2508 size_t num_bps = m_thread_observation_bps.size();
2509 if (num_bps != 0)
2510 {
2511 for (int i = 0; i < num_bps; i++)
2512 {
2513 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2514 if (break_sp)
2515 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002516 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002517 log->Printf("Enabled noticing new thread breakpoint.");
2518 break_sp->SetEnabled(true);
2519 }
2520 }
2521 }
2522 else
2523 {
2524 for (int i = 0; bp_names[i] != NULL; i++)
2525 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002526 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002527 if (breakpoint)
2528 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002529 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002530 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2531 m_thread_observation_bps.push_back(breakpoint->GetID());
2532 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2533 }
2534 else
2535 {
2536 if (log)
2537 log->Printf("Failed to create new thread notification breakpoint.");
2538 return false;
2539 }
2540 }
2541 }
2542
2543 return true;
2544}
2545
2546bool
2547ProcessGDBRemote::StopNoticingNewThreads()
2548{
Jim Inghamff276fe2011-02-08 05:19:01 +00002549 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002550 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002551 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002552 size_t num_bps = m_thread_observation_bps.size();
2553 if (num_bps != 0)
2554 {
2555 for (int i = 0; i < num_bps; i++)
2556 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002557
2558 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2559 if (break_sp)
2560 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002561 break_sp->SetEnabled(false);
2562 }
2563 }
2564 }
2565 return true;
2566}
2567
2568