blob: dbe81aea2ffdbf3a692b36c4e84b9d97c33cae4b [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
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000440ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000441{
Greg Clayton4b407112010-09-30 21:49:03 +0000442 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000443
444 uint32_t launch_flags = launch_info.GetFlags().Get();
445 const char *stdin_path = NULL;
446 const char *stdout_path = NULL;
447 const char *stderr_path = NULL;
448 const char *working_dir = launch_info.GetWorkingDirectory();
449
450 const ProcessLaunchInfo::FileAction *file_action;
451 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
452 if (file_action)
453 {
454 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
455 stdin_path = file_action->GetPath();
456 }
457 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
458 if (file_action)
459 {
460 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
461 stdout_path = file_action->GetPath();
462 }
463 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
464 if (file_action)
465 {
466 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
467 stderr_path = file_action->GetPath();
468 }
469
Chris Lattner24943d22010-06-08 16:52:24 +0000470 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
471 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
472 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000473 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000474
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000475 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000476 if (object_file)
477 {
Chris Lattner24943d22010-06-08 16:52:24 +0000478 char host_port[128];
479 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000480 char connect_url[128];
481 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000482
Greg Claytona2f74232011-02-24 22:24:29 +0000483 // Make sure we aren't already connected?
484 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000485 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000486 error = StartDebugserverProcess (host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000487 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000488 {
Johnny Chenc143d622011-08-09 18:56:45 +0000489 if (log)
490 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000491 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000492 }
Chris Lattner24943d22010-06-08 16:52:24 +0000493
Greg Claytone71e2582011-02-04 01:58:07 +0000494 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000495 }
496
497 if (error.Success())
498 {
499 lldb_utility::PseudoTerminal pty;
500 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000501
502 // If the debugserver is local and we aren't disabling STDIO, lets use
503 // a pseudo terminal to instead of relying on the 'O' packets for stdio
504 // since 'O' packets can really slow down debugging if the inferior
505 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000506 PlatformSP platform_sp (m_target.GetPlatform());
507 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000508 {
509 const char *slave_name = NULL;
510 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000511 {
Greg Claytona2f74232011-02-24 22:24:29 +0000512 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
513 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000514 }
Greg Claytona2f74232011-02-24 22:24:29 +0000515 if (stdin_path == NULL)
516 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000517
Greg Claytona2f74232011-02-24 22:24:29 +0000518 if (stdout_path == NULL)
519 stdout_path = slave_name;
520
521 if (stderr_path == NULL)
522 stderr_path = slave_name;
523 }
524
Greg Claytonafb81862011-03-02 21:34:46 +0000525 // Set STDIN to /dev/null if we want STDIO disabled or if either
526 // STDOUT or STDERR have been set to something and STDIN hasn't
527 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000528 stdin_path = "/dev/null";
529
Greg Claytonafb81862011-03-02 21:34:46 +0000530 // Set STDOUT to /dev/null if we want STDIO disabled or if either
531 // STDIN or STDERR have been set to something and STDOUT hasn't
532 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000533 stdout_path = "/dev/null";
534
Greg Claytonafb81862011-03-02 21:34:46 +0000535 // Set STDERR to /dev/null if we want STDIO disabled or if either
536 // STDIN or STDOUT have been set to something and STDERR hasn't
537 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000538 stderr_path = "/dev/null";
539
540 if (stdin_path)
541 m_gdb_comm.SetSTDIN (stdin_path);
542 if (stdout_path)
543 m_gdb_comm.SetSTDOUT (stdout_path);
544 if (stderr_path)
545 m_gdb_comm.SetSTDERR (stderr_path);
546
547 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
548
Greg Claytona4582402011-05-08 04:53:50 +0000549 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000550
551 if (working_dir && working_dir[0])
552 {
553 m_gdb_comm.SetWorkingDir (working_dir);
554 }
555
556 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000557 const Args &environment = launch_info.GetEnvironmentEntries();
558 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000559 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000560 size_t num_environment_entries = environment.GetArgumentCount();
561 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000562 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000563 const char *env_entry = environment.GetArgumentAtIndex(i);
564 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000565 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000566 }
Greg Claytona2f74232011-02-24 22:24:29 +0000567 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000568
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000569 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000570 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000571 if (arg_packet_err == 0)
572 {
573 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000574 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000575 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000576 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000577 }
578 else
579 {
Greg Claytona2f74232011-02-24 22:24:29 +0000580 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000581 }
Greg Claytona2f74232011-02-24 22:24:29 +0000582 }
583 else
584 {
Greg Clayton9c236732011-10-26 00:56:27 +0000585 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000586 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000587
588 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000589
Greg Claytona2f74232011-02-24 22:24:29 +0000590 if (GetID() == LLDB_INVALID_PROCESS_ID)
591 {
Johnny Chenc143d622011-08-09 18:56:45 +0000592 if (log)
593 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000594 KillDebugserverProcess ();
595 return error;
596 }
597
Greg Clayton261a18b2011-06-02 22:22:38 +0000598 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000599 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000600 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000601
602 if (!disable_stdio)
603 {
604 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
605 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor());
606 }
Chris Lattner24943d22010-06-08 16:52:24 +0000607 }
608 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000609 else
610 {
Johnny Chenc143d622011-08-09 18:56:45 +0000611 if (log)
612 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000613 }
Chris Lattner24943d22010-06-08 16:52:24 +0000614 }
615 else
616 {
617 // Set our user ID to an invalid process ID.
618 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000619 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
620 exe_module->GetFileSpec().GetFilename().AsCString(),
621 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000622 }
Chris Lattner24943d22010-06-08 16:52:24 +0000623 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000624
Chris Lattner24943d22010-06-08 16:52:24 +0000625}
626
627
628Error
Greg Claytone71e2582011-02-04 01:58:07 +0000629ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000630{
631 Error error;
632 // Sleep and wait a bit for debugserver to start to listen...
633 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
634 if (conn_ap.get())
635 {
Chris Lattner24943d22010-06-08 16:52:24 +0000636 const uint32_t max_retry_count = 50;
637 uint32_t retry_count = 0;
638 while (!m_gdb_comm.IsConnected())
639 {
Greg Claytone71e2582011-02-04 01:58:07 +0000640 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000641 {
642 m_gdb_comm.SetConnection (conn_ap.release());
643 break;
644 }
645 retry_count++;
646
647 if (retry_count >= max_retry_count)
648 break;
649
650 usleep (100000);
651 }
652 }
653
654 if (!m_gdb_comm.IsConnected())
655 {
656 if (error.Success())
657 error.SetErrorString("not connected to remote gdb server");
658 return error;
659 }
660
Greg Clayton24bc5d92011-03-30 18:16:51 +0000661 // We always seem to be able to open a connection to a local port
662 // so we need to make sure we can then send data to it. If we can't
663 // then we aren't actually connected to anything, so try and do the
664 // handshake with the remote GDB server and make sure that goes
665 // alright.
666 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000667 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000668 m_gdb_comm.Disconnect();
669 if (error.Success())
670 error.SetErrorString("not connected to remote gdb server");
671 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000672 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000673 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
674 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess,
675 this,
676 m_debugserver_pid,
677 false);
678 m_gdb_comm.ResetDiscoverableSettings();
679 m_gdb_comm.QueryNoAckModeSupported ();
680 m_gdb_comm.GetThreadSuffixSupported ();
681 m_gdb_comm.GetHostInfo ();
682 m_gdb_comm.GetVContSupported ('c');
Chris Lattner24943d22010-06-08 16:52:24 +0000683 return error;
684}
685
686void
687ProcessGDBRemote::DidLaunchOrAttach ()
688{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000689 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
690 if (log)
691 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000692 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000693 {
694 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
695
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000696 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000697
Chris Lattner24943d22010-06-08 16:52:24 +0000698 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000699
Greg Claytoncb8977d2011-03-23 00:09:55 +0000700 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
701 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000702 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000703 ArchSpec &target_arch = GetTarget().GetArchitecture();
704
705 if (target_arch.IsValid())
706 {
707 // If the remote host is ARM and we have apple as the vendor, then
708 // ARM executables and shared libraries can have mixed ARM architectures.
709 // You can have an armv6 executable, and if the host is armv7, then the
710 // system will load the best possible architecture for all shared libraries
711 // it has, so we really need to take the remote host architecture as our
712 // defacto architecture in this case.
713
714 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
715 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
716 {
717 target_arch = gdb_remote_arch;
718 }
719 else
720 {
721 // Fill in what is missing in the triple
722 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
723 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000724 if (target_triple.getVendorName().size() == 0)
725 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000726 target_triple.setVendor (remote_triple.getVendor());
727
Greg Clayton2f085c62011-05-15 01:25:55 +0000728 if (target_triple.getOSName().size() == 0)
729 {
730 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000731
Greg Clayton2f085c62011-05-15 01:25:55 +0000732 if (target_triple.getEnvironmentName().size() == 0)
733 target_triple.setEnvironment (remote_triple.getEnvironment());
734 }
735 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000736 }
737 }
738 else
739 {
740 // The target doesn't have a valid architecture yet, set it from
741 // the architecture we got from the remote GDB server
742 target_arch = gdb_remote_arch;
743 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000744 }
Chris Lattner24943d22010-06-08 16:52:24 +0000745 }
746}
747
748void
749ProcessGDBRemote::DidLaunch ()
750{
751 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000752}
753
754Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000755ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000756{
757 Error error;
758 // Clear out and clean up from any current state
759 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000760 if (attach_pid != LLDB_INVALID_PROCESS_ID)
761 {
Greg Claytona2f74232011-02-24 22:24:29 +0000762 // Make sure we aren't already connected?
763 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000764 {
Greg Claytona2f74232011-02-24 22:24:29 +0000765 char host_port[128];
766 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
767 char connect_url[128];
768 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000769
Greg Claytonb72d0f02011-04-12 05:54:46 +0000770 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000771
772 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000773 {
Greg Claytona2f74232011-02-24 22:24:29 +0000774 const char *error_string = error.AsCString();
775 if (error_string == NULL)
776 error_string = "unable to launch " DEBUGSERVER_BASENAME;
777
778 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000779 }
Greg Claytona2f74232011-02-24 22:24:29 +0000780 else
781 {
782 error = ConnectToDebugserver (connect_url);
783 }
784 }
785
786 if (error.Success())
787 {
788 char packet[64];
789 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid);
790
791 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000792 }
793 }
Chris Lattner24943d22010-06-08 16:52:24 +0000794 return error;
795}
796
797size_t
798ProcessGDBRemote::AttachInputReaderCallback
799(
800 void *baton,
801 InputReader *reader,
802 lldb::InputReaderAction notification,
803 const char *bytes,
804 size_t bytes_len
805)
806{
807 if (notification == eInputReaderGotToken)
808 {
809 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
810 if (gdb_process->m_waiting_for_attach)
811 gdb_process->m_waiting_for_attach = false;
812 reader->SetIsDone(true);
813 return 1;
814 }
815 return 0;
816}
817
818Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000819ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000820{
821 Error error;
822 // Clear out and clean up from any current state
823 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000824
Chris Lattner24943d22010-06-08 16:52:24 +0000825 if (process_name && process_name[0])
826 {
Greg Claytona2f74232011-02-24 22:24:29 +0000827 // Make sure we aren't already connected?
828 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000829 {
Greg Claytona2f74232011-02-24 22:24:29 +0000830 char host_port[128];
831 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
832 char connect_url[128];
833 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
834
Greg Claytonb72d0f02011-04-12 05:54:46 +0000835 error = StartDebugserverProcess (host_port);
Greg Claytona2f74232011-02-24 22:24:29 +0000836 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000837 {
Greg Claytona2f74232011-02-24 22:24:29 +0000838 const char *error_string = error.AsCString();
839 if (error_string == NULL)
840 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +0000841
Greg Claytona2f74232011-02-24 22:24:29 +0000842 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000843 }
Greg Claytona2f74232011-02-24 22:24:29 +0000844 else
845 {
846 error = ConnectToDebugserver (connect_url);
847 }
848 }
849
850 if (error.Success())
851 {
852 StreamString packet;
853
854 if (wait_for_launch)
855 packet.PutCString("vAttachWait");
856 else
857 packet.PutCString("vAttachName");
858 packet.PutChar(';');
859 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
860
861 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
862
Chris Lattner24943d22010-06-08 16:52:24 +0000863 }
864 }
Chris Lattner24943d22010-06-08 16:52:24 +0000865 return error;
866}
867
Chris Lattner24943d22010-06-08 16:52:24 +0000868
869void
870ProcessGDBRemote::DidAttach ()
871{
Greg Claytone71e2582011-02-04 01:58:07 +0000872 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000873}
874
875Error
876ProcessGDBRemote::WillResume ()
877{
Greg Claytonc1f45872011-02-12 06:28:37 +0000878 m_continue_c_tids.clear();
879 m_continue_C_tids.clear();
880 m_continue_s_tids.clear();
881 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000882 return Error();
883}
884
885Error
886ProcessGDBRemote::DoResume ()
887{
Jim Ingham3ae449a2010-11-17 02:32:00 +0000888 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000889 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
890 if (log)
891 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +0000892
893 Listener listener ("gdb-remote.resume-packet-sent");
894 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
895 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000896 StreamString continue_packet;
897 bool continue_packet_error = false;
898 if (m_gdb_comm.HasAnyVContSupport ())
899 {
900 continue_packet.PutCString ("vCont");
901
902 if (!m_continue_c_tids.empty())
903 {
904 if (m_gdb_comm.GetVContSupported ('c'))
905 {
906 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)
907 continue_packet.Printf(";c:%4.4x", *t_pos);
908 }
909 else
910 continue_packet_error = true;
911 }
912
913 if (!continue_packet_error && !m_continue_C_tids.empty())
914 {
915 if (m_gdb_comm.GetVContSupported ('C'))
916 {
917 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)
918 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first);
919 }
920 else
921 continue_packet_error = true;
922 }
Greg Claytonb749a262010-12-03 06:02:24 +0000923
Greg Claytonc1f45872011-02-12 06:28:37 +0000924 if (!continue_packet_error && !m_continue_s_tids.empty())
925 {
926 if (m_gdb_comm.GetVContSupported ('s'))
927 {
928 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)
929 continue_packet.Printf(";s:%4.4x", *t_pos);
930 }
931 else
932 continue_packet_error = true;
933 }
934
935 if (!continue_packet_error && !m_continue_S_tids.empty())
936 {
937 if (m_gdb_comm.GetVContSupported ('S'))
938 {
939 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)
940 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first);
941 }
942 else
943 continue_packet_error = true;
944 }
945
946 if (continue_packet_error)
947 continue_packet.GetString().clear();
948 }
949 else
950 continue_packet_error = true;
951
952 if (continue_packet_error)
953 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000954 // Either no vCont support, or we tried to use part of the vCont
955 // packet that wasn't supported by the remote GDB server.
956 // We need to try and make a simple packet that can do our continue
957 const size_t num_threads = GetThreadList().GetSize();
958 const size_t num_continue_c_tids = m_continue_c_tids.size();
959 const size_t num_continue_C_tids = m_continue_C_tids.size();
960 const size_t num_continue_s_tids = m_continue_s_tids.size();
961 const size_t num_continue_S_tids = m_continue_S_tids.size();
962 if (num_continue_c_tids > 0)
963 {
964 if (num_continue_c_tids == num_threads)
965 {
966 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +0000967 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +0000968 continue_packet.PutChar ('c');
969 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000970 }
971 else if (num_continue_c_tids == 1 &&
972 num_continue_C_tids == 0 &&
973 num_continue_s_tids == 0 &&
974 num_continue_S_tids == 0 )
975 {
976 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +0000977 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +0000978 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +0000979 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +0000980 }
981 }
982
Greg Claytonde1dd812011-06-24 03:21:43 +0000983 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +0000984 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000985 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
986 num_continue_C_tids > 0 &&
987 num_continue_s_tids == 0 &&
988 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +0000989 {
990 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +0000991 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +0000992 if (num_continue_C_tids > 1)
993 {
Greg Claytonde1dd812011-06-24 03:21:43 +0000994 // More that one thread with a signal, yet we don't have
995 // vCont support and we are being asked to resume each
996 // thread with a signal, we need to make sure they are
997 // all the same signal, or we can't issue the continue
998 // accurately with the current support...
999 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001000 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001001 continue_packet_error = false;
1002 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1003 {
1004 if (m_continue_C_tids[i].second != continue_signo)
1005 continue_packet_error = true;
1006 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001007 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001008 if (!continue_packet_error)
1009 m_gdb_comm.SetCurrentThreadForRun (-1);
1010 }
1011 else
1012 {
1013 // Set the continue thread ID
1014 continue_packet_error = false;
1015 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001016 }
1017 if (!continue_packet_error)
1018 {
1019 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001020 continue_packet.Printf("C%2.2x", continue_signo);
1021 }
1022 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001023 }
1024
Greg Claytonde1dd812011-06-24 03:21:43 +00001025 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001026 {
1027 if (num_continue_s_tids == num_threads)
1028 {
1029 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001030 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001031 continue_packet.PutChar ('s');
1032 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001033 }
1034 else if (num_continue_c_tids == 0 &&
1035 num_continue_C_tids == 0 &&
1036 num_continue_s_tids == 1 &&
1037 num_continue_S_tids == 0 )
1038 {
1039 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001040 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001041 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001042 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001043 }
1044 }
1045
1046 if (!continue_packet_error && num_continue_S_tids > 0)
1047 {
1048 if (num_continue_S_tids == num_threads)
1049 {
1050 const int step_signo = m_continue_S_tids.front().second;
1051 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001052 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001053 if (num_continue_S_tids > 1)
1054 {
1055 for (size_t i=1; i<num_threads; ++i)
1056 {
1057 if (m_continue_S_tids[i].second != step_signo)
1058 continue_packet_error = true;
1059 }
1060 }
1061 if (!continue_packet_error)
1062 {
1063 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001064 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001065 continue_packet.Printf("S%2.2x", step_signo);
1066 }
1067 }
1068 else if (num_continue_c_tids == 0 &&
1069 num_continue_C_tids == 0 &&
1070 num_continue_s_tids == 0 &&
1071 num_continue_S_tids == 1 )
1072 {
1073 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001074 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001075 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001076 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001077 }
1078 }
1079 }
1080
1081 if (continue_packet_error)
1082 {
1083 error.SetErrorString ("can't make continue packet for this resume");
1084 }
1085 else
1086 {
1087 EventSP event_sp;
1088 TimeValue timeout;
1089 timeout = TimeValue::Now();
1090 timeout.OffsetWithSeconds (5);
1091 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1092
1093 if (listener.WaitForEvent (&timeout, event_sp) == false)
1094 error.SetErrorString("Resume timed out.");
1095 }
Greg Claytonb749a262010-12-03 06:02:24 +00001096 }
1097
Jim Ingham3ae449a2010-11-17 02:32:00 +00001098 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001099}
1100
Chris Lattner24943d22010-06-08 16:52:24 +00001101uint32_t
Greg Clayton37f962e2011-08-22 02:49:39 +00001102ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001103{
1104 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001105 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001106 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001107 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton37f962e2011-08-22 02:49:39 +00001108 // Update the thread list's stop id immediately so we don't recurse into this function.
Chris Lattner24943d22010-06-08 16:52:24 +00001109
Greg Clayton37f962e2011-08-22 02:49:39 +00001110 std::vector<lldb::tid_t> thread_ids;
1111 bool sequence_mutex_unavailable = false;
1112 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1113 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001114 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001115 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001116 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001117 tid_t tid = thread_ids[i];
1118 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1119 if (!thread_sp)
1120 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1121 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001122 }
Chris Lattner24943d22010-06-08 16:52:24 +00001123 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001124
1125 if (sequence_mutex_unavailable == false)
1126 SetThreadStopInfo (m_last_stop_packet);
1127 return new_thread_list.GetSize(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001128}
1129
1130
1131StateType
1132ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1133{
Greg Clayton261a18b2011-06-02 22:22:38 +00001134 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001135 const char stop_type = stop_packet.GetChar();
1136 switch (stop_type)
1137 {
1138 case 'T':
1139 case 'S':
1140 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001141 if (GetStopID() == 0)
1142 {
1143 // Our first stop, make sure we have a process ID, and also make
1144 // sure we know about our registers
1145 if (GetID() == LLDB_INVALID_PROCESS_ID)
1146 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001147 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001148 if (pid != LLDB_INVALID_PROCESS_ID)
1149 SetID (pid);
1150 }
1151 BuildDynamicRegisterInfo (true);
1152 }
Chris Lattner24943d22010-06-08 16:52:24 +00001153 // Stop with signal and thread info
1154 const uint8_t signo = stop_packet.GetHexU8();
1155 std::string name;
1156 std::string value;
1157 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001158 std::string reason;
1159 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001160 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001161 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001162 uint32_t tid = LLDB_INVALID_THREAD_ID;
1163 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1164 uint32_t exc_data_count = 0;
Greg Claytona875b642011-01-09 21:07:35 +00001165 ThreadSP thread_sp;
1166
Chris Lattner24943d22010-06-08 16:52:24 +00001167 while (stop_packet.GetNameColonValue(name, value))
1168 {
1169 if (name.compare("metype") == 0)
1170 {
1171 // exception type in big endian hex
1172 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1173 }
1174 else if (name.compare("mecount") == 0)
1175 {
1176 // exception count in big endian hex
1177 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16);
1178 }
1179 else if (name.compare("medata") == 0)
1180 {
1181 // exception data in big endian hex
1182 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1183 }
1184 else if (name.compare("thread") == 0)
1185 {
1186 // thread in big endian hex
1187 tid = Args::StringToUInt32 (value.c_str(), 0, 16);
Greg Claytonc3c46612011-02-15 00:19:15 +00001188 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001189 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001190 if (!thread_sp)
1191 {
1192 // Create the thread if we need to
1193 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1194 m_thread_list.AddThread(thread_sp);
1195 }
Chris Lattner24943d22010-06-08 16:52:24 +00001196 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001197 else if (name.compare("hexname") == 0)
1198 {
1199 StringExtractor name_extractor;
1200 // Swap "value" over into "name_extractor"
1201 name_extractor.GetStringRef().swap(value);
1202 // Now convert the HEX bytes into a string value
1203 name_extractor.GetHexByteString (value);
1204 thread_name.swap (value);
1205 }
Chris Lattner24943d22010-06-08 16:52:24 +00001206 else if (name.compare("name") == 0)
1207 {
1208 thread_name.swap (value);
1209 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001210 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001211 {
1212 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1213 }
Greg Clayton65611552011-06-04 01:26:29 +00001214 else if (name.compare("reason") == 0)
1215 {
1216 reason.swap(value);
1217 }
1218 else if (name.compare("description") == 0)
1219 {
1220 StringExtractor desc_extractor;
1221 // Swap "value" over into "name_extractor"
1222 desc_extractor.GetStringRef().swap(value);
1223 // Now convert the HEX bytes into a string value
1224 desc_extractor.GetHexByteString (thread_name);
1225 }
Greg Claytona875b642011-01-09 21:07:35 +00001226 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1227 {
1228 // We have a register number that contains an expedited
1229 // register value. Lets supply this register to our thread
1230 // so it won't have to go and read it.
1231 if (thread_sp)
1232 {
1233 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1234
1235 if (reg != UINT32_MAX)
1236 {
1237 StringExtractor reg_value_extractor;
1238 // Swap "value" over into "reg_value_extractor"
1239 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001240 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1241 {
1242 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1243 name.c_str(),
1244 reg,
1245 reg,
1246 reg_value_extractor.GetStringRef().c_str(),
1247 stop_packet.GetStringRef().c_str());
1248 }
Greg Claytona875b642011-01-09 21:07:35 +00001249 }
1250 }
1251 }
Chris Lattner24943d22010-06-08 16:52:24 +00001252 }
Chris Lattner24943d22010-06-08 16:52:24 +00001253
1254 if (thread_sp)
1255 {
1256 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1257
1258 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001259 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001260 if (exc_type != 0)
1261 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001262 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001263
1264 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1265 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001266 exc_data_size,
1267 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001268 exc_data_size >= 2 ? exc_data[1] : 0,
1269 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001270 }
Greg Clayton65611552011-06-04 01:26:29 +00001271 else
Chris Lattner24943d22010-06-08 16:52:24 +00001272 {
Greg Clayton65611552011-06-04 01:26:29 +00001273 bool handled = false;
1274 if (!reason.empty())
1275 {
1276 if (reason.compare("trace") == 0)
1277 {
1278 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1279 handled = true;
1280 }
1281 else if (reason.compare("breakpoint") == 0)
1282 {
1283 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1284 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1285 if (bp_site_sp)
1286 {
1287 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1288 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1289 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1290 if (bp_site_sp->ValidForThisThread (gdb_thread))
1291 {
1292 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1293 handled = true;
1294 }
1295 }
1296
1297 if (!handled)
1298 {
1299 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1300 }
1301 }
1302 else if (reason.compare("trap") == 0)
1303 {
1304 // Let the trap just use the standard signal stop reason below...
1305 }
1306 else if (reason.compare("watchpoint") == 0)
1307 {
1308 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1309 // TODO: locate the watchpoint somehow...
1310 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1311 handled = true;
1312 }
1313 else if (reason.compare("exception") == 0)
1314 {
1315 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1316 handled = true;
1317 }
1318 }
1319
1320 if (signo)
1321 {
1322 if (signo == SIGTRAP)
1323 {
1324 // Currently we are going to assume SIGTRAP means we are either
1325 // hitting a breakpoint or hardware single stepping.
1326 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
1327 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc);
1328 if (bp_site_sp)
1329 {
1330 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1331 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1332 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1333 if (bp_site_sp->ValidForThisThread (gdb_thread))
1334 {
1335 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1336 handled = true;
1337 }
1338 }
1339 if (!handled)
1340 {
1341 // TODO: check for breakpoint or trap opcode in case there is a hard
1342 // coded software trap
1343 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1344 handled = true;
1345 }
1346 }
1347 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001348 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001349 }
1350 else
1351 {
Greg Clayton643ee732010-08-04 01:40:35 +00001352 StopInfoSP invalid_stop_info_sp;
1353 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001354 }
Greg Clayton65611552011-06-04 01:26:29 +00001355
1356 if (!description.empty())
1357 {
1358 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1359 if (stop_info_sp)
1360 {
1361 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001362 }
Greg Clayton65611552011-06-04 01:26:29 +00001363 else
1364 {
1365 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1366 }
1367 }
1368 }
Chris Lattner24943d22010-06-08 16:52:24 +00001369 }
1370 return eStateStopped;
1371 }
1372 break;
1373
1374 case 'W':
1375 // process exited
1376 return eStateExited;
1377
1378 default:
1379 break;
1380 }
1381 return eStateInvalid;
1382}
1383
1384void
1385ProcessGDBRemote::RefreshStateAfterStop ()
1386{
Chris Lattner24943d22010-06-08 16:52:24 +00001387 // Let all threads recover from stopping and do any clean up based
1388 // on the previous thread state (if any).
1389 m_thread_list.RefreshStateAfterStop();
Greg Clayton261a18b2011-06-02 22:22:38 +00001390 SetThreadStopInfo (m_last_stop_packet);
Chris Lattner24943d22010-06-08 16:52:24 +00001391}
1392
1393Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001394ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001395{
1396 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001397
Greg Claytona4881d02011-01-22 07:12:45 +00001398 bool timed_out = false;
1399 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001400
1401 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001402 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001403 // We are being asked to halt during an attach. We need to just close
1404 // our file handle and debugserver will go away, and we can be done...
1405 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001406 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001407 else
1408 {
1409 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
1410 {
1411 if (timed_out)
1412 error.SetErrorString("timed out sending interrupt packet");
1413 else
1414 error.SetErrorString("unknown error sending interrupt packet");
1415 }
1416 }
Chris Lattner24943d22010-06-08 16:52:24 +00001417 return error;
1418}
1419
1420Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001421ProcessGDBRemote::InterruptIfRunning
1422(
1423 bool discard_thread_plans,
1424 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001425 EventSP &stop_event_sp
1426)
Chris Lattner24943d22010-06-08 16:52:24 +00001427{
1428 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001429
Greg Clayton2860ba92011-01-23 19:58:49 +00001430 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1431
Greg Clayton68ca8232011-01-25 02:58:48 +00001432 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001433 const bool is_running = m_gdb_comm.IsRunning();
1434 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001435 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001436 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001437 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001438 is_running);
1439
Greg Clayton2860ba92011-01-23 19:58:49 +00001440 if (discard_thread_plans)
1441 {
1442 if (log)
1443 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1444 m_thread_list.DiscardThreadPlans();
1445 }
1446 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001447 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001448 if (catch_stop_event)
1449 {
1450 if (log)
1451 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1452 PausePrivateStateThread();
1453 paused_private_state_thread = true;
1454 }
1455
Greg Clayton4fb400f2010-09-27 21:07:38 +00001456 bool timed_out = false;
Greg Claytona4881d02011-01-22 07:12:45 +00001457 bool sent_interrupt = false;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001458 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001459
Greg Clayton72e1c782011-01-22 23:43:18 +00001460 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001461 {
1462 if (timed_out)
1463 error.SetErrorString("timed out sending interrupt packet");
1464 else
1465 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001466 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001467 ResumePrivateStateThread();
1468 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001469 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001470
Greg Clayton72e1c782011-01-22 23:43:18 +00001471 if (catch_stop_event)
1472 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001473 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001474 TimeValue timeout_time;
1475 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001476 timeout_time.OffsetWithSeconds(5);
1477 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001478
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001479 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001480 if (log)
1481 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001482
Greg Clayton2860ba92011-01-23 19:58:49 +00001483 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001484 error.SetErrorString("unable to verify target stopped");
1485 }
1486
Greg Clayton68ca8232011-01-25 02:58:48 +00001487 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001488 {
1489 if (log)
1490 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001491 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001492 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001493 }
Chris Lattner24943d22010-06-08 16:52:24 +00001494 return error;
1495}
1496
Greg Clayton4fb400f2010-09-27 21:07:38 +00001497Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001498ProcessGDBRemote::WillDetach ()
1499{
Greg Clayton2860ba92011-01-23 19:58:49 +00001500 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1501 if (log)
1502 log->Printf ("ProcessGDBRemote::WillDetach()");
1503
Greg Clayton72e1c782011-01-22 23:43:18 +00001504 bool discard_thread_plans = true;
1505 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001506 EventSP event_sp;
Greg Clayton68ca8232011-01-25 02:58:48 +00001507 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001508}
1509
1510Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001511ProcessGDBRemote::DoDetach()
1512{
1513 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001514 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001515 if (log)
1516 log->Printf ("ProcessGDBRemote::DoDetach()");
1517
1518 DisableAllBreakpointSites ();
1519
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001520 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001521
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001522 size_t response_size = m_gdb_comm.SendPacket ("D", 1);
1523 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001524 {
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001525 if (response_size)
1526 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1527 else
1528 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001529 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001530 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001531 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001532
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001533 SetPrivateState (eStateDetached);
1534 ResumePrivateStateThread();
1535
1536 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001537 return error;
1538}
Chris Lattner24943d22010-06-08 16:52:24 +00001539
1540Error
1541ProcessGDBRemote::DoDestroy ()
1542{
1543 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001544 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001545 if (log)
1546 log->Printf ("ProcessGDBRemote::DoDestroy()");
1547
1548 // Interrupt if our inferior is running...
Greg Claytona4881d02011-01-22 07:12:45 +00001549 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001550 {
Jim Ingham8226e942011-10-28 01:11:35 +00001551 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001552 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001553
1554 StringExtractorGDBRemote response;
1555 bool send_async = true;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001556 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001557 {
1558 char packet_cmd = response.GetChar(0);
1559
1560 if (packet_cmd == 'W' || packet_cmd == 'X')
1561 {
1562 m_last_stop_packet = response;
1563 SetExitStatus(response.GetHexU8(), NULL);
1564 }
1565 }
1566 else
1567 {
1568 SetExitStatus(SIGABRT, NULL);
1569 //error.SetErrorString("kill packet failed");
1570 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001571 }
1572 }
Chris Lattner24943d22010-06-08 16:52:24 +00001573 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001574 KillDebugserverProcess ();
1575 return error;
1576}
1577
Chris Lattner24943d22010-06-08 16:52:24 +00001578//------------------------------------------------------------------
1579// Process Queries
1580//------------------------------------------------------------------
1581
1582bool
1583ProcessGDBRemote::IsAlive ()
1584{
Greg Clayton58e844b2010-12-08 05:08:21 +00001585 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001586}
1587
1588addr_t
1589ProcessGDBRemote::GetImageInfoAddress()
1590{
1591 if (!m_gdb_comm.IsRunning())
1592 {
1593 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001594 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001595 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001596 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001597 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1598 }
1599 }
1600 return LLDB_INVALID_ADDRESS;
1601}
1602
Chris Lattner24943d22010-06-08 16:52:24 +00001603//------------------------------------------------------------------
1604// Process Memory
1605//------------------------------------------------------------------
1606size_t
1607ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1608{
1609 if (size > m_max_memory_size)
1610 {
1611 // Keep memory read sizes down to a sane limit. This function will be
1612 // called multiple times in order to complete the task by
1613 // lldb_private::Process so it is ok to do this.
1614 size = m_max_memory_size;
1615 }
1616
1617 char packet[64];
1618 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size);
1619 assert (packet_len + 1 < sizeof(packet));
1620 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001621 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001622 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001623 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001624 {
1625 error.Clear();
1626 return response.GetHexBytes(buf, size, '\xdd');
1627 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001628 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001629 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001630 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001631 error.SetErrorStringWithFormat("'%s' packet unsupported", packet);
1632 else
1633 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str());
1634 }
1635 else
1636 {
1637 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1638 }
1639 return 0;
1640}
1641
1642size_t
1643ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1644{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001645 if (size > m_max_memory_size)
1646 {
1647 // Keep memory read sizes down to a sane limit. This function will be
1648 // called multiple times in order to complete the task by
1649 // lldb_private::Process so it is ok to do this.
1650 size = m_max_memory_size;
1651 }
1652
Chris Lattner24943d22010-06-08 16:52:24 +00001653 StreamString packet;
1654 packet.Printf("M%llx,%zx:", addr, size);
Greg Claytoncd548032011-02-01 01:31:41 +00001655 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00001656 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001657 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00001658 {
Greg Clayton61d043b2011-03-22 04:00:09 +00001659 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001660 {
1661 error.Clear();
1662 return size;
1663 }
Greg Clayton61d043b2011-03-22 04:00:09 +00001664 else if (response.IsErrorResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001665 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str());
Greg Clayton61d043b2011-03-22 04:00:09 +00001666 else if (response.IsUnsupportedResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00001667 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str());
1668 else
1669 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
1670 }
1671 else
1672 {
1673 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1674 }
1675 return 0;
1676}
1677
1678lldb::addr_t
1679ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1680{
Greg Clayton989816b2011-05-14 01:50:35 +00001681 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1682
Greg Clayton2f085c62011-05-15 01:25:55 +00001683 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00001684 switch (supported)
1685 {
1686 case eLazyBoolCalculate:
1687 case eLazyBoolYes:
1688 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1689 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1690 return allocated_addr;
1691
1692 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001693 // Call mmap() to create memory in the inferior..
1694 unsigned prot = 0;
1695 if (permissions & lldb::ePermissionsReadable)
1696 prot |= eMmapProtRead;
1697 if (permissions & lldb::ePermissionsWritable)
1698 prot |= eMmapProtWrite;
1699 if (permissions & lldb::ePermissionsExecutable)
1700 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00001701
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001702 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
1703 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
1704 m_addr_to_mmap_size[allocated_addr] = size;
1705 else
1706 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00001707 break;
1708 }
1709
Chris Lattner24943d22010-06-08 16:52:24 +00001710 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton613b8732011-05-17 03:37:42 +00001711 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00001712 else
1713 error.Clear();
1714 return allocated_addr;
1715}
1716
1717Error
1718ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
1719{
1720 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00001721 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
1722
1723 switch (supported)
1724 {
1725 case eLazyBoolCalculate:
1726 // We should never be deallocating memory without allocating memory
1727 // first so we should never get eLazyBoolCalculate
1728 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
1729 break;
1730
1731 case eLazyBoolYes:
1732 if (!m_gdb_comm.DeallocateMemory (addr))
1733 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
1734 break;
1735
1736 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001737 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00001738 {
1739 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00001740 if (pos != m_addr_to_mmap_size.end() &&
1741 InferiorCallMunmap(this, addr, pos->second))
1742 m_addr_to_mmap_size.erase (pos);
1743 else
1744 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00001745 }
1746 break;
1747 }
1748
Chris Lattner24943d22010-06-08 16:52:24 +00001749 return error;
1750}
1751
1752
1753//------------------------------------------------------------------
1754// Process STDIO
1755//------------------------------------------------------------------
1756
1757size_t
1758ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error)
1759{
1760 Mutex::Locker locker(m_stdio_mutex);
1761 size_t bytes_available = m_stdout_data.size();
1762 if (bytes_available > 0)
1763 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001764 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1765 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001766 log->Printf ("ProcessGDBRemote::%s (&%p[%lu]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001767 if (bytes_available > buf_size)
1768 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001769 memcpy(buf, m_stdout_data.c_str(), buf_size);
Chris Lattner24943d22010-06-08 16:52:24 +00001770 m_stdout_data.erase(0, buf_size);
1771 bytes_available = buf_size;
1772 }
1773 else
1774 {
Greg Clayton53d68e72010-07-20 22:52:08 +00001775 memcpy(buf, m_stdout_data.c_str(), bytes_available);
Chris Lattner24943d22010-06-08 16:52:24 +00001776 m_stdout_data.clear();
1777
1778 //ResetEventBits(eBroadcastBitSTDOUT);
1779 }
1780 }
1781 return bytes_available;
1782}
1783
1784size_t
1785ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error)
1786{
1787 // Can we get STDERR through the remote protocol?
1788 return 0;
1789}
1790
1791size_t
1792ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
1793{
1794 if (m_stdio_communication.IsConnected())
1795 {
1796 ConnectionStatus status;
1797 m_stdio_communication.Write(src, src_len, status, NULL);
1798 }
1799 return 0;
1800}
1801
1802Error
1803ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
1804{
1805 Error error;
1806 assert (bp_site != NULL);
1807
Greg Claytone005f2c2010-11-06 01:53:30 +00001808 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001809 user_id_t site_id = bp_site->GetID();
1810 const addr_t addr = bp_site->GetLoadAddress();
1811 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001812 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001813
1814 if (bp_site->IsEnabled())
1815 {
1816 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001817 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 +00001818 return error;
1819 }
1820 else
1821 {
1822 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1823
1824 if (bp_site->HardwarePreferred())
1825 {
1826 // Try and set hardware breakpoint, and if that fails, fall through
1827 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00001828 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00001829 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001830 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001831 {
1832 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00001833 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00001834 return error;
1835 }
Chris Lattner24943d22010-06-08 16:52:24 +00001836 }
1837 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001838
1839 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00001840 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001841 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
1842 {
1843 bp_site->SetEnabled(true);
1844 bp_site->SetType (BreakpointSite::eExternal);
1845 return error;
1846 }
Chris Lattner24943d22010-06-08 16:52:24 +00001847 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001848
1849 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00001850 }
1851
1852 if (log)
1853 {
1854 const char *err_string = error.AsCString();
1855 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
1856 bp_site->GetLoadAddress(),
1857 err_string ? err_string : "NULL");
1858 }
1859 // We shouldn't reach here on a successful breakpoint enable...
1860 if (error.Success())
1861 error.SetErrorToGenericError();
1862 return error;
1863}
1864
1865Error
1866ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
1867{
1868 Error error;
1869 assert (bp_site != NULL);
1870 addr_t addr = bp_site->GetLoadAddress();
1871 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00001872 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001873 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001874 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001875
1876 if (bp_site->IsEnabled())
1877 {
1878 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
1879
Greg Claytonb72d0f02011-04-12 05:54:46 +00001880 BreakpointSite::Type bp_type = bp_site->GetType();
1881 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00001882 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00001883 case BreakpointSite::eSoftware:
1884 error = DisableSoftwareBreakpoint (bp_site);
1885 break;
1886
1887 case BreakpointSite::eHardware:
1888 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1889 error.SetErrorToGenericError();
1890 break;
1891
1892 case BreakpointSite::eExternal:
1893 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
1894 error.SetErrorToGenericError();
1895 break;
Chris Lattner24943d22010-06-08 16:52:24 +00001896 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001897 if (error.Success())
1898 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00001899 }
1900 else
1901 {
1902 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001903 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 +00001904 return error;
1905 }
1906
1907 if (error.Success())
1908 error.SetErrorToGenericError();
1909 return error;
1910}
1911
Johnny Chen21900fb2011-09-06 22:38:36 +00001912// Pre-requisite: wp != NULL.
1913static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00001914GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00001915{
1916 assert(wp);
1917 bool watch_read = wp->WatchpointRead();
1918 bool watch_write = wp->WatchpointWrite();
1919
1920 // watch_read and watch_write cannot both be false.
1921 assert(watch_read || watch_write);
1922 if (watch_read && watch_write)
1923 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00001924 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00001925 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00001926 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00001927 return eWatchpointWrite;
1928}
1929
Chris Lattner24943d22010-06-08 16:52:24 +00001930Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001931ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001932{
1933 Error error;
1934 if (wp)
1935 {
1936 user_id_t watchID = wp->GetID();
1937 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00001938 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001939 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001940 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00001941 if (wp->IsEnabled())
1942 {
1943 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001944 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001945 return error;
1946 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001947
1948 GDBStoppointType type = GetGDBStoppointType(wp);
1949 // Pass down an appropriate z/Z packet...
1950 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00001951 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001952 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
1953 {
1954 wp->SetEnabled(true);
1955 return error;
1956 }
1957 else
1958 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00001959 }
Johnny Chen21900fb2011-09-06 22:38:36 +00001960 else
1961 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00001962 }
1963 else
1964 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00001965 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00001966 }
1967 if (error.Success())
1968 error.SetErrorToGenericError();
1969 return error;
1970}
1971
1972Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00001973ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00001974{
1975 Error error;
1976 if (wp)
1977 {
1978 user_id_t watchID = wp->GetID();
1979
Greg Claytone005f2c2010-11-06 01:53:30 +00001980 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001981
1982 addr_t addr = wp->GetLoadAddress();
1983 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001984 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001985
Johnny Chen21900fb2011-09-06 22:38:36 +00001986 if (!wp->IsEnabled())
1987 {
1988 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001989 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen21900fb2011-09-06 22:38:36 +00001990 return error;
1991 }
1992
Chris Lattner24943d22010-06-08 16:52:24 +00001993 if (wp->IsHardware())
1994 {
Johnny Chen21900fb2011-09-06 22:38:36 +00001995 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00001996 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00001997 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
1998 {
1999 wp->SetEnabled(false);
2000 return error;
2001 }
2002 else
2003 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002004 }
2005 // TODO: clear software watchpoints if we implement them
2006 }
2007 else
2008 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002009 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002010 }
2011 if (error.Success())
2012 error.SetErrorToGenericError();
2013 return error;
2014}
2015
2016void
2017ProcessGDBRemote::Clear()
2018{
2019 m_flags = 0;
2020 m_thread_list.Clear();
2021 {
2022 Mutex::Locker locker(m_stdio_mutex);
2023 m_stdout_data.clear();
2024 }
Chris Lattner24943d22010-06-08 16:52:24 +00002025}
2026
2027Error
2028ProcessGDBRemote::DoSignal (int signo)
2029{
2030 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002031 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002032 if (log)
2033 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2034
2035 if (!m_gdb_comm.SendAsyncSignal (signo))
2036 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2037 return error;
2038}
2039
Chris Lattner24943d22010-06-08 16:52:24 +00002040Error
Greg Claytonb72d0f02011-04-12 05:54:46 +00002041ProcessGDBRemote::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 +00002042{
2043 Error error;
2044 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2045 {
2046 // If we locate debugserver, keep that located version around
2047 static FileSpec g_debugserver_file_spec;
2048
Greg Claytonb72d0f02011-04-12 05:54:46 +00002049 ProcessLaunchInfo launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002050 char debugserver_path[PATH_MAX];
Greg Claytonb72d0f02011-04-12 05:54:46 +00002051 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002052
2053 // Always check to see if we have an environment override for the path
2054 // to the debugserver to use and use it if we do.
2055 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2056 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002057 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002058 else
2059 debugserver_file_spec = g_debugserver_file_spec;
2060 bool debugserver_exists = debugserver_file_spec.Exists();
2061 if (!debugserver_exists)
2062 {
2063 // The debugserver binary is in the LLDB.framework/Resources
2064 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002065 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002066 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002067 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002068 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002069 if (debugserver_exists)
2070 {
2071 g_debugserver_file_spec = debugserver_file_spec;
2072 }
2073 else
2074 {
2075 g_debugserver_file_spec.Clear();
2076 debugserver_file_spec.Clear();
2077 }
Chris Lattner24943d22010-06-08 16:52:24 +00002078 }
2079 }
2080
2081 if (debugserver_exists)
2082 {
2083 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2084
2085 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002086
Greg Claytone005f2c2010-11-06 01:53:30 +00002087 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002088
Greg Claytonb72d0f02011-04-12 05:54:46 +00002089 Args &debugserver_args = launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002090 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002091
Chris Lattner24943d22010-06-08 16:52:24 +00002092 // Start args with "debugserver /file/path -r --"
2093 debugserver_args.AppendArgument(debugserver_path);
2094 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002095 // use native registers, not the GDB registers
2096 debugserver_args.AppendArgument("--native-regs");
2097 // make debugserver run in its own session so signals generated by
2098 // special terminal key sequences (^C) don't affect debugserver
2099 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002100
Chris Lattner24943d22010-06-08 16:52:24 +00002101 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2102 if (env_debugserver_log_file)
2103 {
2104 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2105 debugserver_args.AppendArgument(arg_cstr);
2106 }
2107
2108 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2109 if (env_debugserver_log_flags)
2110 {
2111 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2112 debugserver_args.AppendArgument(arg_cstr);
2113 }
Greg Claytoncc3e6402011-01-25 06:55:13 +00002114// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002115// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002116
Greg Claytonb72d0f02011-04-12 05:54:46 +00002117 // We currently send down all arguments, attach pids, or attach
2118 // process names in dedicated GDB server packets, so we don't need
2119 // to pass them as arguments. This is currently because of all the
2120 // things we need to setup prior to launching: the environment,
2121 // current working dir, file actions, etc.
2122#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002123 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002124 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002125 {
Greg Claytona2f74232011-02-24 22:24:29 +00002126 // Terminate the debugserver args so we can now append the inferior args
2127 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002128
Greg Claytona2f74232011-02-24 22:24:29 +00002129 for (int i = 0; inferior_argv[i] != NULL; ++i)
2130 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002131 }
2132 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2133 {
2134 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2135 debugserver_args.AppendArgument (arg_cstr);
2136 }
2137 else if (attach_name && attach_name[0])
2138 {
2139 if (wait_for_launch)
2140 debugserver_args.AppendArgument ("--waitfor");
2141 else
2142 debugserver_args.AppendArgument ("--attach");
2143 debugserver_args.AppendArgument (attach_name);
2144 }
Chris Lattner24943d22010-06-08 16:52:24 +00002145#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002146
2147 ProcessLaunchInfo::FileAction file_action;
2148
2149 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2150 // to "/dev/null" if we run into any problems.
2151 file_action.Close (STDIN_FILENO);
2152 launch_info.AppendFileAction (file_action);
2153 file_action.Close (STDOUT_FILENO);
2154 launch_info.AppendFileAction (file_action);
2155 file_action.Close (STDERR_FILENO);
2156 launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002157
2158 if (log)
2159 {
2160 StreamString strm;
2161 debugserver_args.Dump (&strm);
2162 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2163 }
2164
Greg Claytonb72d0f02011-04-12 05:54:46 +00002165 error = Host::LaunchProcess(launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002166
Greg Claytonb72d0f02011-04-12 05:54:46 +00002167 if (error.Success ())
2168 m_debugserver_pid = launch_info.GetProcessID();
2169 else
Chris Lattner24943d22010-06-08 16:52:24 +00002170 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2171
2172 if (error.Fail() || log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002173 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002174 }
2175 else
2176 {
Greg Clayton9c236732011-10-26 00:56:27 +00002177 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002178 }
2179
2180 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2181 StartAsyncThread ();
2182 }
2183 return error;
2184}
2185
2186bool
2187ProcessGDBRemote::MonitorDebugserverProcess
2188(
2189 void *callback_baton,
2190 lldb::pid_t debugserver_pid,
2191 int signo, // Zero for no signal
2192 int exit_status // Exit value of process if signal is zero
2193)
2194{
2195 // We pass in the ProcessGDBRemote inferior process it and name it
2196 // "gdb_remote_pid". The process ID is passed in the "callback_baton"
2197 // pointer value itself, thus we need the double cast...
2198
2199 // "debugserver_pid" argument passed in is the process ID for
2200 // debugserver that we are tracking...
2201
Greg Clayton75ccf502010-08-21 02:22:51 +00002202 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002203
2204 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2205 if (log)
2206 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2207
Greg Clayton75ccf502010-08-21 02:22:51 +00002208 if (process)
Chris Lattner24943d22010-06-08 16:52:24 +00002209 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002210 // Sleep for a half a second to make sure our inferior process has
2211 // time to set its exit status before we set it incorrectly when
2212 // both the debugserver and the inferior process shut down.
2213 usleep (500000);
2214 // If our process hasn't yet exited, debugserver might have died.
2215 // If the process did exit, the we are reaping it.
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002216 const StateType state = process->GetState();
2217
2218 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2219 state != eStateInvalid &&
2220 state != eStateUnloaded &&
2221 state != eStateExited &&
2222 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002223 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002224 char error_str[1024];
2225 if (signo)
Chris Lattner24943d22010-06-08 16:52:24 +00002226 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002227 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2228 if (signal_cstr)
2229 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002230 else
Greg Clayton75ccf502010-08-21 02:22:51 +00002231 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Chris Lattner24943d22010-06-08 16:52:24 +00002232 }
2233 else
2234 {
Greg Clayton75ccf502010-08-21 02:22:51 +00002235 ::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 +00002236 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002237
2238 process->SetExitStatus (-1, error_str);
2239 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002240 // Debugserver has exited we need to let our ProcessGDBRemote
2241 // know that it no longer has a debugserver instance
2242 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2243 // We are returning true to this function below, so we can
2244 // forget about the monitor handle.
2245 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002246 }
2247 return true;
2248}
2249
2250void
2251ProcessGDBRemote::KillDebugserverProcess ()
2252{
2253 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2254 {
2255 ::kill (m_debugserver_pid, SIGINT);
2256 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2257 }
2258}
2259
2260void
2261ProcessGDBRemote::Initialize()
2262{
2263 static bool g_initialized = false;
2264
2265 if (g_initialized == false)
2266 {
2267 g_initialized = true;
2268 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2269 GetPluginDescriptionStatic(),
2270 CreateInstance);
2271
2272 Log::Callbacks log_callbacks = {
2273 ProcessGDBRemoteLog::DisableLog,
2274 ProcessGDBRemoteLog::EnableLog,
2275 ProcessGDBRemoteLog::ListLogCategories
2276 };
2277
2278 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2279 }
2280}
2281
2282bool
Chris Lattner24943d22010-06-08 16:52:24 +00002283ProcessGDBRemote::StartAsyncThread ()
2284{
Greg Claytone005f2c2010-11-06 01:53:30 +00002285 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002286
2287 if (log)
2288 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2289
2290 // Create a thread that watches our internal state and controls which
2291 // events make it to clients (into the DCProcess event queue).
2292 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002293 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002294}
2295
2296void
2297ProcessGDBRemote::StopAsyncThread ()
2298{
Greg Claytone005f2c2010-11-06 01:53:30 +00002299 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002300
2301 if (log)
2302 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2303
2304 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002305
2306 // This will shut down the async thread.
2307 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002308
2309 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002310 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002311 {
2312 Host::ThreadJoin (m_async_thread, NULL, NULL);
2313 }
2314}
2315
2316
2317void *
2318ProcessGDBRemote::AsyncThread (void *arg)
2319{
2320 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2321
Greg Claytone005f2c2010-11-06 01:53:30 +00002322 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002323 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002324 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002325
2326 Listener listener ("ProcessGDBRemote::AsyncThread");
2327 EventSP event_sp;
2328 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2329 eBroadcastBitAsyncThreadShouldExit;
2330
2331 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2332 {
Greg Claytona2f74232011-02-24 22:24:29 +00002333 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2334
Chris Lattner24943d22010-06-08 16:52:24 +00002335 bool done = false;
2336 while (!done)
2337 {
2338 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002339 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002340 if (listener.WaitForEvent (NULL, event_sp))
2341 {
2342 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002343 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002344 {
Greg Claytona2f74232011-02-24 22:24:29 +00002345 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002346 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 +00002347
Greg Claytona2f74232011-02-24 22:24:29 +00002348 switch (event_type)
2349 {
2350 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002351 {
Greg Claytona2f74232011-02-24 22:24:29 +00002352 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002353
Greg Claytona2f74232011-02-24 22:24:29 +00002354 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002355 {
Greg Claytona2f74232011-02-24 22:24:29 +00002356 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2357 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2358 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002359 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002360
Greg Claytona2f74232011-02-24 22:24:29 +00002361 if (::strstr (continue_cstr, "vAttach") == NULL)
2362 process->SetPrivateState(eStateRunning);
2363 StringExtractorGDBRemote response;
2364 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002365
Greg Claytona2f74232011-02-24 22:24:29 +00002366 switch (stop_state)
2367 {
2368 case eStateStopped:
2369 case eStateCrashed:
2370 case eStateSuspended:
2371 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002372 process->SetPrivateState (stop_state);
2373 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002374
Greg Claytona2f74232011-02-24 22:24:29 +00002375 case eStateExited:
2376 process->m_last_stop_packet = response;
Greg Claytona2f74232011-02-24 22:24:29 +00002377 response.SetFilePos(1);
2378 process->SetExitStatus(response.GetHexU8(), NULL);
2379 done = true;
2380 break;
2381
2382 case eStateInvalid:
2383 process->SetExitStatus(-1, "lost connection");
2384 break;
2385
2386 default:
2387 process->SetPrivateState (stop_state);
2388 break;
2389 }
Chris Lattner24943d22010-06-08 16:52:24 +00002390 }
2391 }
Greg Claytona2f74232011-02-24 22:24:29 +00002392 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002393
Greg Claytona2f74232011-02-24 22:24:29 +00002394 case eBroadcastBitAsyncThreadShouldExit:
2395 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002396 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002397 done = true;
2398 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002399
Greg Claytona2f74232011-02-24 22:24:29 +00002400 default:
2401 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002402 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 +00002403 done = true;
2404 break;
2405 }
2406 }
2407 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2408 {
2409 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2410 {
2411 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002412 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002413 }
Chris Lattner24943d22010-06-08 16:52:24 +00002414 }
2415 }
2416 else
2417 {
2418 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002419 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 +00002420 done = true;
2421 }
2422 }
2423 }
2424
2425 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002426 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002427
2428 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2429 return NULL;
2430}
2431
Chris Lattner24943d22010-06-08 16:52:24 +00002432const char *
2433ProcessGDBRemote::GetDispatchQueueNameForThread
2434(
2435 addr_t thread_dispatch_qaddr,
2436 std::string &dispatch_queue_name
2437)
2438{
2439 dispatch_queue_name.clear();
2440 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2441 {
2442 // Cache the dispatch_queue_offsets_addr value so we don't always have
2443 // to look it up
2444 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2445 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002446 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2447 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002448 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002449 if (module_sp)
2450 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2451
2452 if (dispatch_queue_offsets_symbol == NULL)
2453 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002454 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002455 if (module_sp)
2456 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2457 }
Chris Lattner24943d22010-06-08 16:52:24 +00002458 if (dispatch_queue_offsets_symbol)
Greg Claytoneea26402010-09-14 23:36:40 +00002459 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002460
2461 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2462 return NULL;
2463 }
2464
2465 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002466 DataExtractor data (memory_buffer,
2467 sizeof(memory_buffer),
2468 m_target.GetArchitecture().GetByteOrder(),
2469 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002470
2471 // Excerpt from src/queue_private.h
2472 struct dispatch_queue_offsets_s
2473 {
2474 uint16_t dqo_version;
2475 uint16_t dqo_label;
2476 uint16_t dqo_label_size;
2477 } dispatch_queue_offsets;
2478
2479
2480 Error error;
2481 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2482 {
2483 uint32_t data_offset = 0;
2484 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2485 {
2486 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2487 {
2488 data_offset = 0;
2489 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2490 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2491 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2492 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2493 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2494 dispatch_queue_name.erase (bytes_read);
2495 }
2496 }
2497 }
2498 }
2499 if (dispatch_queue_name.empty())
2500 return NULL;
2501 return dispatch_queue_name.c_str();
2502}
2503
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002504//uint32_t
2505//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2506//{
2507// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2508// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2509// if (m_local_debugserver)
2510// {
2511// return Host::ListProcessesMatchingName (name, matches, pids);
2512// }
2513// else
2514// {
2515// // FIXME: Implement talking to the remote debugserver.
2516// return 0;
2517// }
2518//
2519//}
2520//
Jim Ingham55e01d82011-01-22 01:33:44 +00002521bool
2522ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2523 lldb_private::StoppointCallbackContext *context,
2524 lldb::user_id_t break_id,
2525 lldb::user_id_t break_loc_id)
2526{
2527 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2528 // run so I can stop it if that's what I want to do.
2529 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2530 if (log)
2531 log->Printf("Hit New Thread Notification breakpoint.");
2532 return false;
2533}
2534
2535
2536bool
2537ProcessGDBRemote::StartNoticingNewThreads()
2538{
2539 static const char *bp_names[] =
2540 {
2541 "start_wqthread",
Jim Inghamff276fe2011-02-08 05:19:01 +00002542 "_pthread_wqthread",
Jim Ingham55e01d82011-01-22 01:33:44 +00002543 "_pthread_start",
2544 NULL
2545 };
2546
2547 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2548 size_t num_bps = m_thread_observation_bps.size();
2549 if (num_bps != 0)
2550 {
2551 for (int i = 0; i < num_bps; i++)
2552 {
2553 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2554 if (break_sp)
2555 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002556 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002557 log->Printf("Enabled noticing new thread breakpoint.");
2558 break_sp->SetEnabled(true);
2559 }
2560 }
2561 }
2562 else
2563 {
2564 for (int i = 0; bp_names[i] != NULL; i++)
2565 {
Jim Inghamd6d47972011-09-23 00:54:11 +00002566 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get();
Jim Ingham55e01d82011-01-22 01:33:44 +00002567 if (breakpoint)
2568 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002569 if (log && log->GetVerbose())
Jim Ingham55e01d82011-01-22 01:33:44 +00002570 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]);
2571 m_thread_observation_bps.push_back(breakpoint->GetID());
2572 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
2573 }
2574 else
2575 {
2576 if (log)
2577 log->Printf("Failed to create new thread notification breakpoint.");
2578 return false;
2579 }
2580 }
2581 }
2582
2583 return true;
2584}
2585
2586bool
2587ProcessGDBRemote::StopNoticingNewThreads()
2588{
Jim Inghamff276fe2011-02-08 05:19:01 +00002589 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00002590 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00002591 log->Printf ("Disabling new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002592 size_t num_bps = m_thread_observation_bps.size();
2593 if (num_bps != 0)
2594 {
2595 for (int i = 0; i < num_bps; i++)
2596 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002597
2598 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]);
2599 if (break_sp)
2600 {
Jim Ingham55e01d82011-01-22 01:33:44 +00002601 break_sp->SetEnabled(false);
2602 }
2603 }
2604 }
2605 return true;
2606}
2607
2608