blob: 917fc4df360a7dfbc43f77b396bed96c6f963a60 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Greg Clayton989816b2011-05-14 01:50:35 +000014#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000015#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000016#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000017#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000018
19// C++ Includes
20#include <algorithm>
21#include <map>
22
23// Other libraries and framework includes
24
Johnny Chenecd4feb2011-10-14 00:42:25 +000025#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000026#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Core/ArchSpec.h"
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000030#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Core/InputReader.h"
32#include "lldb/Core/Module.h"
33#include "lldb/Core/PluginManager.h"
34#include "lldb/Core/State.h"
35#include "lldb/Core/StreamString.h"
36#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000037#include "lldb/Core/Value.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Host/TimeValue.h"
39#include "lldb/Symbol/ObjectFile.h"
40#include "lldb/Target/DynamicLoader.h"
41#include "lldb/Target/Target.h"
42#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000043#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000044#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045
46// Project includes
47#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000048#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000049#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000050#include "GDBRemoteRegisterContext.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000054#include "StopInfoMachException.h"
55
Chris Lattner24943d22010-06-08 16:52:24 +000056
Chris Lattner24943d22010-06-08 16:52:24 +000057
58#define DEBUGSERVER_BASENAME "debugserver"
59using namespace lldb;
60using namespace lldb_private;
61
Jim Inghamf9600482011-03-29 21:45:47 +000062static bool rand_initialized = false;
63
Chris Lattner24943d22010-06-08 16:52:24 +000064static inline uint16_t
65get_random_port ()
66{
Jim Inghamf9600482011-03-29 21:45:47 +000067 if (!rand_initialized)
68 {
Stephen Wilson60f19d52011-03-30 00:12:40 +000069 time_t seed = time(NULL);
70
Jim Inghamf9600482011-03-29 21:45:47 +000071 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +000072 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +000073 }
Stephen Wilson50daf772011-03-25 18:16:28 +000074 return (rand() % (UINT16_MAX - 1000u)) + 1000u;
Chris Lattner24943d22010-06-08 16:52:24 +000075}
76
77
78const char *
79ProcessGDBRemote::GetPluginNameStatic()
80{
Greg Claytonb1888f22011-03-19 01:12:21 +000081 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +000082}
83
84const char *
85ProcessGDBRemote::GetPluginDescriptionStatic()
86{
87 return "GDB Remote protocol based debugging plug-in.";
88}
89
90void
91ProcessGDBRemote::Terminate()
92{
93 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
94}
95
96
97Process*
98ProcessGDBRemote::CreateInstance (Target &target, Listener &listener)
99{
100 return new ProcessGDBRemote (target, listener);
101}
102
103bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000104ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000105{
Greg Clayton61ddf562011-10-21 21:41:45 +0000106 if (plugin_specified_by_name)
107 return true;
108
Chris Lattner24943d22010-06-08 16:52:24 +0000109 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000110 Module *exe_module = target.GetExecutableModulePointer();
111 if (exe_module)
112 return exe_module->GetFileSpec().Exists();
Jim Ingham7508e732010-08-09 23:31:02 +0000113 // However, if there is no executable module, we return true since we might be preparing to attach.
114 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000115}
116
117//----------------------------------------------------------------------
118// ProcessGDBRemote constructor
119//----------------------------------------------------------------------
120ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
121 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000122 m_flags (0),
Chris Lattner24943d22010-06-08 16:52:24 +0000123 m_stdio_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000124 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000125 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton75ccf502010-08-21 02:22:51 +0000126 m_debugserver_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000127 m_last_stop_packet (),
Chris Lattner24943d22010-06-08 16:52:24 +0000128 m_register_info (),
Chris Lattner24943d22010-06-08 16:52:24 +0000129 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"),
130 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonc1f45872011-02-12 06:28:37 +0000131 m_continue_c_tids (),
132 m_continue_C_tids (),
133 m_continue_s_tids (),
134 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000135 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000136 m_max_memory_size (512),
Jim Ingham7508e732010-08-09 23:31:02 +0000137 m_waiting_for_attach (false),
Jim Ingham55e01d82011-01-22 01:33:44 +0000138 m_thread_observation_bps()
Chris Lattner24943d22010-06-08 16:52:24 +0000139{
Greg Claytonff39f742011-04-01 00:29:43 +0000140 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
141 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Chris Lattner24943d22010-06-08 16:52:24 +0000142}
143
144//----------------------------------------------------------------------
145// Destructor
146//----------------------------------------------------------------------
147ProcessGDBRemote::~ProcessGDBRemote()
148{
Greg Clayton09c81ef2011-02-08 01:34:25 +0000149 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread))
Greg Clayton75ccf502010-08-21 02:22:51 +0000150 {
151 Host::ThreadCancel (m_debugserver_thread, NULL);
152 thread_result_t thread_result;
153 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL);
154 m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
155 }
Chris Lattner24943d22010-06-08 16:52:24 +0000156 // m_mach_process.UnregisterNotificationCallbacks (this);
157 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000158 // We need to call finalize on the process before destroying ourselves
159 // to make sure all of the broadcaster cleanup goes as planned. If we
160 // destruct this class, then Process::~Process() might have problems
161 // trying to fully destroy the broadcaster.
162 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000163}
164
165//----------------------------------------------------------------------
166// PluginInterface
167//----------------------------------------------------------------------
168const char *
169ProcessGDBRemote::GetPluginName()
170{
171 return "Process debugging plug-in that uses the GDB remote protocol";
172}
173
174const char *
175ProcessGDBRemote::GetShortPluginName()
176{
177 return GetPluginNameStatic();
178}
179
180uint32_t
181ProcessGDBRemote::GetPluginVersion()
182{
183 return 1;
184}
185
186void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000187ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000188{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000189 if (!force && m_register_info.GetNumRegisters() > 0)
190 return;
191
192 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000193 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000194 uint32_t reg_offset = 0;
195 uint32_t reg_num = 0;
Greg Clayton61d043b2011-03-22 04:00:09 +0000196 StringExtractorGDBRemote::ResponseType response_type;
197 for (response_type = StringExtractorGDBRemote::eResponse;
198 response_type == StringExtractorGDBRemote::eResponse;
199 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000200 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000201 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
202 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000203 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000204 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000205 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000206 response_type = response.GetResponseType();
207 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000208 {
209 std::string name;
210 std::string value;
211 ConstString reg_name;
212 ConstString alt_name;
213 ConstString set_name;
214 RegisterInfo reg_info = { NULL, // Name
215 NULL, // Alt name
216 0, // byte size
217 reg_offset, // offset
218 eEncodingUint, // encoding
219 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000220 {
221 LLDB_INVALID_REGNUM, // GCC reg num
222 LLDB_INVALID_REGNUM, // DWARF reg num
223 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000224 reg_num, // GDB reg num
225 reg_num // native register number
Chris Lattner24943d22010-06-08 16:52:24 +0000226 }
227 };
228
229 while (response.GetNameColonValue(name, value))
230 {
231 if (name.compare("name") == 0)
232 {
233 reg_name.SetCString(value.c_str());
234 }
235 else if (name.compare("alt-name") == 0)
236 {
237 alt_name.SetCString(value.c_str());
238 }
239 else if (name.compare("bitsize") == 0)
240 {
241 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
242 }
243 else if (name.compare("offset") == 0)
244 {
245 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000246 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000247 {
248 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000249 }
250 }
251 else if (name.compare("encoding") == 0)
252 {
253 if (value.compare("uint") == 0)
254 reg_info.encoding = eEncodingUint;
255 else if (value.compare("sint") == 0)
256 reg_info.encoding = eEncodingSint;
257 else if (value.compare("ieee754") == 0)
258 reg_info.encoding = eEncodingIEEE754;
259 else if (value.compare("vector") == 0)
260 reg_info.encoding = eEncodingVector;
261 }
262 else if (name.compare("format") == 0)
263 {
264 if (value.compare("binary") == 0)
265 reg_info.format = eFormatBinary;
266 else if (value.compare("decimal") == 0)
267 reg_info.format = eFormatDecimal;
268 else if (value.compare("hex") == 0)
269 reg_info.format = eFormatHex;
270 else if (value.compare("float") == 0)
271 reg_info.format = eFormatFloat;
272 else if (value.compare("vector-sint8") == 0)
273 reg_info.format = eFormatVectorOfSInt8;
274 else if (value.compare("vector-uint8") == 0)
275 reg_info.format = eFormatVectorOfUInt8;
276 else if (value.compare("vector-sint16") == 0)
277 reg_info.format = eFormatVectorOfSInt16;
278 else if (value.compare("vector-uint16") == 0)
279 reg_info.format = eFormatVectorOfUInt16;
280 else if (value.compare("vector-sint32") == 0)
281 reg_info.format = eFormatVectorOfSInt32;
282 else if (value.compare("vector-uint32") == 0)
283 reg_info.format = eFormatVectorOfUInt32;
284 else if (value.compare("vector-float32") == 0)
285 reg_info.format = eFormatVectorOfFloat32;
286 else if (value.compare("vector-uint128") == 0)
287 reg_info.format = eFormatVectorOfUInt128;
288 }
289 else if (name.compare("set") == 0)
290 {
291 set_name.SetCString(value.c_str());
292 }
293 else if (name.compare("gcc") == 0)
294 {
295 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
296 }
297 else if (name.compare("dwarf") == 0)
298 {
299 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
300 }
301 else if (name.compare("generic") == 0)
302 {
303 if (value.compare("pc") == 0)
304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC;
305 else if (value.compare("sp") == 0)
306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP;
307 else if (value.compare("fp") == 0)
308 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP;
309 else if (value.compare("ra") == 0)
310 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA;
311 else if (value.compare("flags") == 0)
312 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS;
Greg Clayton5a269102011-05-22 04:32:55 +0000313 else if (value.find("arg") == 0)
314 {
315 if (value.size() == 4)
316 {
317 switch (value[3])
318 {
319 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break;
320 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break;
321 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break;
322 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break;
323 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break;
324 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break;
325 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break;
326 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break;
327 }
328 }
329 }
Chris Lattner24943d22010-06-08 16:52:24 +0000330 }
331 }
332
Jason Molenda53d96862010-06-11 23:44:18 +0000333 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000334 assert (reg_info.byte_size != 0);
335 reg_offset += reg_info.byte_size;
336 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
337 }
338 }
339 else
340 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000341 response_type = StringExtractorGDBRemote::eError;
Greg Clayton24bc5d92011-03-30 18:16:51 +0000342 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000343 }
344 }
345
346 if (reg_num == 0)
347 {
348 // We didn't get anything. See if we are debugging ARM and fill with
349 // a hard coded register set until we can get an updated debugserver
350 // down on the devices.
Jason Molenda428b5502011-10-06 01:45:46 +0000351
352 if (!GetTarget().GetArchitecture().IsValid()
353 && m_gdb_comm.GetHostArchitecture().IsValid()
354 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm
355 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
356 {
Chris Lattner24943d22010-06-08 16:52:24 +0000357 m_register_info.HardcodeARMRegisters();
Jason Molenda428b5502011-10-06 01:45:46 +0000358 }
359 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm)
360 {
361 m_register_info.HardcodeARMRegisters();
362 }
Chris Lattner24943d22010-06-08 16:52:24 +0000363 }
364 m_register_info.Finalize ();
365}
366
367Error
368ProcessGDBRemote::WillLaunch (Module* module)
369{
370 return WillLaunchOrAttach ();
371}
372
373Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000374ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000375{
376 return WillLaunchOrAttach ();
377}
378
379Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000380ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000381{
382 return WillLaunchOrAttach ();
383}
384
385Error
Greg Claytone71e2582011-02-04 01:58:07 +0000386ProcessGDBRemote::DoConnectRemote (const char *remote_url)
387{
388 Error error (WillLaunchOrAttach ());
389
390 if (error.Fail())
391 return error;
392
Greg Clayton180546b2011-04-30 01:09:13 +0000393 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000394
395 if (error.Fail())
396 return error;
397 StartAsyncThread ();
398
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000399 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000400 if (pid == LLDB_INVALID_PROCESS_ID)
401 {
402 // We don't have a valid process ID, so note that we are connected
403 // and could now request to launch or attach, or get remote process
404 // listings...
405 SetPrivateState (eStateConnected);
406 }
407 else
408 {
409 // We have a valid process
410 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000411 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000412 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000413 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000414 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000415 if (state == eStateStopped)
416 {
417 SetPrivateState (state);
418 }
419 else
420 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
421 }
422 else
423 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
424 }
425 return error;
426}
427
428Error
Chris Lattner24943d22010-06-08 16:52:24 +0000429ProcessGDBRemote::WillLaunchOrAttach ()
430{
431 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000432 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000433 return error;
434}
435
436//----------------------------------------------------------------------
437// Process Control
438//----------------------------------------------------------------------
439Error
440ProcessGDBRemote::DoLaunch
441(
442 Module* module,
443 char const *argv[],
444 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +0000445 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +0000446 const char *stdin_path,
447 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +0000448 const char *stderr_path,
449 const char *working_dir
Chris Lattner24943d22010-06-08 16:52:24 +0000450)
451{
Greg Clayton4b407112010-09-30 21:49:03 +0000452 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000453 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
454 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
455 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000456 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000457
458 ObjectFile * object_file = module->GetObjectFile();
459 if (object_file)
460 {
Chris Lattner24943d22010-06-08 16:52:24 +0000461 char host_port[128];
462 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000463 char connect_url[128];
464 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000465
Greg Claytona2f74232011-02-24 22:24:29 +0000466 // Make sure we aren't already connected?
467 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000468 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000469 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000470 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000471 {
Johnny Chenc143d622011-08-09 18:56:45 +0000472 if (log)
473 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000474 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000475 }
Chris Lattner24943d22010-06-08 16:52:24 +0000476
Greg Claytone71e2582011-02-04 01:58:07 +0000477 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000478 }
479
480 if (error.Success())
481 {
482 lldb_utility::PseudoTerminal pty;
483 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000484
485 // If the debugserver is local and we aren't disabling STDIO, lets use
486 // a pseudo terminal to instead of relying on the 'O' packets for stdio
487 // since 'O' packets can really slow down debugging if the inferior
488 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000489 PlatformSP platform_sp (m_target.GetPlatform());
490 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000491 {
492 const char *slave_name = NULL;
493 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000494 {
Greg Claytona2f74232011-02-24 22:24:29 +0000495 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
496 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000497 }
Greg Claytona2f74232011-02-24 22:24:29 +0000498 if (stdin_path == NULL)
499 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000500
Greg Claytona2f74232011-02-24 22:24:29 +0000501 if (stdout_path == NULL)
502 stdout_path = slave_name;
503
504 if (stderr_path == NULL)
505 stderr_path = slave_name;
506 }
507
Greg Claytonafb81862011-03-02 21:34:46 +0000508 // Set STDIN to /dev/null if we want STDIO disabled or if either
509 // STDOUT or STDERR have been set to something and STDIN hasn't
510 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000511 stdin_path = "/dev/null";
512
Greg Claytonafb81862011-03-02 21:34:46 +0000513 // Set STDOUT to /dev/null if we want STDIO disabled or if either
514 // STDIN or STDERR have been set to something and STDOUT hasn't
515 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000516 stdout_path = "/dev/null";
517
Greg Claytonafb81862011-03-02 21:34:46 +0000518 // Set STDERR to /dev/null if we want STDIO disabled or if either
519 // STDIN or STDOUT have been set to something and STDERR hasn't
520 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000521 stderr_path = "/dev/null";
522
523 if (stdin_path)
524 m_gdb_comm.SetSTDIN (stdin_path);
525 if (stdout_path)
526 m_gdb_comm.SetSTDOUT (stdout_path);
527 if (stderr_path)
528 m_gdb_comm.SetSTDERR (stderr_path);
529
530 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
531
Greg Claytona4582402011-05-08 04:53:50 +0000532 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000533
534 if (working_dir && working_dir[0])
535 {
536 m_gdb_comm.SetWorkingDir (working_dir);
537 }
538
539 // Send the environment and the program + arguments after we connect
540 if (envp)
541 {
542 const char *env_entry;
543 for (int i=0; (env_entry = envp[i]); ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000544 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000545 if (m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000546 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000547 }
Greg Claytona2f74232011-02-24 22:24:29 +0000548 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000549
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000550 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
551 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv);
Greg Claytona2f74232011-02-24 22:24:29 +0000552 if (arg_packet_err == 0)
553 {
554 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000555 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000556 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000557 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000558 }
559 else
560 {
Greg Claytona2f74232011-02-24 22:24:29 +0000561 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000562 }
Greg Claytona2f74232011-02-24 22:24:29 +0000563 }
564 else
565 {
Greg Clayton9c236732011-10-26 00:56:27 +0000566 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000567 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000568
569 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000570
Greg Claytona2f74232011-02-24 22:24:29 +0000571 if (GetID() == LLDB_INVALID_PROCESS_ID)
572 {
Johnny Chenc143d622011-08-09 18:56:45 +0000573 if (log)
574 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000575 KillDebugserverProcess ();
576 return error;
577 }
578
Greg Clayton261a18b2011-06-02 22:22:38 +0000579 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000580 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000581 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000582
583 if (!disable_stdio)
584 {
585 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
586 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
587 }
Chris Lattner24943d22010-06-08 16:52:24 +0000588 }
589 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000590 else
591 {
Johnny Chenc143d622011-08-09 18:56:45 +0000592 if (log)
593 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000594 }
Chris Lattner24943d22010-06-08 16:52:24 +0000595 }
596 else
597 {
598 // Set our user ID to an invalid process ID.
599 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton9c236732011-10-26 00:56:27 +0000600 error.SetErrorStringWithFormat("failed to get object file from '%s' for arch %s",
Greg Clayton940b1032011-02-23 00:35:02 +0000601 module->GetFileSpec().GetFilename().AsCString(),
602 module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000603 }
Chris Lattner24943d22010-06-08 16:52:24 +0000604 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000605
Chris Lattner24943d22010-06-08 16:52:24 +0000606}
607
608
609Error
Greg Claytone71e2582011-02-04 01:58:07 +0000610ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000611{
612 Error error;
613 // Sleep and wait a bit for debugserver to start to listen...
614 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
615 if (conn_ap.get())
616 {
Chris Lattner24943d22010-06-08 16:52:24 +0000617 const uint32_t max_retry_count = 50;
618 uint32_t retry_count = 0;
619 while (!m_gdb_comm.IsConnected())
620 {
Greg Claytone71e2582011-02-04 01:58:07 +0000621 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000622 {
623 m_gdb_comm.SetConnection (conn_ap.release());
624 break;
625 }
626 retry_count++;
627
628 if (retry_count >= max_retry_count)
629 break;
630
631 usleep (100000);
632 }
633 }
634
635 if (!m_gdb_comm.IsConnected())
636 {
637 if (error.Success())
638 error.SetErrorString("not connected to remote gdb server");
639 return error;
640 }
641
Greg Clayton24bc5d92011-03-30 18:16:51 +0000642 // We always seem to be able to open a connection to a local port
643 // so we need to make sure we can then send data to it. If we can't
644 // then we aren't actually connected to anything, so try and do the
645 // handshake with the remote GDB server and make sure that goes
646 // alright.
647 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000648 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000649 m_gdb_comm.Disconnect();
650 if (error.Success())
651 error.SetErrorString("not connected to remote gdb server");
652 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000653 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000654 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
655 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
656 this,
657 m_debugserver_pid,
658 false);
659 m_gdb_comm.ResetDiscoverableSettings();
660 m_gdb_comm.QueryNoAckModeSupported ();
661 m_gdb_comm.GetThreadSuffixSupported ();
662 m_gdb_comm.GetHostInfo ();
663 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000664 return error;
665}
666
667void
668ProcessGDBRemote::DidLaunchOrAttach ()
669{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000670 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
671 if (log)
672 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000673 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000674 {
675 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
676
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000677 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000678
Chris Lattner24943d22010-06-08 16:52:24 +0000679 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000680
Greg Claytoncb8977d2011-03-23 00:09:55 +0000681 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
682 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000683 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000684 ArchSpec &target_arch = GetTarget().GetArchitecture();
685
686 if (target_arch.IsValid())
687 {
688 // If the remote host is ARM and we have apple as the vendor, then
689 // ARM executables and shared libraries can have mixed ARM architectures.
690 // You can have an armv6 executable, and if the host is armv7, then the
691 // system will load the best possible architecture for all shared libraries
692 // it has, so we really need to take the remote host architecture as our
693 // defacto architecture in this case.
694
695 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
696 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
697 {
698 target_arch = gdb_remote_arch;
699 }
700 else
701 {
702 // Fill in what is missing in the triple
703 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
704 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000705 if (target_triple.getVendorName().size() == 0)
706 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000707 target_triple.setVendor (remote_triple.getVendor());
708
Greg Clayton2f085c62011-05-15 01:25:55 +0000709 if (target_triple.getOSName().size() == 0)
710 {
711 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000712
Greg Clayton2f085c62011-05-15 01:25:55 +0000713 if (target_triple.getEnvironmentName().size() == 0)
714 target_triple.setEnvironment (remote_triple.getEnvironment());
715 }
716 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000717 }
718 }
719 else
720 {
721 // The target doesn't have a valid architecture yet, set it from
722 // the architecture we got from the remote GDB server
723 target_arch = gdb_remote_arch;
724 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000725 }
Chris Lattner24943d22010-06-08 16:52:24 +0000726 }
727}
728
729void
730ProcessGDBRemote::DidLaunch ()
731{
732 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000733}
734
735Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000736ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000737{
738 Error error;
739 // Clear out and clean up from any current state
740 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000741 if (attach_pid != LLDB_INVALID_PROCESS_ID)
742 {
Greg Claytona2f74232011-02-24 22:24:29 +0000743 // Make sure we aren't already connected?
744 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000745 {
Greg Claytona2f74232011-02-24 22:24:29 +0000746 char host_port[128];
747 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
748 char connect_url[128];
749 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000750
Greg Claytonb72d0f02011-04-12 05:54:46 +0000751 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000752
753 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000754 {
Greg Claytona2f74232011-02-24 22:24:29 +0000755 const char *error_string = error.AsCString();
756 if (error_string == NULL)
757 error_string = "unable to launch " DEBUGSERVER_BASENAME;
758
759 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000760 }
Greg Claytona2f74232011-02-24 22:24:29 +0000761 else
762 {
763 error = ConnectToDebugserver (connect_url);
764 }
765 }
766
767 if (error.Success())
768 {
769 char packet[64];
770 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
771
772 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000773 }
774 }
Chris Lattner24943d22010-06-08 16:52:24 +0000775 return error;
776}
777
778size_t
779ProcessGDBRemote::AttachInputReaderCallback
780(
781 void *baton,
782 InputReader *reader,
783 lldb::InputReaderAction notification,
784 const char *bytes,
785 size_t bytes_len
786)
787{
788 if (notification == eInputReaderGotToken)
789 {
790 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
791 if (gdb_process->m_waiting_for_attach)
792 gdb_process->m_waiting_for_attach = false;
793 reader->SetIsDone(true);
794 return 1;
795 }
796 return 0;
797}
798
799Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000800ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000801{
802 Error error;
803 // Clear out and clean up from any current state
804 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000805
Chris Lattner24943d22010-06-08 16:52:24 +0000806 if (process_name && process_name[0])
807 {
Greg Claytona2f74232011-02-24 22:24:29 +0000808 // Make sure we aren't already connected?
809 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000810 {
Greg Claytona2f74232011-02-24 22:24:29 +0000811 char host_port[128];
812 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
813 char connect_url[128];
814 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
815
Greg Claytonb72d0f02011-04-12 05:54:46 +0000816 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000817 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000818 {
Greg Claytona2f74232011-02-24 22:24:29 +0000819 const char *error_string = error.AsCString();
820 if (error_string == NULL)
821 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000822
Greg Claytona2f74232011-02-24 22:24:29 +0000823 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000824 }
Greg Claytona2f74232011-02-24 22:24:29 +0000825 else
826 {
827 error = ConnectToDebugserver (connect_url);
828 }
829 }
830
831 if (error.Success())
832 {
833 StreamString packet;
834
835 if (wait_for_launch)
836 packet.PutCString("vAttachWait");
837 else
838 packet.PutCString("vAttachName");
839 packet.PutChar(';');
840 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
841
842 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
843
Chris Lattner24943d22010-06-08 16:52:24 +0000844 }
845 }
Chris Lattner24943d22010-06-08 16:52:24 +0000846 return error;
847}
848
Chris Lattner24943d22010-06-08 16:52:24 +0000849
850void
851ProcessGDBRemote::DidAttach ()
852{
Greg Claytone71e2582011-02-04 01:58:07 +0000853 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000854}
855
856Error
857ProcessGDBRemote::WillResume ()
858{
Greg Claytonc1f45872011-02-12 06:28:37 +0000859 m_continue_c_tids.clear();
860 m_continue_C_tids.clear();
861 m_continue_s_tids.clear();
862 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000863 return Error();
864}
865
866Error
867ProcessGDBRemote::DoResume ()
868{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000869 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000870 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
871 if (log)
872 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000873
874 Listener listener ("gdb-remote.resume-packet-sent");
875 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
876 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000877 StreamString continue_packet;
878 bool continue_packet_error = false;
879 if (m_gdb_comm.HasAnyVContSupport ())
880 {
881 continue_packet.PutCString ("vCont");
882
883 if (!m_continue_c_tids.empty())
884 {
885 if (m_gdb_comm.GetVContSupported ('c'))
886 {
887 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)
888 continue_packet.Printf(";c:%4.4x", *t_pos);
889 }
890 else
891 continue_packet_error = true;
892 }
893
894 if (!continue_packet_error && !m_continue_C_tids.empty())
895 {
896 if (m_gdb_comm.GetVContSupported ('C'))
897 {
898 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)
899 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
900 }
901 else
902 continue_packet_error = true;
903 }
Greg Claytonb749a262010-12-03 06:02:24 +0000904
Greg Claytonc1f45872011-02-12 06:28:37 +0000905 if (!continue_packet_error && !m_continue_s_tids.empty())
906 {
907 if (m_gdb_comm.GetVContSupported ('s'))
908 {
909 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)
910 continue_packet.Printf(";s:%4.4x", *t_pos);
911 }
912 else
913 continue_packet_error = true;
914 }
915
916 if (!continue_packet_error && !m_continue_S_tids.empty())
917 {
918 if (m_gdb_comm.GetVContSupported ('S'))
919 {
920 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)
921 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
922 }
923 else
924 continue_packet_error = true;
925 }
926
927 if (continue_packet_error)
928 continue_packet.GetString().clear();
929 }
930 else
931 continue_packet_error = true;
932
933 if (continue_packet_error)
934 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000935 // Either no vCont support, or we tried to use part of the vCont
936 // packet that wasn't supported by the remote GDB server.
937 // We need to try and make a simple packet that can do our continue
938 const size_t num_threads = GetThreadList().GetSize();
939 const size_t num_continue_c_tids = m_continue_c_tids.size();
940 const size_t num_continue_C_tids = m_continue_C_tids.size();
941 const size_t num_continue_s_tids = m_continue_s_tids.size();
942 const size_t num_continue_S_tids = m_continue_S_tids.size();
943 if (num_continue_c_tids > 0)
944 {
945 if (num_continue_c_tids == num_threads)
946 {
947 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000948 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000949 continue_packet.PutChar ('c');
950 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000951 }
952 else if (num_continue_c_tids == 1 &&
953 num_continue_C_tids == 0 &&
954 num_continue_s_tids == 0 &&
955 num_continue_S_tids == 0 )
956 {
957 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000958 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000959 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000960 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000961 }
962 }
963
Greg Claytonde1dd812011-06-24 03:21:43 +0000964 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000965 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000966 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
967 num_continue_C_tids > 0 &&
968 num_continue_s_tids == 0 &&
969 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000970 {
971 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000972 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +0000973 if (num_continue_C_tids > 1)
974 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000975 // More that one thread with a signal, yet we don't have
976 // vCont support and we are being asked to resume each
977 // thread with a signal, we need to make sure they are
978 // all the same signal, or we can't issue the continue
979 // accurately with the current support...
980 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +0000981 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000982 continue_packet_error = false;
983 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
984 {
985 if (m_continue_C_tids[i].second != continue_signo)
986 continue_packet_error = true;
987 }
Greg Claytonc1f45872011-02-12 06:28:37 +0000988 }
Greg Claytonde1dd812011-06-24 03:21:43 +0000989 if (!continue_packet_error)
990 m_gdb_comm.SetCurrentThreadForRun (-1);
991 }
992 else
993 {
994 // Set the continue thread ID
995 continue_packet_error = false;
996 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +0000997 }
998 if (!continue_packet_error)
999 {
1000 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001001 continue_packet.Printf("C%2.2x", continue_signo);
1002 }
1003 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001004 }
1005
Greg Claytonde1dd812011-06-24 03:21:43 +00001006 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001007 {
1008 if (num_continue_s_tids == num_threads)
1009 {
1010 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001011 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001012 continue_packet.PutChar ('s');
1013 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001014 }
1015 else if (num_continue_c_tids == 0 &&
1016 num_continue_C_tids == 0 &&
1017 num_continue_s_tids == 1 &&
1018 num_continue_S_tids == 0 )
1019 {
1020 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001021 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001022 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001023 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001024 }
1025 }
1026
1027 if (!continue_packet_error && num_continue_S_tids > 0)
1028 {
1029 if (num_continue_S_tids == num_threads)
1030 {
1031 const int step_signo = m_continue_S_tids.front().second;
1032 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001033 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001034 if (num_continue_S_tids > 1)
1035 {
1036 for (size_t i=1; i<num_threads; ++i)
1037 {
1038 if (m_continue_S_tids[i].second != step_signo)
1039 continue_packet_error = true;
1040 }
1041 }
1042 if (!continue_packet_error)
1043 {
1044 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001045 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001046 continue_packet.Printf("S%2.2x", step_signo);
1047 }
1048 }
1049 else if (num_continue_c_tids == 0 &&
1050 num_continue_C_tids == 0 &&
1051 num_continue_s_tids == 0 &&
1052 num_continue_S_tids == 1 )
1053 {
1054 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001055 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001056 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001057 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001058 }
1059 }
1060 }
1061
1062 if (continue_packet_error)
1063 {
1064 error.SetErrorString ("can't make continue packet for this resume");
1065 }
1066 else
1067 {
1068 EventSP event_sp;
1069 TimeValue timeout;
1070 timeout = TimeValue::Now();
1071 timeout.OffsetWithSeconds (5);
1072 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1073
1074 if (listener.WaitForEvent (&timeout, event_sp) == false)
1075 error.SetErrorString("Resume timed out.");
1076 }
Greg Claytonb749a262010-12-03 06:02:24 +00001077 }
1078
Jim Ingham3ae449a2010-11-17 02:32:00 +00001079 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001080}
1081
Chris Lattner24943d22010-06-08 16:52:24 +00001082uint32_t
Greg Clayton37f962e2011-08-22 02:49:39 +00001083ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001084{
1085 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001086 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001087 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001088 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001089 // Update the thread list's stop id immediately so we don't recurse into this function.
Chris Lattner24943d22010-06-08 16:52:24 +00001090
Greg Clayton37f962e2011-08-22 02:49:39 +00001091 std::vector<lldb::tid_t> thread_ids;
1092 bool sequence_mutex_unavailable = false;
1093 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1094 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001095 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001096 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001097 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001098 tid_t tid = thread_ids[i];
1099 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1100 if (!thread_sp)
1101 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1102 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001103 }
Chris Lattner24943d22010-06-08 16:52:24 +00001104 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001105
1106 if (sequence_mutex_unavailable == false)
1107 SetThreadStopInfo (m_last_stop_packet);
1108 return new_thread_list.GetSize(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001109}
1110
1111
1112StateType
1113ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1114{
Greg Clayton261a18b2011-06-02 22:22:38 +00001115 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001116 const char stop_type = stop_packet.GetChar();
1117 switch (stop_type)
1118 {
1119 case 'T':
1120 case 'S':
1121 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001122 if (GetStopID() == 0)
1123 {
1124 // Our first stop, make sure we have a process ID, and also make
1125 // sure we know about our registers
1126 if (GetID() == LLDB_INVALID_PROCESS_ID)
1127 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001128 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001129 if (pid != LLDB_INVALID_PROCESS_ID)
1130 SetID (pid);
1131 }
1132 BuildDynamicRegisterInfo (true);
1133 }
Chris Lattner24943d22010-06-08 16:52:24 +00001134 // Stop with signal and thread info
1135 const uint8_t signo = stop_packet.GetHexU8();
1136 std::string name;
1137 std::string value;
1138 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001139 std::string reason;
1140 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001141 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001142 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001143 uint32_t tid = LLDB_INVALID_THREAD_ID;
1144 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1145 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001146 ThreadSP thread_sp;
1147
Chris Lattner24943d22010-06-08 16:52:24 +00001148 while (stop_packet.GetNameColonValue(name, value))
1149 {
1150 if (name.compare("metype") == 0)
1151 {
1152 // exception type in big endian hex
1153 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1154 }
1155 else if (name.compare("mecount") == 0)
1156 {
1157 // exception count in big endian hex
1158 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1159 }
1160 else if (name.compare("medata") == 0)
1161 {
1162 // exception data in big endian hex
1163 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1164 }
1165 else if (name.compare("thread") == 0)
1166 {
1167 // thread in big endian hex
1168 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001169 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001170 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001171 if (!thread_sp)
1172 {
1173 // Create the thread if we need to
1174 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1175 m_thread_list.AddThread(thread_sp);
1176 }
Chris Lattner24943d22010-06-08 16:52:24 +00001177 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001178 else if (name.compare("hexname") == 0)
1179 {
1180 StringExtractor name_extractor;
1181 // Swap "value" over into "name_extractor"
1182 name_extractor.GetStringRef().swap(value);
1183 // Now convert the HEX bytes into a string value
1184 name_extractor.GetHexByteString (value);
1185 thread_name.swap (value);
1186 }
Chris Lattner24943d22010-06-08 16:52:24 +00001187 else if (name.compare("name") == 0)
1188 {
1189 thread_name.swap (value);
1190 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001191 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001192 {
1193 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1194 }
Greg Clayton65611552011-06-04 01:26:29 +00001195 else if (name.compare("reason") == 0)
1196 {
1197 reason.swap(value);
1198 }
1199 else if (name.compare("description") == 0)
1200 {
1201 StringExtractor desc_extractor;
1202 // Swap "value" over into "name_extractor"
1203 desc_extractor.GetStringRef().swap(value);
1204 // Now convert the HEX bytes into a string value
1205 desc_extractor.GetHexByteString (thread_name);
1206 }
Greg Claytona875b642011-01-09 21:07:35 +00001207 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1208 {
1209 // We have a register number that contains an expedited
1210 // register value. Lets supply this register to our thread
1211 // so it won't have to go and read it.
1212 if (thread_sp)
1213 {
1214 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1215
1216 if (reg != UINT32_MAX)
1217 {
1218 StringExtractor reg_value_extractor;
1219 // Swap "value" over into "reg_value_extractor"
1220 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001221 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1222 {
1223 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1224 name.c_str(),
1225 reg,
1226 reg,
1227 reg_value_extractor.GetStringRef().c_str(),
1228 stop_packet.GetStringRef().c_str());
1229 }
Greg Claytona875b642011-01-09 21:07:35 +00001230 }
1231 }
1232 }
Chris Lattner24943d22010-06-08 16:52:24 +00001233 }
Chris Lattner24943d22010-06-08 16:52:24 +00001234
1235 if (thread_sp)
1236 {
1237 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1238
1239 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001240 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001241 if (exc_type != 0)
1242 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001243 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001244
1245 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1246 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001247 exc_data_size,
1248 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001249 exc_data_size >= 2 ? exc_data[1] : 0,
1250 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001251 }
Greg Clayton65611552011-06-04 01:26:29 +00001252 else
Chris Lattner24943d22010-06-08 16:52:24 +00001253 {
Greg Clayton65611552011-06-04 01:26:29 +00001254 bool handled = false;
1255 if (!reason.empty())
1256 {
1257 if (reason.compare("trace") == 0)
1258 {
1259 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1260 handled = true;
1261 }
1262 else if (reason.compare("breakpoint") == 0)
1263 {
1264 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1265 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1266 if (bp_site_sp)
1267 {
1268 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1269 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1270 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1271 if (bp_site_sp->ValidForThisThread (gdb_thread))
1272 {
1273 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1274 handled = true;
1275 }
1276 }
1277
1278 if (!handled)
1279 {
1280 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1281 }
1282 }
1283 else if (reason.compare("trap") == 0)
1284 {
1285 // Let the trap just use the standard signal stop reason below...
1286 }
1287 else if (reason.compare("watchpoint") == 0)
1288 {
1289 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1290 // TODO: locate the watchpoint somehow...
1291 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1292 handled = true;
1293 }
1294 else if (reason.compare("exception") == 0)
1295 {
1296 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1297 handled = true;
1298 }
1299 }
1300
1301 if (signo)
1302 {
1303 if (signo == SIGTRAP)
1304 {
1305 // Currently we are going to assume SIGTRAP means we are either
1306 // hitting a breakpoint or hardware single stepping.
1307 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1308 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1309 if (bp_site_sp)
1310 {
1311 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1312 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1313 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1314 if (bp_site_sp->ValidForThisThread (gdb_thread))
1315 {
1316 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1317 handled = true;
1318 }
1319 }
1320 if (!handled)
1321 {
1322 // TODO: check for breakpoint or trap opcode in case there is a hard
1323 // coded software trap
1324 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1325 handled = true;
1326 }
1327 }
1328 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001329 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001330 }
1331 else
1332 {
Greg Clayton643ee732010-08-04 01:40:35 +00001333 StopInfoSP invalid_stop_info_sp;
1334 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001335 }
Greg Clayton65611552011-06-04 01:26:29 +00001336
1337 if (!description.empty())
1338 {
1339 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1340 if (stop_info_sp)
1341 {
1342 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001343 }
Greg Clayton65611552011-06-04 01:26:29 +00001344 else
1345 {
1346 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1347 }
1348 }
1349 }
Chris Lattner24943d22010-06-08 16:52:24 +00001350 }
1351 return eStateStopped;
1352 }
1353 break;
1354
1355 case 'W':
1356 // process exited
1357 return eStateExited;
1358
1359 default:
1360 break;
1361 }
1362 return eStateInvalid;
1363}
1364
1365void
1366ProcessGDBRemote::RefreshStateAfterStop ()
1367{
Chris Lattner24943d22010-06-08 16:52:24 +00001368 // Let all threads recover from stopping and do any clean up based
1369 // on the previous thread state (if any).
1370 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001371 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001372}
1373
1374Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001375ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001376{
1377 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001378
Greg Claytona4881d02011-01-22 07:12:45 +00001379 bool timed_out = false;
1380 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001381
1382 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001383 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001384 // We are being asked to halt during an attach. We need to just close
1385 // our file handle and debugserver will go away, and we can be done...
1386 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001387 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001388 else
1389 {
1390 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1391 {
1392 if (timed_out)
1393 error.SetErrorString("timed out sending interrupt packet");
1394 else
1395 error.SetErrorString("unknown error sending interrupt packet");
1396 }
1397 }
Chris Lattner24943d22010-06-08 16:52:24 +00001398 return error;
1399}
1400
1401Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001402ProcessGDBRemote::InterruptIfRunning
1403(
1404 bool discard_thread_plans,
1405 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001406 EventSP &stop_event_sp
1407)
Chris Lattner24943d22010-06-08 16:52:24 +00001408{
1409 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001410
Greg Clayton2860ba92011-01-23 19:58:49 +00001411 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1412
Greg Clayton68ca8232011-01-25 02:58:48 +00001413 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001414 const bool is_running = m_gdb_comm.IsRunning();
1415 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001416 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001417 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001418 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001419 is_running);
1420
Greg Clayton2860ba92011-01-23 19:58:49 +00001421 if (discard_thread_plans)
1422 {
1423 if (log)
1424 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1425 m_thread_list.DiscardThreadPlans();
1426 }
1427 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001428 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001429 if (catch_stop_event)
1430 {
1431 if (log)
1432 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1433 PausePrivateStateThread();
1434 paused_private_state_thread = true;
1435 }
1436
Greg Clayton4fb400f2010-09-27 21:07:38 +00001437 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001438 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001439 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001440
Greg Clayton72e1c782011-01-22 23:43:18 +00001441 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001442 {
1443 if (timed_out)
1444 error.SetErrorString("timed out sending interrupt packet");
1445 else
1446 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001447 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001448 ResumePrivateStateThread();
1449 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001450 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001451
Greg Clayton72e1c782011-01-22 23:43:18 +00001452 if (catch_stop_event)
1453 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001454 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001455 TimeValue timeout_time;
1456 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001457 timeout_time.OffsetWithSeconds(5);
1458 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001459
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001460 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001461 if (log)
1462 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001463
Greg Clayton2860ba92011-01-23 19:58:49 +00001464 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001465 error.SetErrorString("unable to verify target stopped");
1466 }
1467
Greg Clayton68ca8232011-01-25 02:58:48 +00001468 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001469 {
1470 if (log)
1471 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001472 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001473 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001474 }
Chris Lattner24943d22010-06-08 16:52:24 +00001475 return error;
1476}
1477
Greg Clayton4fb400f2010-09-27 21:07:38 +00001478Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001479ProcessGDBRemote::WillDetach ()
1480{
Greg Clayton2860ba92011-01-23 19:58:49 +00001481 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1482 if (log)
1483 log->Printf ("ProcessGDBRemote::WillDetach()");
1484
Greg Clayton72e1c782011-01-22 23:43:18 +00001485 bool discard_thread_plans = true;
1486 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001487 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001488 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001489}
1490
1491Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001492ProcessGDBRemote::DoDetach()
1493{
1494 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001495 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001496 if (log)
1497 log->Printf ("ProcessGDBRemote::DoDetach()");
1498
1499 DisableAllBreakpointSites ();
1500
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001501 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001502
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001503 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1504 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001505 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001506 if (response_size)
1507 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1508 else
1509 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001510 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001511 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001512 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001513
Greg Clayton4fb400f2010-09-27 21:07:38 +00001514 m_gdb_comm.StopReadThread();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001515 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001516
1517 SetPrivateState (eStateDetached);
1518 ResumePrivateStateThread();
1519
1520 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001521 return error;
1522}
Chris Lattner24943d22010-06-08 16:52:24 +00001523
1524Error
1525ProcessGDBRemote::DoDestroy ()
1526{
1527 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001528 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001529 if (log)
1530 log->Printf ("ProcessGDBRemote::DoDestroy()");
1531
1532 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001533 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001534 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001535 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton27a8dd72011-01-25 04:57:42 +00001536 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001537 // We are being asked to halt during an attach. We need to just close
1538 // our file handle and debugserver will go away, and we can be done...
1539 m_gdb_comm.Disconnect();
Greg Clayton27a8dd72011-01-25 04:57:42 +00001540 }
1541 else
Greg Clayton72e1c782011-01-22 23:43:18 +00001542 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001543
1544 StringExtractorGDBRemote response;
1545 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001546 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001547 {
1548 char packet_cmd = response.GetChar(0);
1549
1550 if (packet_cmd == 'W' || packet_cmd == 'X')
1551 {
1552 m_last_stop_packet = response;
1553 SetExitStatus(response.GetHexU8(), NULL);
1554 }
1555 }
1556 else
1557 {
1558 SetExitStatus(SIGABRT, NULL);
1559 //error.SetErrorString("kill packet failed");
1560 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001561 }
1562 }
Chris Lattner24943d22010-06-08 16:52:24 +00001563 StopAsyncThread ();
1564 m_gdb_comm.StopReadThread();
1565 KillDebugserverProcess ();
Johnny Chenc5b15db2010-09-03 22:35:47 +00001566 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00001567 return error;
1568}
1569
Chris Lattner24943d22010-06-08 16:52:24 +00001570//------------------------------------------------------------------
1571// Process Queries
1572//------------------------------------------------------------------
1573
1574bool
1575ProcessGDBRemote::IsAlive ()
1576{
Greg Clayton58e844b2010-12-08 05:08:21 +00001577 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001578}
1579
1580addr_t
1581ProcessGDBRemote::GetImageInfoAddress()
1582{
1583 if (!m_gdb_comm.IsRunning())
1584 {
1585 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001586 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001587 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001588 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001589 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1590 }
1591 }
1592 return LLDB_INVALID_ADDRESS;
1593}
1594
Chris Lattner24943d22010-06-08 16:52:24 +00001595//------------------------------------------------------------------
1596// Process Memory
1597//------------------------------------------------------------------
1598size_t
1599ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1600{
1601 if (size > m_max_memory_size)
1602 {
1603 // Keep memory read sizes down to a sane limit. This function will be
1604 // called multiple times in order to complete the task by
1605 // lldb_private::Process so it is ok to do this.
1606 size = m_max_memory_size;
1607 }
1608
1609 char packet[64];
1610 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1611 assert (packet_len + 1 < sizeof(packet));
1612 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001613 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001614 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001615 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001616 {
1617 error.Clear();
1618 return response.GetHexBytes(buf, size, '\xdd');
1619 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001620 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001621 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001622 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001623 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1624 else
1625 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1626 }
1627 else
1628 {
1629 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1630 }
1631 return 0;
1632}
1633
1634size_t
1635ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1636{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001637 if (size > m_max_memory_size)
1638 {
1639 // Keep memory read sizes down to a sane limit. This function will be
1640 // called multiple times in order to complete the task by
1641 // lldb_private::Process so it is ok to do this.
1642 size = m_max_memory_size;
1643 }
1644
Chris Lattner24943d22010-06-08 16:52:24 +00001645 StreamString packet;
1646 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001647 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001648 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001649 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001650 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001651 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001652 {
1653 error.Clear();
1654 return size;
1655 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001656 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001657 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001658 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001659 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1660 else
1661 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1662 }
1663 else
1664 {
1665 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1666 }
1667 return 0;
1668}
1669
1670lldb::addr_t
1671ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1672{
Greg Clayton989816b2011-05-14 01:50:35 +00001673 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1674
Greg Clayton2f085c62011-05-15 01:25:55 +00001675 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001676 switch (supported)
1677 {
1678 case eLazyBoolCalculate:
1679 case eLazyBoolYes:
1680 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1681 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1682 return allocated_addr;
1683
1684 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001685 // Call mmap() to create memory in the inferior..
1686 unsigned prot = 0;
1687 if (permissions & lldb::ePermissionsReadable)
1688 prot |= eMmapProtRead;
1689 if (permissions & lldb::ePermissionsWritable)
1690 prot |= eMmapProtWrite;
1691 if (permissions & lldb::ePermissionsExecutable)
1692 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001693
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001694 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1695 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1696 m_addr_to_mmap_size[allocated_addr] = size;
1697 else
1698 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001699 break;
1700 }
1701
Chris Lattner24943d22010-06-08 16:52:24 +00001702 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001703 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001704 else
1705 error.Clear();
1706 return allocated_addr;
1707}
1708
1709Error
1710ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1711{
1712 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001713 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1714
1715 switch (supported)
1716 {
1717 case eLazyBoolCalculate:
1718 // We should never be deallocating memory without allocating memory
1719 // first so we should never get eLazyBoolCalculate
1720 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1721 break;
1722
1723 case eLazyBoolYes:
1724 if (!m_gdb_comm.DeallocateMemory (addr))
1725 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1726 break;
1727
1728 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001729 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001730 {
1731 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001732 if (pos != m_addr_to_mmap_size.end() &&
1733 InferiorCallMunmap(this, addr, pos->second))
1734 m_addr_to_mmap_size.erase (pos);
1735 else
1736 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001737 }
1738 break;
1739 }
1740
Chris Lattner24943d22010-06-08 16:52:24 +00001741 return error;
1742}
1743
1744
1745//------------------------------------------------------------------
1746// Process STDIO
1747//------------------------------------------------------------------
1748
1749size_t
1750ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1751{
1752 Mutex::Locker locker(m_stdio_mutex);
1753 size_t bytes_available = m_stdout_data.size();
1754 if (bytes_available > 0)
1755 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001756 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1757 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001758 log->Printf ("ProcessGDBRemote::%s (&%p[%lu]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001759 if (bytes_available > buf_size)
1760 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001761 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001762 m_stdout_data.erase(0, buf_size);
1763 bytes_available = buf_size;
1764 }
1765 else
1766 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001767 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001768 m_stdout_data.clear();
1769
1770 //ResetEventBits(eBroadcastBitSTDOUT);
1771 }
1772 }
1773 return bytes_available;
1774}
1775
1776size_t
1777ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1778{
1779 // Can we get STDERR through the remote protocol?
1780 return 0;
1781}
1782
1783size_t
1784ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1785{
1786 if (m_stdio_communication.IsConnected())
1787 {
1788 ConnectionStatus status;
1789 m_stdio_communication.Write(src, src_len, status, NULL);
1790 }
1791 return 0;
1792}
1793
1794Error
1795ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1796{
1797 Error error;
1798 assert (bp_site != NULL);
1799
Greg Claytone005f2c2010-11-06 01:53:30 +00001800 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001801 user_id_t site_id = bp_site->GetID();
1802 const addr_t addr = bp_site->GetLoadAddress();
1803 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001804 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001805
1806 if (bp_site->IsEnabled())
1807 {
1808 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001809 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001810 return error;
1811 }
1812 else
1813 {
1814 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1815
1816 if (bp_site->HardwarePreferred())
1817 {
1818 // Try and set hardware breakpoint, and if that fails, fall through
1819 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001820 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001821 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001822 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001823 {
1824 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001825 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001826 return error;
1827 }
Chris Lattner24943d22010-06-08 16:52:24 +00001828 }
1829 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001830
1831 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001832 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001833 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1834 {
1835 bp_site->SetEnabled(true);
1836 bp_site->SetType (BreakpointSite::eExternal);
1837 return error;
1838 }
Chris Lattner24943d22010-06-08 16:52:24 +00001839 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001840
1841 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001842 }
1843
1844 if (log)
1845 {
1846 const char *err_string = error.AsCString();
1847 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1848 bp_site->GetLoadAddress(),
1849 err_string ? err_string : "NULL");
1850 }
1851 // We shouldn't reach here on a successful breakpoint enable...
1852 if (error.Success())
1853 error.SetErrorToGenericError();
1854 return error;
1855}
1856
1857Error
1858ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1859{
1860 Error error;
1861 assert (bp_site != NULL);
1862 addr_t addr = bp_site->GetLoadAddress();
1863 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001864 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001865 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001866 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001867
1868 if (bp_site->IsEnabled())
1869 {
1870 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1871
Greg Claytonb72d0f02011-04-12 05:54:46 +00001872 BreakpointSite::Type bp_type = bp_site->GetType();
1873 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001874 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001875 case BreakpointSite::eSoftware:
1876 error = DisableSoftwareBreakpoint (bp_site);
1877 break;
1878
1879 case BreakpointSite::eHardware:
1880 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1881 error.SetErrorToGenericError();
1882 break;
1883
1884 case BreakpointSite::eExternal:
1885 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1886 error.SetErrorToGenericError();
1887 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001888 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001889 if (error.Success())
1890 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001891 }
1892 else
1893 {
1894 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001895 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001896 return error;
1897 }
1898
1899 if (error.Success())
1900 error.SetErrorToGenericError();
1901 return error;
1902}
1903
Johnny Chen21900fb2011-09-06 22:38:36 +00001904// Pre-requisite: wp != NULL.
1905static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00001906GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00001907{
1908 assert(wp);
1909 bool watch_read = wp->WatchpointRead();
1910 bool watch_write = wp->WatchpointWrite();
1911
1912 // watch_read and watch_write cannot both be false.
1913 assert(watch_read || watch_write);
1914 if (watch_read && watch_write)
1915 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001916 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00001917 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00001918 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00001919 return eWatchpointWrite;
1920}
1921
Chris Lattner24943d22010-06-08 16:52:24 +00001922Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001923ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001924{
1925 Error error;
1926 if (wp)
1927 {
1928 user_id_t watchID = wp->GetID();
1929 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001930 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001931 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001932 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00001933 if (wp->IsEnabled())
1934 {
1935 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001936 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001937 return error;
1938 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001939
1940 GDBStoppointType type = GetGDBStoppointType(wp);
1941 // Pass down an appropriate z/Z packet...
1942 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00001943 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001944 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
1945 {
1946 wp->SetEnabled(true);
1947 return error;
1948 }
1949 else
1950 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001951 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001952 else
1953 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00001954 }
1955 else
1956 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001957 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001958 }
1959 if (error.Success())
1960 error.SetErrorToGenericError();
1961 return error;
1962}
1963
1964Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001965ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001966{
1967 Error error;
1968 if (wp)
1969 {
1970 user_id_t watchID = wp->GetID();
1971
Greg Claytone005f2c2010-11-06 01:53:30 +00001972 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001973
1974 addr_t addr = wp->GetLoadAddress();
1975 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001976 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001977
Johnny Chen21900fb2011-09-06 22:38:36 +00001978 if (!wp->IsEnabled())
1979 {
1980 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001981 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00001982 return error;
1983 }
1984
Chris Lattner24943d22010-06-08 16:52:24 +00001985 if (wp->IsHardware())
1986 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001987 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00001988 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00001989 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
1990 {
1991 wp->SetEnabled(false);
1992 return error;
1993 }
1994 else
1995 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001996 }
1997 // TODO: clear software watchpoints if we implement them
1998 }
1999 else
2000 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002001 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002002 }
2003 if (error.Success())
2004 error.SetErrorToGenericError();
2005 return error;
2006}
2007
2008void
2009ProcessGDBRemote::Clear()
2010{
2011 m_flags = 0;
2012 m_thread_list.Clear();
2013 {
2014 Mutex::Locker locker(m_stdio_mutex);
2015 m_stdout_data.clear();
2016 }
Chris Lattner24943d22010-06-08 16:52:24 +00002017}
2018
2019Error
2020ProcessGDBRemote::DoSignal (int signo)
2021{
2022 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002023 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002024 if (log)
2025 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2026
2027 if (!m_gdb_comm.SendAsyncSignal (signo))
2028 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2029 return error;
2030}
2031
Chris Lattner24943d22010-06-08 16:52:24 +00002032Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002033ProcessGDBRemote::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 +00002034{
2035 Error error;
2036 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2037 {
2038 // If we locate debugserver, keep that located version around
2039 static FileSpec g_debugserver_file_spec;
2040
Greg Claytonb72d0f02011-04-12 05:54:46 +00002041 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002042 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002043 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002044
2045 // Always check to see if we have an environment override for the path
2046 // to the debugserver to use and use it if we do.
2047 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2048 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002049 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002050 else
2051 debugserver_file_spec = g_debugserver_file_spec;
2052 bool debugserver_exists = debugserver_file_spec.Exists();
2053 if (!debugserver_exists)
2054 {
2055 // The debugserver binary is in the LLDB.framework/Resources
2056 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002057 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002058 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002059 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002060 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002061 if (debugserver_exists)
2062 {
2063 g_debugserver_file_spec = debugserver_file_spec;
2064 }
2065 else
2066 {
2067 g_debugserver_file_spec.Clear();
2068 debugserver_file_spec.Clear();
2069 }
Chris Lattner24943d22010-06-08 16:52:24 +00002070 }
2071 }
2072
2073 if (debugserver_exists)
2074 {
2075 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2076
2077 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002078
Greg Claytone005f2c2010-11-06 01:53:30 +00002079 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002080
Greg Claytonb72d0f02011-04-12 05:54:46 +00002081 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002082 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002083
Chris Lattner24943d22010-06-08 16:52:24 +00002084 // Start args with "debugserver /file/path -r --"
2085 debugserver_args.AppendArgument(debugserver_path);
2086 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002087 // use native registers, not the GDB registers
2088 debugserver_args.AppendArgument("--native-regs");
2089 // make debugserver run in its own session so signals generated by
2090 // special terminal key sequences (^C) don't affect debugserver
2091 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002092
Chris Lattner24943d22010-06-08 16:52:24 +00002093 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2094 if (env_debugserver_log_file)
2095 {
2096 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2097 debugserver_args.AppendArgument(arg_cstr);
2098 }
2099
2100 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2101 if (env_debugserver_log_flags)
2102 {
2103 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2104 debugserver_args.AppendArgument(arg_cstr);
2105 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002106// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002107// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002108
Greg Claytonb72d0f02011-04-12 05:54:46 +00002109 // We currently send down all arguments, attach pids, or attach
2110 // process names in dedicated GDB server packets, so we don't need
2111 // to pass them as arguments. This is currently because of all the
2112 // things we need to setup prior to launching: the environment,
2113 // current working dir, file actions, etc.
2114#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002115 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002116 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002117 {
Greg Claytona2f74232011-02-24 22:24:29 +00002118 // Terminate the debugserver args so we can now append the inferior args
2119 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002120
Greg Claytona2f74232011-02-24 22:24:29 +00002121 for (int i = 0; inferior_argv[i] != NULL; ++i)
2122 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002123 }
2124 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2125 {
2126 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2127 debugserver_args.AppendArgument (arg_cstr);
2128 }
2129 else if (attach_name && attach_name[0])
2130 {
2131 if (wait_for_launch)
2132 debugserver_args.AppendArgument ("--waitfor");
2133 else
2134 debugserver_args.AppendArgument ("--attach");
2135 debugserver_args.AppendArgument (attach_name);
2136 }
Chris Lattner24943d22010-06-08 16:52:24 +00002137#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002138
2139 ProcessLaunchInfo::FileAction file_action;
2140
2141 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2142 // to "/dev/null" if we run into any problems.
2143 file_action.Close (STDIN_FILENO);
2144 launch_info.AppendFileAction (file_action);
2145 file_action.Close (STDOUT_FILENO);
2146 launch_info.AppendFileAction (file_action);
2147 file_action.Close (STDERR_FILENO);
2148 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002149
2150 if (log)
2151 {
2152 StreamString strm;
2153 debugserver_args.Dump (&strm);
2154 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2155 }
2156
Greg Claytonb72d0f02011-04-12 05:54:46 +00002157 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002158
Greg Claytonb72d0f02011-04-12 05:54:46 +00002159 if (error.Success ())
2160 m_debugserver_pid = launch_info.GetProcessID();
2161 else
Chris Lattner24943d22010-06-08 16:52:24 +00002162 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2163
2164 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002165 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002166 }
2167 else
2168 {
Greg Clayton9c236732011-10-26 00:56:27 +00002169 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002170 }
2171
2172 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2173 StartAsyncThread ();
2174 }
2175 return error;
2176}
2177
2178bool
2179ProcessGDBRemote::MonitorDebugserverProcess
2180(
2181 void *callback_baton,
2182 lldb::pid_t debugserver_pid,
2183 int signo, // Zero for no signal
2184 int exit_status // Exit value of process if signal is zero
2185)
2186{
2187 // We pass in the ProcessGDBRemote inferior process it and name it
2188 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2189 // pointer value itself, thus we need the double cast...
2190
2191 // "debugserver_pid" argument passed in is the process ID for
2192 // debugserver that we are tracking...
2193
Greg Clayton75ccf502010-08-21 02:22:51 +00002194 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002195
2196 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2197 if (log)
2198 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2199
Greg Clayton75ccf502010-08-21 02:22:51 +00002200 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002201 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002202 // Sleep for a half a second to make sure our inferior process has
2203 // time to set its exit status before we set it incorrectly when
2204 // both the debugserver and the inferior process shut down.
2205 usleep (500000);
2206 // If our process hasn't yet exited, debugserver might have died.
2207 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002208 const StateType state = process->GetState();
2209
2210 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2211 state != eStateInvalid &&
2212 state != eStateUnloaded &&
2213 state != eStateExited &&
2214 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002215 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002216 char error_str[1024];
2217 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002218 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002219 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2220 if (signal_cstr)
2221 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002222 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002223 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002224 }
2225 else
2226 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002227 ::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 +00002228 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002229
2230 process->SetExitStatus (-1, error_str);
2231 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002232 // Debugserver has exited we need to let our ProcessGDBRemote
2233 // know that it no longer has a debugserver instance
2234 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2235 // We are returning true to this function below, so we can
2236 // forget about the monitor handle.
2237 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002238 }
2239 return true;
2240}
2241
2242void
2243ProcessGDBRemote::KillDebugserverProcess ()
2244{
2245 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2246 {
2247 ::kill (m_debugserver_pid, SIGINT);
2248 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2249 }
2250}
2251
2252void
2253ProcessGDBRemote::Initialize()
2254{
2255 static bool g_initialized = false;
2256
2257 if (g_initialized == false)
2258 {
2259 g_initialized = true;
2260 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2261 GetPluginDescriptionStatic(),
2262 CreateInstance);
2263
2264 Log::Callbacks log_callbacks = {
2265 ProcessGDBRemoteLog::DisableLog,
2266 ProcessGDBRemoteLog::EnableLog,
2267 ProcessGDBRemoteLog::ListLogCategories
2268 };
2269
2270 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2271 }
2272}
2273
2274bool
Chris Lattner24943d22010-06-08 16:52:24 +00002275ProcessGDBRemote::StartAsyncThread ()
2276{
Greg Claytone005f2c2010-11-06 01:53:30 +00002277 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002278
2279 if (log)
2280 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2281
2282 // Create a thread that watches our internal state and controls which
2283 // events make it to clients (into the DCProcess event queue).
2284 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002285 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002286}
2287
2288void
2289ProcessGDBRemote::StopAsyncThread ()
2290{
Greg Claytone005f2c2010-11-06 01:53:30 +00002291 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002292
2293 if (log)
2294 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2295
2296 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2297
2298 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002299 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002300 {
2301 Host::ThreadJoin (m_async_thread, NULL, NULL);
2302 }
2303}
2304
2305
2306void *
2307ProcessGDBRemote::AsyncThread (void *arg)
2308{
2309 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2310
Greg Claytone005f2c2010-11-06 01:53:30 +00002311 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002312 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002313 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002314
2315 Listener listener ("ProcessGDBRemote::AsyncThread");
2316 EventSP event_sp;
2317 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2318 eBroadcastBitAsyncThreadShouldExit;
2319
2320 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2321 {
Greg Claytona2f74232011-02-24 22:24:29 +00002322 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2323
Chris Lattner24943d22010-06-08 16:52:24 +00002324 bool done = false;
2325 while (!done)
2326 {
2327 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002328 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002329 if (listener.WaitForEvent (NULL, event_sp))
2330 {
2331 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002332 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002333 {
Greg Claytona2f74232011-02-24 22:24:29 +00002334 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002335 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002336
Greg Claytona2f74232011-02-24 22:24:29 +00002337 switch (event_type)
2338 {
2339 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002340 {
Greg Claytona2f74232011-02-24 22:24:29 +00002341 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002342
Greg Claytona2f74232011-02-24 22:24:29 +00002343 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002344 {
Greg Claytona2f74232011-02-24 22:24:29 +00002345 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2346 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2347 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002348 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002349
Greg Claytona2f74232011-02-24 22:24:29 +00002350 if (::strstr (continue_cstr, "vAttach") == NULL)
2351 process->SetPrivateState(eStateRunning);
2352 StringExtractorGDBRemote response;
2353 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002354
Greg Claytona2f74232011-02-24 22:24:29 +00002355 switch (stop_state)
2356 {
2357 case eStateStopped:
2358 case eStateCrashed:
2359 case eStateSuspended:
2360 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002361 process->SetPrivateState (stop_state);
2362 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002363
Greg Claytona2f74232011-02-24 22:24:29 +00002364 case eStateExited:
2365 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002366 response.SetFilePos(1);
2367 process->SetExitStatus(response.GetHexU8(), NULL);
2368 done = true;
2369 break;
2370
2371 case eStateInvalid:
2372 process->SetExitStatus(-1, "lost connection");
2373 break;
2374
2375 default:
2376 process->SetPrivateState (stop_state);
2377 break;
2378 }
Chris Lattner24943d22010-06-08 16:52:24 +00002379 }
2380 }
Greg Claytona2f74232011-02-24 22:24:29 +00002381 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002382
Greg Claytona2f74232011-02-24 22:24:29 +00002383 case eBroadcastBitAsyncThreadShouldExit:
2384 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002385 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002386 done = true;
2387 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002388
Greg Claytona2f74232011-02-24 22:24:29 +00002389 default:
2390 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002391 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Claytona2f74232011-02-24 22:24:29 +00002392 done = true;
2393 break;
2394 }
2395 }
2396 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2397 {
2398 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2399 {
2400 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002401 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002402 }
Chris Lattner24943d22010-06-08 16:52:24 +00002403 }
2404 }
2405 else
2406 {
2407 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002408 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002409 done = true;
2410 }
2411 }
2412 }
2413
2414 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002415 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002416
2417 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2418 return NULL;
2419}
2420
Chris Lattner24943d22010-06-08 16:52:24 +00002421const char *
2422ProcessGDBRemote::GetDispatchQueueNameForThread
2423(
2424 addr_t thread_dispatch_qaddr,
2425 std::string &dispatch_queue_name
2426)
2427{
2428 dispatch_queue_name.clear();
2429 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2430 {
2431 // Cache the dispatch_queue_offsets_addr value so we don't always have
2432 // to look it up
2433 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2434 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002435 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2436 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002437 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002438 if (module_sp)
2439 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2440
2441 if (dispatch_queue_offsets_symbol == NULL)
2442 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002443 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002444 if (module_sp)
2445 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2446 }
Chris Lattner24943d22010-06-08 16:52:24 +00002447 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002448 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002449
2450 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2451 return NULL;
2452 }
2453
2454 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002455 DataExtractor data (memory_buffer,
2456 sizeof(memory_buffer),
2457 m_target.GetArchitecture().GetByteOrder(),
2458 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002459
2460 // Excerpt from src/queue_private.h
2461 struct dispatch_queue_offsets_s
2462 {
2463 uint16_t dqo_version;
2464 uint16_t dqo_label;
2465 uint16_t dqo_label_size;
2466 } dispatch_queue_offsets;
2467
2468
2469 Error error;
2470 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2471 {
2472 uint32_t data_offset = 0;
2473 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2474 {
2475 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2476 {
2477 data_offset = 0;
2478 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2479 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2480 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2481 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2482 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2483 dispatch_queue_name.erase (bytes_read);
2484 }
2485 }
2486 }
2487 }
2488 if (dispatch_queue_name.empty())
2489 return NULL;
2490 return dispatch_queue_name.c_str();
2491}
2492
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002493//uint32_t
2494//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2495//{
2496// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2497// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2498// if (m_local_debugserver)
2499// {
2500// return Host::ListProcessesMatchingName (name, matches, pids);
2501// }
2502// else
2503// {
2504// // FIXME: Implement talking to the remote debugserver.
2505// return 0;
2506// }
2507//
2508//}
2509//
Jim Ingham55e01d82011-01-22 01:33:44 +00002510bool
2511ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2512 lldb_private::StoppointCallbackContext *context,
2513 lldb::user_id_t break_id,
2514 lldb::user_id_t break_loc_id)
2515{
2516 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2517 // run so I can stop it if that's what I want to do.
2518 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2519 if (log)
2520 log->Printf("Hit New Thread Notification breakpoint.");
2521 return false;
2522}
2523
2524
2525bool
2526ProcessGDBRemote::StartNoticingNewThreads()
2527{
2528 static const char *bp_names[] =
2529 {
2530 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002531 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002532 "_pthread_start",
2533 NULL
2534 };
2535
2536 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2537 size_t num_bps = m_thread_observation_bps.size();
2538 if (num_bps != 0)
2539 {
2540 for (int i = 0; i < num_bps; i++)
2541 {
2542 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2543 if (break_sp)
2544 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002545 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002546 log->Printf("Enabled noticing new thread breakpoint.");
2547 break_sp->SetEnabled(true);
2548 }
2549 }
2550 }
2551 else
2552 {
2553 for (int i = 0; bp_names[i] != NULL; i++)
2554 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002555 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002556 if (breakpoint)
2557 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002558 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002559 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2560 m_thread_observation_bps.push_back(breakpoint->GetID());
2561 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2562 }
2563 else
2564 {
2565 if (log)
2566 log->Printf("Failed to create new thread notification breakpoint.");
2567 return false;
2568 }
2569 }
2570 }
2571
2572 return true;
2573}
2574
2575bool
2576ProcessGDBRemote::StopNoticingNewThreads()
2577{
Jim Inghamff276fe2011-02-08 05:19:01 +00002578 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002579 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002580 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002581 size_t num_bps = m_thread_observation_bps.size();
2582 if (num_bps != 0)
2583 {
2584 for (int i = 0; i < num_bps; i++)
2585 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002586
2587 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2588 if (break_sp)
2589 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002590 break_sp->SetEnabled(false);
2591 }
2592 }
2593 }
2594 return true;
2595}
2596
2597