blob: 8f09fcf9d8c55f12c7cfab3e6f4abbaf608cd461 [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
25#include "lldb/Breakpoint/WatchpointLocation.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{
106 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000107 Module *exe_module = target.GetExecutableModulePointer();
108 if (exe_module)
109 return exe_module->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000110 // However, if there is no executable module, we return true since we might be preparing to attach.
111 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000112}
113
114//----------------------------------------------------------------------
115// ProcessGDBRemote constructor
116//----------------------------------------------------------------------
117ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
118 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000119 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000120 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000121 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000123 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000124 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000125 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000126 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
127 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000128 m_continue_c_tids (),
129 m_continue_C_tids (),
130 m_continue_s_tids (),
131 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000132 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000133 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000134 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000135 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000136{
Greg Claytonff39f742011-04-01 00:29:43 +0000137 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
138 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000139}
140
141//----------------------------------------------------------------------
142// Destructor
143//----------------------------------------------------------------------
144ProcessGDBRemote::~ProcessGDBRemote()
145{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000146 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000147 {
148 Host::ThreadCancel (m_debugserver_thread, NULL);
149 thread_result_t thread_result;
150 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
151 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
152 }
Chris Lattner24943d22010-06-08 16:52:24 +0000153 // m_mach_process.UnregisterNotificationCallbacks (this);
154 Clear();
155}
156
157//----------------------------------------------------------------------
158// PluginInterface
159//----------------------------------------------------------------------
160const char *
161ProcessGDBRemote::GetPluginName()
162{
163 return "Process debugging plug-in that uses the GDB remote protocol";
164}
165
166const char *
167ProcessGDBRemote::GetShortPluginName()
168{
169 return GetPluginNameStatic();
170}
171
172uint32_t
173ProcessGDBRemote::GetPluginVersion()
174{
175 return 1;
176}
177
178void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000179ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000180{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000181 if (!force && m_register_info.GetNumRegisters() > 0)
182 return;
183
184 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000185 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000186 uint32_t reg_offset = 0;
187 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000188 StringExtractorGDBRemote::ResponseType response_type;
189 for (response_type = StringExtractorGDBRemote::eResponse;
190 response_type == StringExtractorGDBRemote::eResponse;
191 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000192 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000193 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
194 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000195 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000196 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000197 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000198 response_type = response.GetResponseType();
199 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000200 {
201 std::string name;
202 std::string value;
203 ConstString reg_name;
204 ConstString alt_name;
205 ConstString set_name;
206 RegisterInfo reg_info = { NULL, // Name
207 NULL, // Alt name
208 0, // byte size
209 reg_offset, // offset
210 eEncodingUint, // encoding
211 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000212 {
213 LLDB_INVALID_REGNUM, // GCC reg num
214 LLDB_INVALID_REGNUM, // DWARF reg num
215 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000216 reg_num, // GDB reg num
217 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000218 }
219 };
220
221 while (response.GetNameColonValue(name, value))
222 {
223 if (name.compare("name") == 0)
224 {
225 reg_name.SetCString(value.c_str());
226 }
227 else if (name.compare("alt-name") == 0)
228 {
229 alt_name.SetCString(value.c_str());
230 }
231 else if (name.compare("bitsize") == 0)
232 {
233 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
234 }
235 else if (name.compare("offset") == 0)
236 {
237 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000238 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000239 {
240 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000241 }
242 }
243 else if (name.compare("encoding") == 0)
244 {
245 if (value.compare("uint") == 0)
246 reg_info.encoding = eEncodingUint;
247 else if (value.compare("sint") == 0)
248 reg_info.encoding = eEncodingSint;
249 else if (value.compare("ieee754") == 0)
250 reg_info.encoding = eEncodingIEEE754;
251 else if (value.compare("vector") == 0)
252 reg_info.encoding = eEncodingVector;
253 }
254 else if (name.compare("format") == 0)
255 {
256 if (value.compare("binary") == 0)
257 reg_info.format = eFormatBinary;
258 else if (value.compare("decimal") == 0)
259 reg_info.format = eFormatDecimal;
260 else if (value.compare("hex") == 0)
261 reg_info.format = eFormatHex;
262 else if (value.compare("float") == 0)
263 reg_info.format = eFormatFloat;
264 else if (value.compare("vector-sint8") == 0)
265 reg_info.format = eFormatVectorOfSInt8;
266 else if (value.compare("vector-uint8") == 0)
267 reg_info.format = eFormatVectorOfUInt8;
268 else if (value.compare("vector-sint16") == 0)
269 reg_info.format = eFormatVectorOfSInt16;
270 else if (value.compare("vector-uint16") == 0)
271 reg_info.format = eFormatVectorOfUInt16;
272 else if (value.compare("vector-sint32") == 0)
273 reg_info.format = eFormatVectorOfSInt32;
274 else if (value.compare("vector-uint32") == 0)
275 reg_info.format = eFormatVectorOfUInt32;
276 else if (value.compare("vector-float32") == 0)
277 reg_info.format = eFormatVectorOfFloat32;
278 else if (value.compare("vector-uint128") == 0)
279 reg_info.format = eFormatVectorOfUInt128;
280 }
281 else if (name.compare("set") == 0)
282 {
283 set_name.SetCString(value.c_str());
284 }
285 else if (name.compare("gcc") == 0)
286 {
287 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
288 }
289 else if (name.compare("dwarf") == 0)
290 {
291 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
292 }
293 else if (name.compare("generic") == 0)
294 {
295 if (value.compare("pc") == 0)
296 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
297 else if (value.compare("sp") == 0)
298 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
299 else if (value.compare("fp") == 0)
300 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
301 else if (value.compare("ra") == 0)
302 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
303 else if (value.compare("flags") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000305 else if (value.find("arg") == 0)
306 {
307 if (value.size() == 4)
308 {
309 switch (value[3])
310 {
311 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
312 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
313 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
314 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
315 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
316 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
317 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
318 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
319 }
320 }
321 }
Chris Lattner24943d22010-06-08 16:52:24 +0000322 }
323 }
324
Jason Molenda53d96862010-06-11 23:44:18 +0000325 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000326 assert (reg_info.byte_size != 0);
327 reg_offset += reg_info.byte_size;
328 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
329 }
330 }
331 else
332 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000333 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000334 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000335 }
336 }
337
338 if (reg_num == 0)
339 {
340 // We didn't get anything. See if we are debugging ARM and fill with
341 // a hard coded register set until we can get an updated debugserver
342 // down on the devices.
Greg Clayton940b1032011-02-23 00:35:02 +0000343 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
Chris Lattner24943d22010-06-08 16:52:24 +0000344 m_register_info.HardcodeARMRegisters();
345 }
346 m_register_info.Finalize ();
347}
348
349Error
350ProcessGDBRemote::WillLaunch (Module* module)
351{
352 return WillLaunchOrAttach ();
353}
354
355Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000356ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000357{
358 return WillLaunchOrAttach ();
359}
360
361Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000362ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000363{
364 return WillLaunchOrAttach ();
365}
366
367Error
Greg Claytone71e2582011-02-04 01:58:07 +0000368ProcessGDBRemote::DoConnectRemote (const char *remote_url)
369{
370 Error error (WillLaunchOrAttach ());
371
372 if (error.Fail())
373 return error;
374
Greg Clayton180546b2011-04-30 01:09:13 +0000375 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000376
377 if (error.Fail())
378 return error;
379 StartAsyncThread ();
380
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000381 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000382 if (pid == LLDB_INVALID_PROCESS_ID)
383 {
384 // We don't have a valid process ID, so note that we are connected
385 // and could now request to launch or attach, or get remote process
386 // listings...
387 SetPrivateState (eStateConnected);
388 }
389 else
390 {
391 // We have a valid process
392 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000393 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000394 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000395 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000396 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000397 if (state == eStateStopped)
398 {
399 SetPrivateState (state);
400 }
401 else
402 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
403 }
404 else
405 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
406 }
407 return error;
408}
409
410Error
Chris Lattner24943d22010-06-08 16:52:24 +0000411ProcessGDBRemote::WillLaunchOrAttach ()
412{
413 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000414 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000415 return error;
416}
417
418//----------------------------------------------------------------------
419// Process Control
420//----------------------------------------------------------------------
421Error
422ProcessGDBRemote::DoLaunch
423(
424 Module* module,
425 char const *argv[],
426 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000427 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000428 const char *stdin_path,
429 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000430 const char *stderr_path,
431 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000432)
433{
Greg Clayton4b407112010-09-30 21:49:03 +0000434 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000435 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
436 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
437 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000438 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000439
440 ObjectFile * object_file = module->GetObjectFile();
441 if (object_file)
442 {
Chris Lattner24943d22010-06-08 16:52:24 +0000443 char host_port[128];
444 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000445 char connect_url[128];
446 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000447
Greg Claytona2f74232011-02-24 22:24:29 +0000448 // Make sure we aren't already connected?
449 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000450 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000451 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000452 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000453 {
Johnny Chenc143d622011-08-09 18:56:45 +0000454 if (log)
455 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000456 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000457 }
Chris Lattner24943d22010-06-08 16:52:24 +0000458
Greg Claytone71e2582011-02-04 01:58:07 +0000459 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000460 }
461
462 if (error.Success())
463 {
464 lldb_utility::PseudoTerminal pty;
465 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000466
467 // If the debugserver is local and we aren't disabling STDIO, lets use
468 // a pseudo terminal to instead of relying on the 'O' packets for stdio
469 // since 'O' packets can really slow down debugging if the inferior
470 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000471 PlatformSP platform_sp (m_target.GetPlatform());
472 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000473 {
474 const char *slave_name = NULL;
475 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000476 {
Greg Claytona2f74232011-02-24 22:24:29 +0000477 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
478 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000479 }
Greg Claytona2f74232011-02-24 22:24:29 +0000480 if (stdin_path == NULL)
481 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000482
Greg Claytona2f74232011-02-24 22:24:29 +0000483 if (stdout_path == NULL)
484 stdout_path = slave_name;
485
486 if (stderr_path == NULL)
487 stderr_path = slave_name;
488 }
489
Greg Claytonafb81862011-03-02 21:34:46 +0000490 // Set STDIN to /dev/null if we want STDIO disabled or if either
491 // STDOUT or STDERR have been set to something and STDIN hasn't
492 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000493 stdin_path = "/dev/null";
494
Greg Claytonafb81862011-03-02 21:34:46 +0000495 // Set STDOUT to /dev/null if we want STDIO disabled or if either
496 // STDIN or STDERR have been set to something and STDOUT hasn't
497 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000498 stdout_path = "/dev/null";
499
Greg Claytonafb81862011-03-02 21:34:46 +0000500 // Set STDERR to /dev/null if we want STDIO disabled or if either
501 // STDIN or STDOUT have been set to something and STDERR hasn't
502 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000503 stderr_path = "/dev/null";
504
505 if (stdin_path)
506 m_gdb_comm.SetSTDIN (stdin_path);
507 if (stdout_path)
508 m_gdb_comm.SetSTDOUT (stdout_path);
509 if (stderr_path)
510 m_gdb_comm.SetSTDERR (stderr_path);
511
512 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
513
Greg Claytona4582402011-05-08 04:53:50 +0000514 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000515
516 if (working_dir && working_dir[0])
517 {
518 m_gdb_comm.SetWorkingDir (working_dir);
519 }
520
521 // Send the environment and the program + arguments after we connect
522 if (envp)
523 {
524 const char *env_entry;
525 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000526 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000527 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000528 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000529 }
Greg Claytona2f74232011-02-24 22:24:29 +0000530 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000531
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000532 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
533 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
Greg Claytona2f74232011-02-24 22:24:29 +0000534 if (arg_packet_err == 0)
535 {
536 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000537 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000538 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000539 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000540 }
541 else
542 {
Greg Claytona2f74232011-02-24 22:24:29 +0000543 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000544 }
Greg Claytona2f74232011-02-24 22:24:29 +0000545 }
546 else
547 {
548 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err);
549 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000550
551 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000552
Greg Claytona2f74232011-02-24 22:24:29 +0000553 if (GetID() == LLDB_INVALID_PROCESS_ID)
554 {
Johnny Chenc143d622011-08-09 18:56:45 +0000555 if (log)
556 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000557 KillDebugserverProcess ();
558 return error;
559 }
560
Greg Clayton261a18b2011-06-02 22:22:38 +0000561 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000562 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000563 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000564
565 if (!disable_stdio)
566 {
567 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
568 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
569 }
Chris Lattner24943d22010-06-08 16:52:24 +0000570 }
571 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000572 else
573 {
Johnny Chenc143d622011-08-09 18:56:45 +0000574 if (log)
575 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000576 }
Chris Lattner24943d22010-06-08 16:52:24 +0000577 }
578 else
579 {
580 // Set our user ID to an invalid process ID.
581 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton940b1032011-02-23 00:35:02 +0000582 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n",
583 module->GetFileSpec().GetFilename().AsCString(),
584 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000585 }
Chris Lattner24943d22010-06-08 16:52:24 +0000586 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000587
Chris Lattner24943d22010-06-08 16:52:24 +0000588}
589
590
591Error
Greg Claytone71e2582011-02-04 01:58:07 +0000592ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000593{
594 Error error;
595 // Sleep and wait a bit for debugserver to start to listen...
596 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
597 if (conn_ap.get())
598 {
Chris Lattner24943d22010-06-08 16:52:24 +0000599 const uint32_t max_retry_count = 50;
600 uint32_t retry_count = 0;
601 while (!m_gdb_comm.IsConnected())
602 {
Greg Claytone71e2582011-02-04 01:58:07 +0000603 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000604 {
605 m_gdb_comm.SetConnection (conn_ap.release());
606 break;
607 }
608 retry_count++;
609
610 if (retry_count >= max_retry_count)
611 break;
612
613 usleep (100000);
614 }
615 }
616
617 if (!m_gdb_comm.IsConnected())
618 {
619 if (error.Success())
620 error.SetErrorString("not connected to remote gdb server");
621 return error;
622 }
623
Greg Clayton24bc5d92011-03-30 18:16:51 +0000624 // We always seem to be able to open a connection to a local port
625 // so we need to make sure we can then send data to it. If we can't
626 // then we aren't actually connected to anything, so try and do the
627 // handshake with the remote GDB server and make sure that goes
628 // alright.
629 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000630 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000631 m_gdb_comm.Disconnect();
632 if (error.Success())
633 error.SetErrorString("not connected to remote gdb server");
634 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000635 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000636 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
637 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
638 this,
639 m_debugserver_pid,
640 false);
641 m_gdb_comm.ResetDiscoverableSettings();
642 m_gdb_comm.QueryNoAckModeSupported ();
643 m_gdb_comm.GetThreadSuffixSupported ();
644 m_gdb_comm.GetHostInfo ();
645 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000646 return error;
647}
648
649void
650ProcessGDBRemote::DidLaunchOrAttach ()
651{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000652 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
653 if (log)
654 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000655 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000656 {
657 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
658
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000659 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000660
Chris Lattner24943d22010-06-08 16:52:24 +0000661 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000662
Greg Claytoncb8977d2011-03-23 00:09:55 +0000663 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
664 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000665 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000666 ArchSpec &target_arch = GetTarget().GetArchitecture();
667
668 if (target_arch.IsValid())
669 {
670 // If the remote host is ARM and we have apple as the vendor, then
671 // ARM executables and shared libraries can have mixed ARM architectures.
672 // You can have an armv6 executable, and if the host is armv7, then the
673 // system will load the best possible architecture for all shared libraries
674 // it has, so we really need to take the remote host architecture as our
675 // defacto architecture in this case.
676
677 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
678 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
679 {
680 target_arch = gdb_remote_arch;
681 }
682 else
683 {
684 // Fill in what is missing in the triple
685 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
686 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000687 if (target_triple.getVendorName().size() == 0)
688 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000689 target_triple.setVendor (remote_triple.getVendor());
690
Greg Clayton2f085c62011-05-15 01:25:55 +0000691 if (target_triple.getOSName().size() == 0)
692 {
693 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000694
Greg Clayton2f085c62011-05-15 01:25:55 +0000695 if (target_triple.getEnvironmentName().size() == 0)
696 target_triple.setEnvironment (remote_triple.getEnvironment());
697 }
698 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000699 }
700 }
701 else
702 {
703 // The target doesn't have a valid architecture yet, set it from
704 // the architecture we got from the remote GDB server
705 target_arch = gdb_remote_arch;
706 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000707 }
Chris Lattner24943d22010-06-08 16:52:24 +0000708 }
709}
710
711void
712ProcessGDBRemote::DidLaunch ()
713{
714 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000715}
716
717Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000718ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000719{
720 Error error;
721 // Clear out and clean up from any current state
722 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000723 if (attach_pid != LLDB_INVALID_PROCESS_ID)
724 {
Greg Claytona2f74232011-02-24 22:24:29 +0000725 // Make sure we aren't already connected?
726 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000727 {
Greg Claytona2f74232011-02-24 22:24:29 +0000728 char host_port[128];
729 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
730 char connect_url[128];
731 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000732
Greg Claytonb72d0f02011-04-12 05:54:46 +0000733 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000734
735 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000736 {
Greg Claytona2f74232011-02-24 22:24:29 +0000737 const char *error_string = error.AsCString();
738 if (error_string == NULL)
739 error_string = "unable to launch " DEBUGSERVER_BASENAME;
740
741 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000742 }
Greg Claytona2f74232011-02-24 22:24:29 +0000743 else
744 {
745 error = ConnectToDebugserver (connect_url);
746 }
747 }
748
749 if (error.Success())
750 {
751 char packet[64];
752 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
753
754 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000755 }
756 }
Chris Lattner24943d22010-06-08 16:52:24 +0000757 return error;
758}
759
760size_t
761ProcessGDBRemote::AttachInputReaderCallback
762(
763 void *baton,
764 InputReader *reader,
765 lldb::InputReaderAction notification,
766 const char *bytes,
767 size_t bytes_len
768)
769{
770 if (notification == eInputReaderGotToken)
771 {
772 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
773 if (gdb_process->m_waiting_for_attach)
774 gdb_process->m_waiting_for_attach = false;
775 reader->SetIsDone(true);
776 return 1;
777 }
778 return 0;
779}
780
781Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000782ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000783{
784 Error error;
785 // Clear out and clean up from any current state
786 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000787
Chris Lattner24943d22010-06-08 16:52:24 +0000788 if (process_name && process_name[0])
789 {
Greg Claytona2f74232011-02-24 22:24:29 +0000790 // Make sure we aren't already connected?
791 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000792 {
Greg Claytona2f74232011-02-24 22:24:29 +0000793 char host_port[128];
794 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
795 char connect_url[128];
796 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
797
Greg Claytonb72d0f02011-04-12 05:54:46 +0000798 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000799 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000800 {
Greg Claytona2f74232011-02-24 22:24:29 +0000801 const char *error_string = error.AsCString();
802 if (error_string == NULL)
803 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000804
Greg Claytona2f74232011-02-24 22:24:29 +0000805 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000806 }
Greg Claytona2f74232011-02-24 22:24:29 +0000807 else
808 {
809 error = ConnectToDebugserver (connect_url);
810 }
811 }
812
813 if (error.Success())
814 {
815 StreamString packet;
816
817 if (wait_for_launch)
818 packet.PutCString("vAttachWait");
819 else
820 packet.PutCString("vAttachName");
821 packet.PutChar(';');
822 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
823
824 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
825
Chris Lattner24943d22010-06-08 16:52:24 +0000826 }
827 }
Chris Lattner24943d22010-06-08 16:52:24 +0000828 return error;
829}
830
Chris Lattner24943d22010-06-08 16:52:24 +0000831
832void
833ProcessGDBRemote::DidAttach ()
834{
Greg Claytone71e2582011-02-04 01:58:07 +0000835 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000836}
837
838Error
839ProcessGDBRemote::WillResume ()
840{
Greg Claytonc1f45872011-02-12 06:28:37 +0000841 m_continue_c_tids.clear();
842 m_continue_C_tids.clear();
843 m_continue_s_tids.clear();
844 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000845 return Error();
846}
847
848Error
849ProcessGDBRemote::DoResume ()
850{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000851 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000852 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
853 if (log)
854 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000855
856 Listener listener ("gdb-remote.resume-packet-sent");
857 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
858 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000859 StreamString continue_packet;
860 bool continue_packet_error = false;
861 if (m_gdb_comm.HasAnyVContSupport ())
862 {
863 continue_packet.PutCString ("vCont");
864
865 if (!m_continue_c_tids.empty())
866 {
867 if (m_gdb_comm.GetVContSupported ('c'))
868 {
869 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)
870 continue_packet.Printf(";c:%4.4x", *t_pos);
871 }
872 else
873 continue_packet_error = true;
874 }
875
876 if (!continue_packet_error && !m_continue_C_tids.empty())
877 {
878 if (m_gdb_comm.GetVContSupported ('C'))
879 {
880 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)
881 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
882 }
883 else
884 continue_packet_error = true;
885 }
Greg Claytonb749a262010-12-03 06:02:24 +0000886
Greg Claytonc1f45872011-02-12 06:28:37 +0000887 if (!continue_packet_error && !m_continue_s_tids.empty())
888 {
889 if (m_gdb_comm.GetVContSupported ('s'))
890 {
891 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)
892 continue_packet.Printf(";s:%4.4x", *t_pos);
893 }
894 else
895 continue_packet_error = true;
896 }
897
898 if (!continue_packet_error && !m_continue_S_tids.empty())
899 {
900 if (m_gdb_comm.GetVContSupported ('S'))
901 {
902 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)
903 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
904 }
905 else
906 continue_packet_error = true;
907 }
908
909 if (continue_packet_error)
910 continue_packet.GetString().clear();
911 }
912 else
913 continue_packet_error = true;
914
915 if (continue_packet_error)
916 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000917 // Either no vCont support, or we tried to use part of the vCont
918 // packet that wasn't supported by the remote GDB server.
919 // We need to try and make a simple packet that can do our continue
920 const size_t num_threads = GetThreadList().GetSize();
921 const size_t num_continue_c_tids = m_continue_c_tids.size();
922 const size_t num_continue_C_tids = m_continue_C_tids.size();
923 const size_t num_continue_s_tids = m_continue_s_tids.size();
924 const size_t num_continue_S_tids = m_continue_S_tids.size();
925 if (num_continue_c_tids > 0)
926 {
927 if (num_continue_c_tids == num_threads)
928 {
929 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000930 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000931 continue_packet.PutChar ('c');
932 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000933 }
934 else if (num_continue_c_tids == 1 &&
935 num_continue_C_tids == 0 &&
936 num_continue_s_tids == 0 &&
937 num_continue_S_tids == 0 )
938 {
939 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000940 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000941 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000942 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000943 }
944 }
945
Greg Claytonde1dd812011-06-24 03:21:43 +0000946 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000947 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000948 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
949 num_continue_C_tids > 0 &&
950 num_continue_s_tids == 0 &&
951 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000952 {
953 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000954 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +0000955 if (num_continue_C_tids > 1)
956 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000957 // More that one thread with a signal, yet we don't have
958 // vCont support and we are being asked to resume each
959 // thread with a signal, we need to make sure they are
960 // all the same signal, or we can't issue the continue
961 // accurately with the current support...
962 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +0000963 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000964 continue_packet_error = false;
965 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
966 {
967 if (m_continue_C_tids[i].second != continue_signo)
968 continue_packet_error = true;
969 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000970 }
Greg Claytonde1dd812011-06-24 03:21:43 +0000971 if (!continue_packet_error)
972 m_gdb_comm.SetCurrentThreadForRun (-1);
973 }
974 else
975 {
976 // Set the continue thread ID
977 continue_packet_error = false;
978 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000979 }
980 if (!continue_packet_error)
981 {
982 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +0000983 continue_packet.Printf("C%2.2x", continue_signo);
984 }
985 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000986 }
987
Greg Claytonde1dd812011-06-24 03:21:43 +0000988 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000989 {
990 if (num_continue_s_tids == num_threads)
991 {
992 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000993 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000994 continue_packet.PutChar ('s');
995 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000996 }
997 else if (num_continue_c_tids == 0 &&
998 num_continue_C_tids == 0 &&
999 num_continue_s_tids == 1 &&
1000 num_continue_S_tids == 0 )
1001 {
1002 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001003 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001004 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001005 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001006 }
1007 }
1008
1009 if (!continue_packet_error && num_continue_S_tids > 0)
1010 {
1011 if (num_continue_S_tids == num_threads)
1012 {
1013 const int step_signo = m_continue_S_tids.front().second;
1014 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001015 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001016 if (num_continue_S_tids > 1)
1017 {
1018 for (size_t i=1; i<num_threads; ++i)
1019 {
1020 if (m_continue_S_tids[i].second != step_signo)
1021 continue_packet_error = true;
1022 }
1023 }
1024 if (!continue_packet_error)
1025 {
1026 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001027 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001028 continue_packet.Printf("S%2.2x", step_signo);
1029 }
1030 }
1031 else if (num_continue_c_tids == 0 &&
1032 num_continue_C_tids == 0 &&
1033 num_continue_s_tids == 0 &&
1034 num_continue_S_tids == 1 )
1035 {
1036 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001037 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001038 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001039 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001040 }
1041 }
1042 }
1043
1044 if (continue_packet_error)
1045 {
1046 error.SetErrorString ("can't make continue packet for this resume");
1047 }
1048 else
1049 {
1050 EventSP event_sp;
1051 TimeValue timeout;
1052 timeout = TimeValue::Now();
1053 timeout.OffsetWithSeconds (5);
1054 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1055
1056 if (listener.WaitForEvent (&timeout, event_sp) == false)
1057 error.SetErrorString("Resume timed out.");
1058 }
Greg Claytonb749a262010-12-03 06:02:24 +00001059 }
1060
Jim Ingham3ae449a2010-11-17 02:32:00 +00001061 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001062}
1063
Chris Lattner24943d22010-06-08 16:52:24 +00001064uint32_t
Greg Clayton37f962e2011-08-22 02:49:39 +00001065ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001066{
1067 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001068 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001069 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Chris Lattner24943d22010-06-08 16:52:24 +00001070 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001071 // Update the thread list's stop id immediately so we don't recurse into this function.
Chris Lattner24943d22010-06-08 16:52:24 +00001072
Greg Clayton37f962e2011-08-22 02:49:39 +00001073 std::vector<lldb::tid_t> thread_ids;
1074 bool sequence_mutex_unavailable = false;
1075 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1076 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001077 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001078 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001079 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001080 tid_t tid = thread_ids[i];
1081 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1082 if (!thread_sp)
1083 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1084 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001085 }
Chris Lattner24943d22010-06-08 16:52:24 +00001086 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001087
1088 if (sequence_mutex_unavailable == false)
1089 SetThreadStopInfo (m_last_stop_packet);
1090 return new_thread_list.GetSize(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001091}
1092
1093
1094StateType
1095ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1096{
Greg Clayton261a18b2011-06-02 22:22:38 +00001097 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001098 const char stop_type = stop_packet.GetChar();
1099 switch (stop_type)
1100 {
1101 case 'T':
1102 case 'S':
1103 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001104 if (GetStopID() == 0)
1105 {
1106 // Our first stop, make sure we have a process ID, and also make
1107 // sure we know about our registers
1108 if (GetID() == LLDB_INVALID_PROCESS_ID)
1109 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001110 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001111 if (pid != LLDB_INVALID_PROCESS_ID)
1112 SetID (pid);
1113 }
1114 BuildDynamicRegisterInfo (true);
1115 }
Chris Lattner24943d22010-06-08 16:52:24 +00001116 // Stop with signal and thread info
1117 const uint8_t signo = stop_packet.GetHexU8();
1118 std::string name;
1119 std::string value;
1120 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001121 std::string reason;
1122 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001123 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001124 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001125 uint32_t tid = LLDB_INVALID_THREAD_ID;
1126 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1127 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001128 ThreadSP thread_sp;
1129
Chris Lattner24943d22010-06-08 16:52:24 +00001130 while (stop_packet.GetNameColonValue(name, value))
1131 {
1132 if (name.compare("metype") == 0)
1133 {
1134 // exception type in big endian hex
1135 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1136 }
1137 else if (name.compare("mecount") == 0)
1138 {
1139 // exception count in big endian hex
1140 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1141 }
1142 else if (name.compare("medata") == 0)
1143 {
1144 // exception data in big endian hex
1145 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1146 }
1147 else if (name.compare("thread") == 0)
1148 {
1149 // thread in big endian hex
1150 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001151 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001152 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001153 if (!thread_sp)
1154 {
1155 // Create the thread if we need to
1156 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1157 m_thread_list.AddThread(thread_sp);
1158 }
Chris Lattner24943d22010-06-08 16:52:24 +00001159 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001160 else if (name.compare("hexname") == 0)
1161 {
1162 StringExtractor name_extractor;
1163 // Swap "value" over into "name_extractor"
1164 name_extractor.GetStringRef().swap(value);
1165 // Now convert the HEX bytes into a string value
1166 name_extractor.GetHexByteString (value);
1167 thread_name.swap (value);
1168 }
Chris Lattner24943d22010-06-08 16:52:24 +00001169 else if (name.compare("name") == 0)
1170 {
1171 thread_name.swap (value);
1172 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001173 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001174 {
1175 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1176 }
Greg Clayton65611552011-06-04 01:26:29 +00001177 else if (name.compare("reason") == 0)
1178 {
1179 reason.swap(value);
1180 }
1181 else if (name.compare("description") == 0)
1182 {
1183 StringExtractor desc_extractor;
1184 // Swap "value" over into "name_extractor"
1185 desc_extractor.GetStringRef().swap(value);
1186 // Now convert the HEX bytes into a string value
1187 desc_extractor.GetHexByteString (thread_name);
1188 }
Greg Claytona875b642011-01-09 21:07:35 +00001189 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1190 {
1191 // We have a register number that contains an expedited
1192 // register value. Lets supply this register to our thread
1193 // so it won't have to go and read it.
1194 if (thread_sp)
1195 {
1196 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1197
1198 if (reg != UINT32_MAX)
1199 {
1200 StringExtractor reg_value_extractor;
1201 // Swap "value" over into "reg_value_extractor"
1202 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001203 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1204 {
1205 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1206 name.c_str(),
1207 reg,
1208 reg,
1209 reg_value_extractor.GetStringRef().c_str(),
1210 stop_packet.GetStringRef().c_str());
1211 }
Greg Claytona875b642011-01-09 21:07:35 +00001212 }
1213 }
1214 }
Chris Lattner24943d22010-06-08 16:52:24 +00001215 }
Chris Lattner24943d22010-06-08 16:52:24 +00001216
1217 if (thread_sp)
1218 {
1219 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1220
1221 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001222 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001223 if (exc_type != 0)
1224 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001225 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001226
1227 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1228 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001229 exc_data_size,
1230 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001231 exc_data_size >= 2 ? exc_data[1] : 0,
1232 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001233 }
Greg Clayton65611552011-06-04 01:26:29 +00001234 else
Chris Lattner24943d22010-06-08 16:52:24 +00001235 {
Greg Clayton65611552011-06-04 01:26:29 +00001236 bool handled = false;
1237 if (!reason.empty())
1238 {
1239 if (reason.compare("trace") == 0)
1240 {
1241 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1242 handled = true;
1243 }
1244 else if (reason.compare("breakpoint") == 0)
1245 {
1246 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1247 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1248 if (bp_site_sp)
1249 {
1250 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1251 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1252 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1253 if (bp_site_sp->ValidForThisThread (gdb_thread))
1254 {
1255 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1256 handled = true;
1257 }
1258 }
1259
1260 if (!handled)
1261 {
1262 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1263 }
1264 }
1265 else if (reason.compare("trap") == 0)
1266 {
1267 // Let the trap just use the standard signal stop reason below...
1268 }
1269 else if (reason.compare("watchpoint") == 0)
1270 {
1271 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1272 // TODO: locate the watchpoint somehow...
1273 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1274 handled = true;
1275 }
1276 else if (reason.compare("exception") == 0)
1277 {
1278 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1279 handled = true;
1280 }
1281 }
1282
1283 if (signo)
1284 {
1285 if (signo == SIGTRAP)
1286 {
1287 // Currently we are going to assume SIGTRAP means we are either
1288 // hitting a breakpoint or hardware single stepping.
1289 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1290 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1291 if (bp_site_sp)
1292 {
1293 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1294 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1295 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1296 if (bp_site_sp->ValidForThisThread (gdb_thread))
1297 {
1298 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1299 handled = true;
1300 }
1301 }
1302 if (!handled)
1303 {
1304 // TODO: check for breakpoint or trap opcode in case there is a hard
1305 // coded software trap
1306 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1307 handled = true;
1308 }
1309 }
1310 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001311 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001312 }
1313 else
1314 {
Greg Clayton643ee732010-08-04 01:40:35 +00001315 StopInfoSP invalid_stop_info_sp;
1316 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001317 }
Greg Clayton65611552011-06-04 01:26:29 +00001318
1319 if (!description.empty())
1320 {
1321 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1322 if (stop_info_sp)
1323 {
1324 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001325 }
Greg Clayton65611552011-06-04 01:26:29 +00001326 else
1327 {
1328 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1329 }
1330 }
1331 }
Chris Lattner24943d22010-06-08 16:52:24 +00001332 }
1333 return eStateStopped;
1334 }
1335 break;
1336
1337 case 'W':
1338 // process exited
1339 return eStateExited;
1340
1341 default:
1342 break;
1343 }
1344 return eStateInvalid;
1345}
1346
1347void
1348ProcessGDBRemote::RefreshStateAfterStop ()
1349{
Chris Lattner24943d22010-06-08 16:52:24 +00001350 // Let all threads recover from stopping and do any clean up based
1351 // on the previous thread state (if any).
1352 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001353 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001354}
1355
1356Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001357ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001358{
1359 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001360
Greg Claytona4881d02011-01-22 07:12:45 +00001361 bool timed_out = false;
1362 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001363
1364 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001365 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001366 // We are being asked to halt during an attach. We need to just close
1367 // our file handle and debugserver will go away, and we can be done...
1368 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001369 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001370 else
1371 {
1372 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1373 {
1374 if (timed_out)
1375 error.SetErrorString("timed out sending interrupt packet");
1376 else
1377 error.SetErrorString("unknown error sending interrupt packet");
1378 }
1379 }
Chris Lattner24943d22010-06-08 16:52:24 +00001380 return error;
1381}
1382
1383Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001384ProcessGDBRemote::InterruptIfRunning
1385(
1386 bool discard_thread_plans,
1387 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001388 EventSP &stop_event_sp
1389)
Chris Lattner24943d22010-06-08 16:52:24 +00001390{
1391 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001392
Greg Clayton2860ba92011-01-23 19:58:49 +00001393 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1394
Greg Clayton68ca8232011-01-25 02:58:48 +00001395 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001396 const bool is_running = m_gdb_comm.IsRunning();
1397 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001398 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001399 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001400 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001401 is_running);
1402
Greg Clayton2860ba92011-01-23 19:58:49 +00001403 if (discard_thread_plans)
1404 {
1405 if (log)
1406 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1407 m_thread_list.DiscardThreadPlans();
1408 }
1409 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001410 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001411 if (catch_stop_event)
1412 {
1413 if (log)
1414 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1415 PausePrivateStateThread();
1416 paused_private_state_thread = true;
1417 }
1418
Greg Clayton4fb400f2010-09-27 21:07:38 +00001419 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001420 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001421 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001422
Greg Clayton72e1c782011-01-22 23:43:18 +00001423 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001424 {
1425 if (timed_out)
1426 error.SetErrorString("timed out sending interrupt packet");
1427 else
1428 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001429 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001430 ResumePrivateStateThread();
1431 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001432 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001433
Greg Clayton72e1c782011-01-22 23:43:18 +00001434 if (catch_stop_event)
1435 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001436 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001437 TimeValue timeout_time;
1438 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001439 timeout_time.OffsetWithSeconds(5);
1440 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001441
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001442 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001443 if (log)
1444 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001445
Greg Clayton2860ba92011-01-23 19:58:49 +00001446 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001447 error.SetErrorString("unable to verify target stopped");
1448 }
1449
Greg Clayton68ca8232011-01-25 02:58:48 +00001450 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001451 {
1452 if (log)
1453 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001454 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001455 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001456 }
Chris Lattner24943d22010-06-08 16:52:24 +00001457 return error;
1458}
1459
Greg Clayton4fb400f2010-09-27 21:07:38 +00001460Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001461ProcessGDBRemote::WillDetach ()
1462{
Greg Clayton2860ba92011-01-23 19:58:49 +00001463 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1464 if (log)
1465 log->Printf ("ProcessGDBRemote::WillDetach()");
1466
Greg Clayton72e1c782011-01-22 23:43:18 +00001467 bool discard_thread_plans = true;
1468 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001469 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001470 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001471}
1472
1473Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001474ProcessGDBRemote::DoDetach()
1475{
1476 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001477 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001478 if (log)
1479 log->Printf ("ProcessGDBRemote::DoDetach()");
1480
1481 DisableAllBreakpointSites ();
1482
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001483 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001484
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001485 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1486 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001487 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001488 if (response_size)
1489 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1490 else
1491 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001492 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001493 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001494 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001495
Greg Clayton4fb400f2010-09-27 21:07:38 +00001496 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001497 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001498
1499 SetPrivateState (eStateDetached);
1500 ResumePrivateStateThread();
1501
1502 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001503 return error;
1504}
Chris Lattner24943d22010-06-08 16:52:24 +00001505
1506Error
1507ProcessGDBRemote::DoDestroy ()
1508{
1509 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001510 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001511 if (log)
1512 log->Printf ("ProcessGDBRemote::DoDestroy()");
1513
1514 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001515 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001516 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001517 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001518 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001519 // We are being asked to halt during an attach. We need to just close
1520 // our file handle and debugserver will go away, and we can be done...
1521 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001522 }
1523 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001524 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001525
1526 StringExtractorGDBRemote response;
1527 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001528 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001529 {
1530 char packet_cmd = response.GetChar(0);
1531
1532 if (packet_cmd == 'W' || packet_cmd == 'X')
1533 {
1534 m_last_stop_packet = response;
1535 SetExitStatus(response.GetHexU8(), NULL);
1536 }
1537 }
1538 else
1539 {
1540 SetExitStatus(SIGABRT, NULL);
1541 //error.SetErrorString("kill packet failed");
1542 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001543 }
1544 }
Chris Lattner24943d22010-06-08 16:52:24 +00001545 StopAsyncThread ();
1546 m_gdb_comm.StopReadThread();
1547 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001548 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001549 return error;
1550}
1551
Chris Lattner24943d22010-06-08 16:52:24 +00001552//------------------------------------------------------------------
1553// Process Queries
1554//------------------------------------------------------------------
1555
1556bool
1557ProcessGDBRemote::IsAlive ()
1558{
Greg Clayton58e844b2010-12-08 05:08:21 +00001559 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001560}
1561
1562addr_t
1563ProcessGDBRemote::GetImageInfoAddress()
1564{
1565 if (!m_gdb_comm.IsRunning())
1566 {
1567 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001568 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001569 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001570 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001571 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1572 }
1573 }
1574 return LLDB_INVALID_ADDRESS;
1575}
1576
Chris Lattner24943d22010-06-08 16:52:24 +00001577//------------------------------------------------------------------
1578// Process Memory
1579//------------------------------------------------------------------
1580size_t
1581ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1582{
1583 if (size > m_max_memory_size)
1584 {
1585 // Keep memory read sizes down to a sane limit. This function will be
1586 // called multiple times in order to complete the task by
1587 // lldb_private::Process so it is ok to do this.
1588 size = m_max_memory_size;
1589 }
1590
1591 char packet[64];
1592 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1593 assert (packet_len + 1 < sizeof(packet));
1594 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001595 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001596 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001597 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001598 {
1599 error.Clear();
1600 return response.GetHexBytes(buf, size, '\xdd');
1601 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001602 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001603 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001604 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001605 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1606 else
1607 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1608 }
1609 else
1610 {
1611 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1612 }
1613 return 0;
1614}
1615
1616size_t
1617ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1618{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001619 if (size > m_max_memory_size)
1620 {
1621 // Keep memory read sizes down to a sane limit. This function will be
1622 // called multiple times in order to complete the task by
1623 // lldb_private::Process so it is ok to do this.
1624 size = m_max_memory_size;
1625 }
1626
Chris Lattner24943d22010-06-08 16:52:24 +00001627 StreamString packet;
1628 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001629 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001630 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001631 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001632 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001633 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001634 {
1635 error.Clear();
1636 return size;
1637 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001638 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001639 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001640 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001641 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1642 else
1643 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1644 }
1645 else
1646 {
1647 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1648 }
1649 return 0;
1650}
1651
1652lldb::addr_t
1653ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1654{
Greg Clayton989816b2011-05-14 01:50:35 +00001655 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1656
Greg Clayton2f085c62011-05-15 01:25:55 +00001657 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001658 switch (supported)
1659 {
1660 case eLazyBoolCalculate:
1661 case eLazyBoolYes:
1662 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1663 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1664 return allocated_addr;
1665
1666 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001667 // Call mmap() to create memory in the inferior..
1668 unsigned prot = 0;
1669 if (permissions & lldb::ePermissionsReadable)
1670 prot |= eMmapProtRead;
1671 if (permissions & lldb::ePermissionsWritable)
1672 prot |= eMmapProtWrite;
1673 if (permissions & lldb::ePermissionsExecutable)
1674 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001675
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001676 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1677 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1678 m_addr_to_mmap_size[allocated_addr] = size;
1679 else
1680 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001681 break;
1682 }
1683
Chris Lattner24943d22010-06-08 16:52:24 +00001684 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001685 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001686 else
1687 error.Clear();
1688 return allocated_addr;
1689}
1690
1691Error
1692ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1693{
1694 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001695 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1696
1697 switch (supported)
1698 {
1699 case eLazyBoolCalculate:
1700 // We should never be deallocating memory without allocating memory
1701 // first so we should never get eLazyBoolCalculate
1702 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1703 break;
1704
1705 case eLazyBoolYes:
1706 if (!m_gdb_comm.DeallocateMemory (addr))
1707 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1708 break;
1709
1710 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001711 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001712 {
1713 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001714 if (pos != m_addr_to_mmap_size.end() &&
1715 InferiorCallMunmap(this, addr, pos->second))
1716 m_addr_to_mmap_size.erase (pos);
1717 else
1718 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001719 }
1720 break;
1721 }
1722
Chris Lattner24943d22010-06-08 16:52:24 +00001723 return error;
1724}
1725
1726
1727//------------------------------------------------------------------
1728// Process STDIO
1729//------------------------------------------------------------------
1730
1731size_t
1732ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1733{
1734 Mutex::Locker locker(m_stdio_mutex);
1735 size_t bytes_available = m_stdout_data.size();
1736 if (bytes_available > 0)
1737 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001738 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1739 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001740 log->Printf ("ProcessGDBRemote::%s (&%p[%lu]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001741 if (bytes_available > buf_size)
1742 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001743 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001744 m_stdout_data.erase(0, buf_size);
1745 bytes_available = buf_size;
1746 }
1747 else
1748 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001749 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001750 m_stdout_data.clear();
1751
1752 //ResetEventBits(eBroadcastBitSTDOUT);
1753 }
1754 }
1755 return bytes_available;
1756}
1757
1758size_t
1759ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1760{
1761 // Can we get STDERR through the remote protocol?
1762 return 0;
1763}
1764
1765size_t
1766ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1767{
1768 if (m_stdio_communication.IsConnected())
1769 {
1770 ConnectionStatus status;
1771 m_stdio_communication.Write(src, src_len, status, NULL);
1772 }
1773 return 0;
1774}
1775
1776Error
1777ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1778{
1779 Error error;
1780 assert (bp_site != NULL);
1781
Greg Claytone005f2c2010-11-06 01:53:30 +00001782 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001783 user_id_t site_id = bp_site->GetID();
1784 const addr_t addr = bp_site->GetLoadAddress();
1785 if (log)
1786 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr);
1787
1788 if (bp_site->IsEnabled())
1789 {
1790 if (log)
1791 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
1792 return error;
1793 }
1794 else
1795 {
1796 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1797
1798 if (bp_site->HardwarePreferred())
1799 {
1800 // Try and set hardware breakpoint, and if that fails, fall through
1801 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001802 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001803 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001804 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001805 {
1806 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001807 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001808 return error;
1809 }
Chris Lattner24943d22010-06-08 16:52:24 +00001810 }
1811 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001812
1813 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001814 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001815 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1816 {
1817 bp_site->SetEnabled(true);
1818 bp_site->SetType (BreakpointSite::eExternal);
1819 return error;
1820 }
Chris Lattner24943d22010-06-08 16:52:24 +00001821 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001822
1823 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001824 }
1825
1826 if (log)
1827 {
1828 const char *err_string = error.AsCString();
1829 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1830 bp_site->GetLoadAddress(),
1831 err_string ? err_string : "NULL");
1832 }
1833 // We shouldn't reach here on a successful breakpoint enable...
1834 if (error.Success())
1835 error.SetErrorToGenericError();
1836 return error;
1837}
1838
1839Error
1840ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1841{
1842 Error error;
1843 assert (bp_site != NULL);
1844 addr_t addr = bp_site->GetLoadAddress();
1845 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001846 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001847 if (log)
1848 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr);
1849
1850 if (bp_site->IsEnabled())
1851 {
1852 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1853
Greg Claytonb72d0f02011-04-12 05:54:46 +00001854 BreakpointSite::Type bp_type = bp_site->GetType();
1855 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001856 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001857 case BreakpointSite::eSoftware:
1858 error = DisableSoftwareBreakpoint (bp_site);
1859 break;
1860
1861 case BreakpointSite::eHardware:
1862 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1863 error.SetErrorToGenericError();
1864 break;
1865
1866 case BreakpointSite::eExternal:
1867 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1868 error.SetErrorToGenericError();
1869 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001870 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001871 if (error.Success())
1872 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001873 }
1874 else
1875 {
1876 if (log)
1877 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
1878 return error;
1879 }
1880
1881 if (error.Success())
1882 error.SetErrorToGenericError();
1883 return error;
1884}
1885
Johnny Chen21900fb2011-09-06 22:38:36 +00001886// Pre-requisite: wp != NULL.
1887static GDBStoppointType
1888GetGDBStoppointType (WatchpointLocation *wp)
1889{
1890 assert(wp);
1891 bool watch_read = wp->WatchpointRead();
1892 bool watch_write = wp->WatchpointWrite();
1893
1894 // watch_read and watch_write cannot both be false.
1895 assert(watch_read || watch_write);
1896 if (watch_read && watch_write)
1897 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001898 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00001899 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00001900 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00001901 return eWatchpointWrite;
1902}
1903
Chris Lattner24943d22010-06-08 16:52:24 +00001904Error
1905ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp)
1906{
1907 Error error;
1908 if (wp)
1909 {
1910 user_id_t watchID = wp->GetID();
1911 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001912 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001913 if (log)
1914 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID);
1915 if (wp->IsEnabled())
1916 {
1917 if (log)
1918 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1919 return error;
1920 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001921
1922 GDBStoppointType type = GetGDBStoppointType(wp);
1923 // Pass down an appropriate z/Z packet...
1924 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00001925 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001926 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
1927 {
1928 wp->SetEnabled(true);
1929 return error;
1930 }
1931 else
1932 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001933 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001934 else
1935 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00001936 }
1937 else
1938 {
1939 error.SetErrorString("Watchpoint location argument was NULL.");
1940 }
1941 if (error.Success())
1942 error.SetErrorToGenericError();
1943 return error;
1944}
1945
1946Error
1947ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp)
1948{
1949 Error error;
1950 if (wp)
1951 {
1952 user_id_t watchID = wp->GetID();
1953
Greg Claytone005f2c2010-11-06 01:53:30 +00001954 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001955
1956 addr_t addr = wp->GetLoadAddress();
1957 if (log)
1958 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr);
1959
Johnny Chen21900fb2011-09-06 22:38:36 +00001960 if (!wp->IsEnabled())
1961 {
1962 if (log)
1963 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
1964 return error;
1965 }
1966
Chris Lattner24943d22010-06-08 16:52:24 +00001967 if (wp->IsHardware())
1968 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001969 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00001970 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00001971 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
1972 {
1973 wp->SetEnabled(false);
1974 return error;
1975 }
1976 else
1977 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001978 }
1979 // TODO: clear software watchpoints if we implement them
1980 }
1981 else
1982 {
1983 error.SetErrorString("Watchpoint location argument was NULL.");
1984 }
1985 if (error.Success())
1986 error.SetErrorToGenericError();
1987 return error;
1988}
1989
1990void
1991ProcessGDBRemote::Clear()
1992{
1993 m_flags = 0;
1994 m_thread_list.Clear();
1995 {
1996 Mutex::Locker locker(m_stdio_mutex);
1997 m_stdout_data.clear();
1998 }
Chris Lattner24943d22010-06-08 16:52:24 +00001999}
2000
2001Error
2002ProcessGDBRemote::DoSignal (int signo)
2003{
2004 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002005 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002006 if (log)
2007 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2008
2009 if (!m_gdb_comm.SendAsyncSignal (signo))
2010 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2011 return error;
2012}
2013
Chris Lattner24943d22010-06-08 16:52:24 +00002014Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002015ProcessGDBRemote::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 +00002016{
2017 Error error;
2018 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2019 {
2020 // If we locate debugserver, keep that located version around
2021 static FileSpec g_debugserver_file_spec;
2022
Greg Claytonb72d0f02011-04-12 05:54:46 +00002023 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002024 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002025 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002026
2027 // Always check to see if we have an environment override for the path
2028 // to the debugserver to use and use it if we do.
2029 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2030 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002031 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002032 else
2033 debugserver_file_spec = g_debugserver_file_spec;
2034 bool debugserver_exists = debugserver_file_spec.Exists();
2035 if (!debugserver_exists)
2036 {
2037 // The debugserver binary is in the LLDB.framework/Resources
2038 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002039 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002040 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002041 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002042 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002043 if (debugserver_exists)
2044 {
2045 g_debugserver_file_spec = debugserver_file_spec;
2046 }
2047 else
2048 {
2049 g_debugserver_file_spec.Clear();
2050 debugserver_file_spec.Clear();
2051 }
Chris Lattner24943d22010-06-08 16:52:24 +00002052 }
2053 }
2054
2055 if (debugserver_exists)
2056 {
2057 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2058
2059 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002060
Greg Claytone005f2c2010-11-06 01:53:30 +00002061 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002062
Greg Claytonb72d0f02011-04-12 05:54:46 +00002063 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002064 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002065
Chris Lattner24943d22010-06-08 16:52:24 +00002066 // Start args with "debugserver /file/path -r --"
2067 debugserver_args.AppendArgument(debugserver_path);
2068 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002069 // use native registers, not the GDB registers
2070 debugserver_args.AppendArgument("--native-regs");
2071 // make debugserver run in its own session so signals generated by
2072 // special terminal key sequences (^C) don't affect debugserver
2073 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002074
Chris Lattner24943d22010-06-08 16:52:24 +00002075 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2076 if (env_debugserver_log_file)
2077 {
2078 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2079 debugserver_args.AppendArgument(arg_cstr);
2080 }
2081
2082 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2083 if (env_debugserver_log_flags)
2084 {
2085 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2086 debugserver_args.AppendArgument(arg_cstr);
2087 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002088// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002089// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002090
Greg Claytonb72d0f02011-04-12 05:54:46 +00002091 // We currently send down all arguments, attach pids, or attach
2092 // process names in dedicated GDB server packets, so we don't need
2093 // to pass them as arguments. This is currently because of all the
2094 // things we need to setup prior to launching: the environment,
2095 // current working dir, file actions, etc.
2096#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002097 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002098 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002099 {
Greg Claytona2f74232011-02-24 22:24:29 +00002100 // Terminate the debugserver args so we can now append the inferior args
2101 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002102
Greg Claytona2f74232011-02-24 22:24:29 +00002103 for (int i = 0; inferior_argv[i] != NULL; ++i)
2104 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002105 }
2106 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2107 {
2108 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2109 debugserver_args.AppendArgument (arg_cstr);
2110 }
2111 else if (attach_name && attach_name[0])
2112 {
2113 if (wait_for_launch)
2114 debugserver_args.AppendArgument ("--waitfor");
2115 else
2116 debugserver_args.AppendArgument ("--attach");
2117 debugserver_args.AppendArgument (attach_name);
2118 }
Chris Lattner24943d22010-06-08 16:52:24 +00002119#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002120
2121 ProcessLaunchInfo::FileAction file_action;
2122
2123 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2124 // to "/dev/null" if we run into any problems.
2125 file_action.Close (STDIN_FILENO);
2126 launch_info.AppendFileAction (file_action);
2127 file_action.Close (STDOUT_FILENO);
2128 launch_info.AppendFileAction (file_action);
2129 file_action.Close (STDERR_FILENO);
2130 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002131
2132 if (log)
2133 {
2134 StreamString strm;
2135 debugserver_args.Dump (&strm);
2136 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2137 }
2138
Greg Claytonb72d0f02011-04-12 05:54:46 +00002139 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002140
Greg Claytonb72d0f02011-04-12 05:54:46 +00002141 if (error.Success ())
2142 m_debugserver_pid = launch_info.GetProcessID();
2143 else
Chris Lattner24943d22010-06-08 16:52:24 +00002144 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2145
2146 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002147 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002148 }
2149 else
2150 {
2151 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
2152 }
2153
2154 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2155 StartAsyncThread ();
2156 }
2157 return error;
2158}
2159
2160bool
2161ProcessGDBRemote::MonitorDebugserverProcess
2162(
2163 void *callback_baton,
2164 lldb::pid_t debugserver_pid,
2165 int signo, // Zero for no signal
2166 int exit_status // Exit value of process if signal is zero
2167)
2168{
2169 // We pass in the ProcessGDBRemote inferior process it and name it
2170 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2171 // pointer value itself, thus we need the double cast...
2172
2173 // "debugserver_pid" argument passed in is the process ID for
2174 // debugserver that we are tracking...
2175
Greg Clayton75ccf502010-08-21 02:22:51 +00002176 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002177
2178 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2179 if (log)
2180 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2181
Greg Clayton75ccf502010-08-21 02:22:51 +00002182 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002183 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002184 // Sleep for a half a second to make sure our inferior process has
2185 // time to set its exit status before we set it incorrectly when
2186 // both the debugserver and the inferior process shut down.
2187 usleep (500000);
2188 // If our process hasn't yet exited, debugserver might have died.
2189 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002190 const StateType state = process->GetState();
2191
2192 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2193 state != eStateInvalid &&
2194 state != eStateUnloaded &&
2195 state != eStateExited &&
2196 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002197 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002198 char error_str[1024];
2199 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002200 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002201 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2202 if (signal_cstr)
2203 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002204 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002205 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002206 }
2207 else
2208 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002209 ::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 +00002210 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002211
2212 process->SetExitStatus (-1, error_str);
2213 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002214 // Debugserver has exited we need to let our ProcessGDBRemote
2215 // know that it no longer has a debugserver instance
2216 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2217 // We are returning true to this function below, so we can
2218 // forget about the monitor handle.
2219 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002220 }
2221 return true;
2222}
2223
2224void
2225ProcessGDBRemote::KillDebugserverProcess ()
2226{
2227 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2228 {
2229 ::kill (m_debugserver_pid, SIGINT);
2230 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2231 }
2232}
2233
2234void
2235ProcessGDBRemote::Initialize()
2236{
2237 static bool g_initialized = false;
2238
2239 if (g_initialized == false)
2240 {
2241 g_initialized = true;
2242 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2243 GetPluginDescriptionStatic(),
2244 CreateInstance);
2245
2246 Log::Callbacks log_callbacks = {
2247 ProcessGDBRemoteLog::DisableLog,
2248 ProcessGDBRemoteLog::EnableLog,
2249 ProcessGDBRemoteLog::ListLogCategories
2250 };
2251
2252 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2253 }
2254}
2255
2256bool
Chris Lattner24943d22010-06-08 16:52:24 +00002257ProcessGDBRemote::StartAsyncThread ()
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 // Create a thread that watches our internal state and controls which
2265 // events make it to clients (into the DCProcess event queue).
2266 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002267 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002268}
2269
2270void
2271ProcessGDBRemote::StopAsyncThread ()
2272{
Greg Claytone005f2c2010-11-06 01:53:30 +00002273 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002274
2275 if (log)
2276 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2277
2278 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2279
2280 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002281 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002282 {
2283 Host::ThreadJoin (m_async_thread, NULL, NULL);
2284 }
2285}
2286
2287
2288void *
2289ProcessGDBRemote::AsyncThread (void *arg)
2290{
2291 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2292
Greg Claytone005f2c2010-11-06 01:53:30 +00002293 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002294 if (log)
2295 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
2296
2297 Listener listener ("ProcessGDBRemote::AsyncThread");
2298 EventSP event_sp;
2299 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2300 eBroadcastBitAsyncThreadShouldExit;
2301
2302 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2303 {
Greg Claytona2f74232011-02-24 22:24:29 +00002304 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2305
Chris Lattner24943d22010-06-08 16:52:24 +00002306 bool done = false;
2307 while (!done)
2308 {
2309 if (log)
2310 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2311 if (listener.WaitForEvent (NULL, event_sp))
2312 {
2313 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002314 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002315 {
Greg Claytona2f74232011-02-24 22:24:29 +00002316 if (log)
2317 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002318
Greg Claytona2f74232011-02-24 22:24:29 +00002319 switch (event_type)
2320 {
2321 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002322 {
Greg Claytona2f74232011-02-24 22:24:29 +00002323 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002324
Greg Claytona2f74232011-02-24 22:24:29 +00002325 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002326 {
Greg Claytona2f74232011-02-24 22:24:29 +00002327 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2328 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2329 if (log)
2330 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002331
Greg Claytona2f74232011-02-24 22:24:29 +00002332 if (::strstr (continue_cstr, "vAttach") == NULL)
2333 process->SetPrivateState(eStateRunning);
2334 StringExtractorGDBRemote response;
2335 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002336
Greg Claytona2f74232011-02-24 22:24:29 +00002337 switch (stop_state)
2338 {
2339 case eStateStopped:
2340 case eStateCrashed:
2341 case eStateSuspended:
2342 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002343 process->SetPrivateState (stop_state);
2344 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002345
Greg Claytona2f74232011-02-24 22:24:29 +00002346 case eStateExited:
2347 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002348 response.SetFilePos(1);
2349 process->SetExitStatus(response.GetHexU8(), NULL);
2350 done = true;
2351 break;
2352
2353 case eStateInvalid:
2354 process->SetExitStatus(-1, "lost connection");
2355 break;
2356
2357 default:
2358 process->SetPrivateState (stop_state);
2359 break;
2360 }
Chris Lattner24943d22010-06-08 16:52:24 +00002361 }
2362 }
Greg Claytona2f74232011-02-24 22:24:29 +00002363 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002364
Greg Claytona2f74232011-02-24 22:24:29 +00002365 case eBroadcastBitAsyncThreadShouldExit:
2366 if (log)
2367 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2368 done = true;
2369 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002370
Greg Claytona2f74232011-02-24 22:24:29 +00002371 default:
2372 if (log)
2373 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2374 done = true;
2375 break;
2376 }
2377 }
2378 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2379 {
2380 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2381 {
2382 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002383 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002384 }
Chris Lattner24943d22010-06-08 16:52:24 +00002385 }
2386 }
2387 else
2388 {
2389 if (log)
2390 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2391 done = true;
2392 }
2393 }
2394 }
2395
2396 if (log)
2397 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
2398
2399 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2400 return NULL;
2401}
2402
Chris Lattner24943d22010-06-08 16:52:24 +00002403const char *
2404ProcessGDBRemote::GetDispatchQueueNameForThread
2405(
2406 addr_t thread_dispatch_qaddr,
2407 std::string &dispatch_queue_name
2408)
2409{
2410 dispatch_queue_name.clear();
2411 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2412 {
2413 // Cache the dispatch_queue_offsets_addr value so we don't always have
2414 // to look it up
2415 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2416 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002417 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2418 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002419 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002420 if (module_sp)
2421 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2422
2423 if (dispatch_queue_offsets_symbol == NULL)
2424 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002425 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002426 if (module_sp)
2427 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2428 }
Chris Lattner24943d22010-06-08 16:52:24 +00002429 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002430 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002431
2432 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2433 return NULL;
2434 }
2435
2436 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002437 DataExtractor data (memory_buffer,
2438 sizeof(memory_buffer),
2439 m_target.GetArchitecture().GetByteOrder(),
2440 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002441
2442 // Excerpt from src/queue_private.h
2443 struct dispatch_queue_offsets_s
2444 {
2445 uint16_t dqo_version;
2446 uint16_t dqo_label;
2447 uint16_t dqo_label_size;
2448 } dispatch_queue_offsets;
2449
2450
2451 Error error;
2452 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2453 {
2454 uint32_t data_offset = 0;
2455 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2456 {
2457 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2458 {
2459 data_offset = 0;
2460 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2461 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2462 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2463 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2464 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2465 dispatch_queue_name.erase (bytes_read);
2466 }
2467 }
2468 }
2469 }
2470 if (dispatch_queue_name.empty())
2471 return NULL;
2472 return dispatch_queue_name.c_str();
2473}
2474
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002475//uint32_t
2476//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2477//{
2478// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2479// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2480// if (m_local_debugserver)
2481// {
2482// return Host::ListProcessesMatchingName (name, matches, pids);
2483// }
2484// else
2485// {
2486// // FIXME: Implement talking to the remote debugserver.
2487// return 0;
2488// }
2489//
2490//}
2491//
Jim Ingham55e01d82011-01-22 01:33:44 +00002492bool
2493ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2494 lldb_private::StoppointCallbackContext *context,
2495 lldb::user_id_t break_id,
2496 lldb::user_id_t break_loc_id)
2497{
2498 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2499 // run so I can stop it if that's what I want to do.
2500 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2501 if (log)
2502 log->Printf("Hit New Thread Notification breakpoint.");
2503 return false;
2504}
2505
2506
2507bool
2508ProcessGDBRemote::StartNoticingNewThreads()
2509{
2510 static const char *bp_names[] =
2511 {
2512 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002513 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002514 "_pthread_start",
2515 NULL
2516 };
2517
2518 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2519 size_t num_bps = m_thread_observation_bps.size();
2520 if (num_bps != 0)
2521 {
2522 for (int i = 0; i < num_bps; i++)
2523 {
2524 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2525 if (break_sp)
2526 {
2527 if (log)
2528 log->Printf("Enabled noticing new thread breakpoint.");
2529 break_sp->SetEnabled(true);
2530 }
2531 }
2532 }
2533 else
2534 {
2535 for (int i = 0; bp_names[i] != NULL; i++)
2536 {
2537 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get();
2538 if (breakpoint)
2539 {
2540 if (log)
2541 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2542 m_thread_observation_bps.push_back(breakpoint->GetID());
2543 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2544 }
2545 else
2546 {
2547 if (log)
2548 log->Printf("Failed to create new thread notification breakpoint.");
2549 return false;
2550 }
2551 }
2552 }
2553
2554 return true;
2555}
2556
2557bool
2558ProcessGDBRemote::StopNoticingNewThreads()
2559{
Jim Inghamff276fe2011-02-08 05:19:01 +00002560 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2561 if (log)
2562 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002563 size_t num_bps = m_thread_observation_bps.size();
2564 if (num_bps != 0)
2565 {
2566 for (int i = 0; i < num_bps; i++)
2567 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002568
2569 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2570 if (break_sp)
2571 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002572 break_sp->SetEnabled(false);
2573 }
2574 }
2575 }
2576 return true;
2577}
2578
2579